Skip to content

Instantly share code, notes, and snippets.

@nnarhinen
Last active June 25, 2019 09:33
Show Gist options
  • Save nnarhinen/52d1744ca881172729de to your computer and use it in GitHub Desktop.
Save nnarhinen/52d1744ca881172729de 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'
})
};
@asadakbar
Copy link

Is there a way to do this with Objection.js? I cant find a way to get a list of all the subclasses of Model because Objection uses es6 extends to create subclasses instead of Bookshelfs internally defined extend. I think each model would need to be added to repl.context explicitly.

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