Skip to content

Instantly share code, notes, and snippets.

@joshblack
Created January 26, 2015 04:19
Show Gist options
  • Save joshblack/acb888ac2ded8fd20ea4 to your computer and use it in GitHub Desktop.
Save joshblack/acb888ac2ded8fd20ea4 to your computer and use it in GitHub Desktop.
Possible ORM API for Node.js / io.js based off of Laravel's Eloquent API
"use strict";
const Schema = require('schema');
const Migration = require('migration');
// Migration builder
let CreateUsersTable = Object.create(Migration);
CreateUsersTable.prototype.up = function up() {
// Schema takes in a table name and instantiates a table
// for us then to use to chain properties to
Schema.create('tableName', function (table) {
table.increments('id');
table.string('stringField', { length: 500, unique: true });
table.integer('intField');
table.boolean('boolField');
table.date('dateField');
table.timestamps();
});
};
CreateUsersTable.prototype.down = function down() {
Schema.drop('tableName');
};
// Seeder
let UsersTableSeeder = Object.create(Seeder, { table: 'users' });
// Run should give us a table object to work with
UsersTableSeeder.prototype.run = function run() {
// Delete everything in table
this.table.truncate();
let data = [];
// Insert data
this.table.seed(data);
}
// Eloquent User Model
const Eloquent = require('eloquent');
let User = Object.create(Eloquent, { table: 'users' });
// Many-to-one relationship
User.prototype.posts = function posts() {
return this.hasMany('post');
}
// Many-to-many relationship
User.prototype.groups = function groups() {
return this.belongsToMany('groups');
}
// Usage
const User = require('./models/user');
let info = { username: 'foo', password: 'bar', email: 'foobar' };
User.create(info).then(function (success) {
console.log('User created');
});
User.all().then(function (users) { console.log('All users!') });
User.find({ id: 3 }).then(function (user) {
console.log('We\'ve found a match for the ${user}');
});
User.where({ email: 'foobar' }).then(function (user) {
console.log('Found the user');
});
User.destroy({ id: 3 }).then(function (msg) {
console.log('User deleted')
});
User.where({ email: 'foobar' }).then(function (user) {
});
// Relationships
User.find({ id: 3 }).then(function (user) {
console.log('Posts are here: ${user.posts}');
// Can subquery further...
return user.posts.where('length', '>', 200);
});
Copy link

ghost commented Sep 28, 2016

I am looking for. Good job.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment