Skip to content

Instantly share code, notes, and snippets.

@bajtos
Created July 25, 2014 15:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bajtos/26890ece90ef9b81cf53 to your computer and use it in GitHub Desktop.
Save bajtos/26890ece90ef9b81cf53 to your computer and use it in GitHub Desktop.
Customize Model.sharedCtor
var loopback = require('loopback');
var boot = require('loopback-boot');
var app = module.exports = loopback();
// hack sharedCtor
var setup = loopback.PersistedModel.setup;
loopback.PersistedModel.setup = function(rec) {
var extend = require('util')._extend;
var modelName = this.modelName;
console.log('setting up', modelName, new Error().stack);
setup.apply(this, arguments);
var sharedCtor = this.sharedCtor;
this.sharedCtor = function(id, req, cb) {
console.log('custom sharedCtor for', modelName, id);
if (typeof(id) === 'object' || typeof(req) !== 'object') {
// non-remoted call `sharedCtor(data, id, cb)`
return sharedCtor.apply(this, arguments);
}
req.pause();
sharedCtor.call(this, id, function() {
req.resume();
cb.apply(this, arguments);
});
};
extend(this.sharedCtor, {
shared: true,
accepts: [
{ arg: 'id', type: 'any', http: {source: 'path'}, description: modelName + ' id' },
{ arg: 'req', type: 'Object', http: { source: 'req' } }
],
http: {path: '/:id'},
returns: { root: true}
});
if (!rec) this.setup(true);
};
// business as usual - setup middleware, start the app
app.use(loopback.favicon());
// request pre-processing middleware
app.use(loopback.compress());
// -- Add your pre-processing middleware here --
// boot scripts mount components like REST API
boot(app, __dirname);
// -- Mount static files here--
// All static middleware should be registered at the end, as all requests
// passing the static middleware are hitting the file system
// Example:
// app.use(loopback.static(path.resolve(__dirname', '../client')));
// Requests that get this far won't be handled
// by any middleware. Convert them into a 404 error
// that will be handled later down the chain.
app.use(loopback.urlNotFound());
// The ultimate error handler.
app.use(loopback.errorHandler());
app.start = function() {
// start the web server
return app.listen(function() {
app.emit('started');
console.log('Web server listening at: %s', app.get('url'));
});
};
// start the server if `$ node server.js`
if (require.main === module) {
app.start();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment