Skip to content

Instantly share code, notes, and snippets.

@ritch ritch/

Created Jul 30, 2015
What would you like to do?
Next Generation of Model and Boot Scripts

Model and Boot Scripts

Currently, model scripts and the way they are loaded are a bit naive.

Take a look at this example:

// models/my-model.js
module.exports = function(MyModel) {
  MyModel.findFooBars = function(filter, cb) {, cb);

In order to ensure a reference to the FooBar model, we must navigate to it. We cannot safely reference models in the exported customization function.

Instead, we should be handed a reference to models.

module.exports = function(MyModel, FooBar) {
  MyModel.findFooBars = function(filter, cb) {
    FooBar.find(filter, cb);

We should also be able to write code that executes before and after the application is booted, without using an event handler.

// foo-bar.js
function config(FooBar) {
  FooBar.http.url = app.get('api version') + '/foo-to-the-bar';
// my-model.js

exports.prepare = function prepare(app) {
  // only the app object is defined
  app.set('api version', '/v8');

exports.config = function config(MyModel, FooBar) {
  // all datasources and models are reference-able
  // the app has not finished booting
  // only dependencies have finished being configured

  MyModel.getFooBarUrl = function(cb) {
    cb(null, FooBar.http.url); // => /foo-to-the-bar

exports.ready = function ready(MyModel, FooBar) {
  // all data sources have been setup
  // all models have been configured
  // all boot scripts have been executed

The same capability can be added to boot scripts. Also since a script must list its dependencies as arguments, the scripts are only conviently associated with models, apps, or datasources. This allows users to write scripts that work with several models, datasources, and apps.


This comment has been minimized.

Copy link

raymondfeng commented Jul 30, 2015

I like the general direction as it adds lifecycle support for the model. For the dependency injection, how to express that FooBar is needed for MyModel?


This comment has been minimized.

Copy link

kraman commented Jul 30, 2015

+1 on model dependency injection and the boot phases


  • Would this mean that could have a my-model.js in common/models and another in server/models and it would be intelligent enough to know that I want the same models injected?
  • I this an attempt to add versioning to the API?

This comment has been minimized.

Copy link
Owner Author

ritch commented Jul 30, 2015

For the dependency injection, how to express that FooBar is needed for MyModel?

Its in the function signature. boot() would look up the model by parsing require('script').functionName.toString().

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.