basic-resource

1.2.2 • Public • Published

basic-resource

Register basic resources

Easy registration on basic REST resources on your Express/mongo node application.

install

Install by command line:

$ npm install basic-resource

Or add to your package.json:

{
    "basic-resource": "^0.2.0"
}

In your resource source add:

var mongoose = require('mongoose');
var ClientSchema = mongoose.Schema({
    name: { type: String, required: true },
    city: { type: String, required: true },
    phone: { type: String, required: true },
    created: { type: Date, default: Date.now }
} );
var Client = mongoose.model("Client", ClientSchema);
return require("basic-resource")(app, Client, {name: "clients", context: "/api"});

Basic urls to be register:

http://your-app-host/clients - GET to get all clients (controller method "index")

http://your-app-host/clients - POST for client creation (controller method "create")

http://your-app-host/clients/:clientId - GET to get one client (controller method "one")

http://your-app-host/clients/:clientId - PUT to update user (controller method "update")

http://your-app-host/clients/:clientId - DELETE - to delete user (controller method "remove")

You can pass additional query params:

Parameter fields will limit fields in result documents to specified. For example you can get /clients?fields=_id,create to only get _id and create fields of all clients

Parameter start will skip first N records of result. For example you can get /clients?start=10 to get clients from 10'th (can be combined with length for pagination)

Parameter length will limit result length to N. For example you can get /clients?length=10 to get only 10 clients (can be combined with start for pagination)

Modify controller default methods

To replace methods use:

var controller = {}; // create controller to 
controller.create = function(req, res) {
    res.statusCode = 406;
    return res.json({
      message: "you currently can't create new users"
    });
}
return require("basic-resource")(app, Client, {name: "clients", context: "/api", controller: controller});

Configure generated controller

You can pass options to controller generator:

var resource = require("basic-resource")(app, Client, {
    name: "clients", 
    context: "/api",
    validate: function(data) {
        return data.match(/[0-9A-F]+/i);
    },
    format: function(data) {
        if(data.index > 10) {
            return {index: "more then 10"};
        }
        return null;
    }
});

Package Sidebar

Install

npm i basic-resource

Weekly Downloads

1

Version

1.2.2

License

none

Last publish

Collaborators

  • sophos