Skip to content

Instantly share code, notes, and snippets.

@Thorsson
Forked from nnarhinen/README.md
Last active August 29, 2015 14:25
Show Gist options
  • Save Thorsson/d6646ed1157280b59129 to your computer and use it in GitHub Desktop.
Save Thorsson/d6646ed1157280b59129 to your computer and use it in GitHub Desktop.
Rails-like console with express.js, bookshelf.js and node-repl-promised

Install node-repl-promised: npm install -g repl-promised

Use the repl to list all users

$ node-promised
> var app = require('./app');
undefined
> var Bookshelf = app.get('bookshelf');
undefined
> Bookshelf.models.User.query()
[ { id: 5,
    email: 'chuck@norris.com',
    name: 'Chuck Norris',
    password_hash: '$2a$10$MuSVvgsOYGBMK12p4boSh.eX/FmmDXvbhrGfJcHPJQr0BLVEOrTcy',
    created_at: 1411628445371,
    updated_at: 1411628445371 } ]
>

If you want to have something pre-defined in your global context, you need to create your own repl initialization script:

var repl = require("repl").start({}),
    promisify = require("repl-promised").promisify,
    app = require('./app');
repl.context.models = app.get('bookshelf').models;
promisify(repl);

after that you can use models-variable directly:

$ node repl.js 
> models.User.query()
[ { id: 5,
    email: 'chuck@norris.com',
    name: 'Chuck Norris',
    password_hash: '$2a$10$MuSVvgsOYGBMK12p4boSh.eX/FmmDXvbhrGfJcHPJQr0BLVEOrTcy',
    created_at: 1411628445371,
    updated_at: 1411628445371 } ]
>
var express = require('express'),
app = express(),
Bookshelf = require('./bookshelf');
app.set('bookshelf', Bookshelf);
module.exports = app;
var knex = require('knex')({
client: 'sqlite',
connection: {
filename: './development.sqlite'
}
});
var Bookshelf = module.exports = require('bookshelf')(knex);
Bookshelf.models = {
User: Bookshelf.Model.extend({
tableName: 'users'
})
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment