Skip to content

Instantly share code, notes, and snippets.

@ishmaelmakitla
Created March 13, 2017 10:02
Show Gist options
  • Save ishmaelmakitla/da37e00af57adf11da4aa8135570b54a to your computer and use it in GitHub Desktop.
Save ishmaelmakitla/da37e00af57adf11da4aa8135570b54a to your computer and use it in GitHub Desktop.
This gist illustrates the use of Knex and Bookshelf in a NodeJS application. This script defines an KNEX object which connects to a running instance of PostgreSQL;
var pg = require('pg');
//Optionally, you may have config file that has the parameters used to connect to PG
//var config = require('../utilities/config');
var knex = require('knex')({
client: 'pg',
connection: {
host : '127.0.0.1',
port : '5432',
user : 'some-role-name',
password : 'role-password',
database : 'your-database',
charset : 'UTF8'
}
});
var bookshelf = require('bookshelf')(knex);
//we export this here because we will use/require db.js in other scripts
exports.bookshelf = bookshelf;
//Optional - but you may also want to use raw knex and so exporting it here is a good idea
exports.knex = knex;
//we include the db.js script (in the same director)
var DatabaseUtils = require('./db.js');
//here we get access to the Bookshelf object
var bookshelf = DatabaseUtils.bookshelf;
bookshelf.plugin('registry');
//here we define our model - this points to the userRoles table in PostgreSQL
var UserRole = bookshelf.Model.extend({tableName: 'userRoles'});
//this is for a collection of user roles
var UserRoles = bookshelf.Collection.extend({model: UserRole});
//example of a user
var User = bookshelf.Model.extend({
tableName: 'users',
roles: function() {
//a User will have one or more roles referenced by the userId in the userRoles table
return this.hasMany(UserRole, 'userId');
}
});
//as an exercise, write the Users model below:
// I will use models object to get access to the models such as User(s), UserRoles, etc defined in models.js
var Models = require('./models.js');
//here is how I search for all:
exports.getAll = function (callback){
Users.forge().fetch().then(function (users){
var allUsers = (users? users.toJSON(): null);
if(allUsers){
callback(null, allUsers);
}
else{
callback(new Error("Users Not Found"));
}
})
.catch(function (err){
console.log("Error Getting Users. Error is ", err);
});
};
//Get user is his related roles:
function findUser(id, callback){
User.forge({'id': id}).fetch({withRelated: ['roles']}).then(function (user){
user = (user? user.toJSON(): null);
if(user){
callback(null, user);
}
else{
callback(new Error("User Not Found"));
}
}).catch(function (err){
callback(err);
});
}
//As an exercise, write a function that retrieves all user-roles
//
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment