A RESTful controller for BackboneORM
npm install backbone-rest
By using BackboneREST on the server and BackboneORM's JSON rendering DSL, you can save time in defining JSON APIs.
Backbone = require 'backbone'
RestController = require 'backbone-rest'
class Task extends Backbone.Model
urlRoot: 'mongodb://localhost:27017/tasks'
sync: require('backbone-mongo').sync(Task)
new RestController(app, {model_type: Task, route: '/tasks'})
var Backbone = require('backbone');
var RestController = require('backbone-rest');
var Task = Backbone.Model.extend({
urlRoot: 'mongodb://localhost:27017/tasks'
});
Task.prototype.sync = require('backbone-mongo').sync(Task);
new RestController(app, {model_type: Task, route: '/tasks'});
BackboneORM provides a DSL for rendering JSON. It is consistent with BackboneORM's query syntax and BackboneREST's url-based query language.
new RestController(app, {
model_type: Task
route: '/tasks'
templates:
show: {$select: ['id', 'name']}
show_with_stuff: {$select: ['id', 'name', 'stuff']}
default_template: 'show'
})
var RestController = require('backbone-rest');
new RestController(app, {
model_type: Task,
route: '/tasks',
templates: {
show: { $select: ['id', 'name'] },
show_with_stuff: { $select: ['id', 'name', 'stuff']}
},
default_template: 'show'
});
You are able to use Express middleware to secure you application.
ensureLoggedIn = require 'connect-ensure-login'
customAuthorization = (req, res, next) ->
unless req.user.canAccessTask(req)
return res.status(401).send('you cannot access this task')
next()
new RestController(app, {
auth: [ensureLoggedIn('/login'), customAuthorization]
model_type: Task
route: '/tasks'
})
var ensureLoggedIn = require('connect-ensure-login');
var customAuthorization = function(req, res, next) {
if (!req.user.canAccessTask(req)) {
return res.status(401).send('you cannot access this task');
}
return next();
};
new RestController(app, {
auth: [ensureLoggedIn('/login'), customAuthorization],
model_type: Task,
route: '/tasks'
});
When using express, you will need to include the json body-parser.
"use strict";
var app = require('express')();
app.use(require('body-parser').json({}));
app.listen(3000);
class Project extends require('backbone').Model {
constructor(options) {
super(options);
this.urlRoot = '/projects';
}
}
Project.sync = require('backbone-orm').sync(Project);
var RESTController = require('backbone-rest');
new RESTController(app, {model_type: Project, route: '/projects'});
"use strict";
var app = require('express')();
app.use(require('body-parser').json({}));
app.listen(3000);
class Project extends require('backbone').Model {
constructor(options) {
super(options);
this.urlRoot = '/projects';
}
}
Project.sync = require('backbone-orm').sync(Project);
var RESTController = require('backbone-rest');
new RESTController(app, {model_type: Project, route: '/projects'});