Giter Club home page Giter Club logo

orm-js's Introduction

orm-js

Note: this module is still in the early alpha phase and still very experimental. Support for JavaScript (i.e., not using TypeScript) isn't provided yet.

This module allows you to map your entity classes, as written in JavaScript or TypeScript, to a database schema, using decorators. Support for SQLite is available through the separate module orm-js-sqlite, support for other databases is planned.

orm-js is designed to work with JavaScript Promise. It's suitable to work with async/await in TypeScript.

Introduction

Many web applications consist of code (such as JavaScript) and data stored in a database system (such as MySQL, SQLite). orm-js provides you some abstraction in order to save your data object to the database or retieve the data mapped back to an object. It also takes care for the database creation and the relations between the various tables (entities).

Take a look at the following code snippet:

import * as orm from 'orm-js/decorators';


@orm.entity() // mark the following class as an entity
export default class User {
  @orm.field()
  @orm.id()
  id: number;
  
  @orm.field()
  userName: string;
  
  @orm.field()
  emailAddress: string;
  
  @orm.field()
  passwordHash: string;
}

The entity name (User) as well as the property names and types are automatically determined by orm-js, you don't need to take care of the naming (unless you have two entities with the same name).

Properties missing the @orm.field() decorator will not be saved to the database, the field won't be created in the schema. You can optionally use @orm.id() for a single field to mark it as the primary key, which is used to uniquely identify a single data record.

You can declare your entities in several JavaScript or TypeScript files or put several of them in a single file. It's your responsibility to load all these files in order to use the orm-js system. For example, you can put all your entity files in a single directory, which you can scan for files to require(). In this example, a simple require('./user') is enough to tell orm-js about this entity (because of the @orm.entity() decorator).

After you've loaded all your entities, you can connect to your database and use orm-js.

Database Connection

orm-js itself does not provide connection to a database. Currently there's only orm-js-sqlite available. Before you can use orm-js (you may load your entities before, however), you have to bind a database connection:

import * as orm from 'orm-js/orm';
import SqliteDatabase from 'orm-js-sqlite';

let connection = new SqliteDatabase('database.db');
orm.setDatabase(connection);

(async () => {
  try {
    await orm.connect();
    console.log('Database is connected!');
  } catch(err) {
    console.error(err);
  }
})();

Schema Creation

The database schema (the tables, fields, relations etc.) is managed by orm-js, you usually can't use any existing schema. After you've loaded your entities and connected to your database, you use build() to create a new database schema:

import * as orm from 'orm-js/orm';

(async () => {
  try {
    await orm.build();
    console.log('Schema created!');
  } catch(err) {
    console.error(err);
  }
})();

Repositories

In order to get or save entity objects, you can use the Repository class provided by orm-js/orm. For each entity, you have to instanciate a new Repository with the entity class passed as its parameter. The following example creates a new user and retrieves it back from the database:

import * as orm from 'orm-js/orm';
import User from './user';

(async () => {
  let repo = new orm.Repository(User);
  
  let user = new User();
  user.userName = 'Hero Brain';
  user.emailAddress = '[email protected]';
  
  // you can use insert() for both new and updating entities
  await repo.insert(user);
  
  // a numeric ID field is automatically set by the insert operation
  console.log(`User got the id: ${user.id}`);
  
  // get an array of User entities
  let userList = await repo.findAll();
  console.log(userList);
})();

Install

Via npm:

$ npm install orm-js

You'll need to install a database connector for orm-js, in order to connect to an actual database. Currently there's only orm-js-sqlite available:

$ npm install orm-js-sqlite

When using TypeScript, make sure to enable both experimentalDecorators and emitDecoratorMetadata in your tsconfig.json:

{
  "compilerOptions": {
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
  }
}

License

orm-js is licensed under the MIT License.

orm-js's People

Stargazers

 avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

orm-js's Issues

Capitalized

I was wondering why you capitalized the names of all decorators. Is this some sort of convention I'm not aware of?

Compilation errors of default code example

I was running the example: README.md, however the following errors occurred:

1. I was trying to connect to a database and it was this error that launched:

file:///home/raphael/wokspace-VSCode/test_ormtypescript/dist/node_modules/orm-js-sqlite/node_modules/sqlite/node_modules/sqlite3/node_modules/node-pre-gyp/node_modules/npmlog/node_modules/set-blocking/index.js

index.js:3Uncaught TypeError: Cannot read property '_handle' of undefined(anonymous function) 
@ index.js:3t.exports 
@ index.js:2(anonymous function) 
@ log.js:11r.52._process 
@ log.js:302u 
@ _prelude.js:1(anonymous function) 
@ node-pre-gyp.js:15r.46.../package 
@ node-pre-gyp.js:191u 
@ _prelude.js:1(anonymous function) 
@ sqlite3.js:1r.44../trace 
@ sqlite3.js:189u 
@ _prelude.js:1(anonymous function) 
@ main.js:5r.43.fs 
@ main.js:646u 
@ _prelude.js:1r.41.orm-js/abstract-database 
@ index.js:11u @ _prelude.js:1r.133.../entities/pessoa 
@ connection.js:40u
@ _prelude.js:1r.132../persistence/connection 
@ main.js:2u 
@ _prelude.js:1e 
@ _prelude.js:1(anonymous function)
@ _prelude.js:1

2. My compiler complained about this snippet of code:

...
var connection = new SqliteDatabase("database.db");
orm.setDatabase(connection);
...

source/persistence/connection.ts(7,17): error TS2345: Argument of type 'SqliteDatabase' is not assignable to parameter of type 'AbstractDatabase'.
Types of property 'schema' are incompatible.
Type 'Schema' is not assignable to type 'Schema'.
Property 'hasTable' is missing in type 'Schema'.

db connection example

first line
import * as orm from 'orm-js';
should be
import * as orm from 'orm-js/orm';

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.