This feature is part of spludo since 1.1.

If you want to make one of your services accessible as a REST Service, you don't have to write the mapping for each of your functions to HTTP-Methods on your own.

Let's assume you have a lib/services/WebApiService.js.

Simple put this into your myapp/main-controllers.js:

new ApiServiceController("api", service_manager.get('WebApi'));

This will register all methods on it's own with the following mapping:

The functions within the service have to look like that:

WebApiService.prototype.putUser = function(cb, user_id, params, context) {
    /*
     * Your logic ...
     */
    if (user_not_found) {
        cb(404, 'Cannot find that user');
    } else {
        cb(200, {
            'id': user_id,
            'name': 'Hans'
        });
    }
}

The callback always takes a first parameter which is the http status code. So we return 200 with a valid object, if it worked. But we return 404 if the user was not found.

The result for the caller will look like that (with http code 404):

{"status":false,"error":"Cannot find that user"}

and in case of success like that (with http code 200):

{"status":true,"data":{"id":2,"name":"Hans"}}

As you can see the verb is used as prefix (GET, POST, DELETE) and depeding on the case if you try to call the collection it calls the pluralized version (methodUsers) or the singular version (methodUser).

To achieve that spludo uses the inflection.js library. If you want to override the mapping use it like that:

new ApiServiceController("api", service_manager.get('WebApi'), {
    'singular': {
        'mice': 'mouse',
        'men': 'man'
    }
});

This will still keep the Api like api/mice but the methods are:

It's also possible to override the method (in case you are in a context when you have to send every request with POST). Use the query parameter _method.

This POST /api/users/123?_method=delete has the same effect like DELETE /api/users/123, it calls: #deleteUser(cb, 123, context).

Comments