express-json-api v0.0.9
Express JSON API
This is an easy to use Express.js route helper that adapts your Mongoose models to jsonapi.org API endpoints. Basically it allows you to do CRUD on your mongoose models with some simple configuration.
Note; this is still very much a work in progress, but I would love to hear your thoughts.
Install
npm install express-json-api --saveRequirements
You are also required to be running expressjs and mongoose.
npm install express --save
npm install mongoose --saveQuick Start
var express = require('express');
var expressJsonApi = require('express-json-api');
var get = expressJsonApi.controllers.get;
var getList = expressJsonApi.controllers.getList;
var patch = expressJsonApi.controllers.patch;
var post = expressJsonApi.controllers.post;
var userModel = require('../models/user'); // a reference to your mongoose models
var config = {
routes: [
{
endpoint: '/users',
model: userModel,
limit: 20,
id: '_id',
methods: {
get: get.default,
getList: getList.default,
patch: patch.default,
post: post.default
},
search: {
active: true,
fields: ['first-name']
},
sanitize: {
active: true
}
}
]
};
expressJsonApi.factory(app, config);Now you can access your users by:
GET /usersto get all usersPOST /usersto create a single userGET /users/:idto get a single userPATCH /users/:idto update a single user
Filters, Sort, Pagination and Search
There are a number of modifers to help return the correct data. These all follow the recommendations of jsonapi.org
GET /users?filter[first-name]=Elon&filter[last-name]=Muskto get all users with the first name "Elon" and the last name "Musk".GET /users?sort=last-nameto get all users and sort by descending last name.GET /users?q=Elonto get all users with "Elon" in thefirst-namefield.GET /users?page[limit]=1&page[offset]=3to get 1 user starting at the 4th.
You can, of course, combine all those together into one long query:
GET /users?filter[country]=Australia&sort=-last-name,first-name&page[limit]=10 to get all Australian users, sort by descending last name, then ascending first name and limit the response to 10 items per page.
TODO
- Write more thorough documentation on sanitizers, how to override individual implementations, and how to use custom serializers.
- Create
DELETEfunctionality. - Implement:
- Stronger jsonapi response standards (eg.
{ data: { type: "users" } }). See http://jsonapi.org/format/#document-resource-objects - jsonapi
relationshipsandlinks. - Standardised error message.
- Dev/debugging mode so that stack traces aren't displayed in production systems.
- Stronger jsonapi response standards (eg.