ficus
v0.0.4
Published
An extremely simple set of utilities for building service-based APIs in ExpressJS.
Downloads
167
Readme
ficus
An extremely simple set of utilities for building service-based APIs in ExpressJS.
The Basics
Install
npm install --save ficus
import {
// utility functions
handle,
wrap,
// errors
AppError,
HttpError,
NotFoundError,
ForbiddenError,
InternalServerError,
UnauthorizedError,
BadRequestError,
ConflictError
} from 'ficus';
Usage
Ficus is focused on building service-based APIs. Instead of writing routes, you write services. Service methods can be composed and reused from other services. Service methods also export as very simply functions, allowing easy testing and a scalable API. To accomplish this, ficus has two utility functions: handle
and wrap
.
handle(opts)
The handle function's main purpose is to map a request object against a schema, run it through a handler function, and then pass the result back through a response schema. This enforces a tight contract for your service methods.
@param opts {object}
reqSchema
: Joi schema representing the form of the request objectresSchema
: Joi schema representing the form of the response objecthandler(reqData, ctx)
: Service handlerreqData
: The request data validated and sanitized throughreqSchema
ctx
: Object of form{req, res}
that allows access to original request values (if present)
@returns Promise
Promise will resolve with final value after the req -> handle -> res
process.
Example
import {handle} from 'ficus';
const getUsers = handle({
reqSchema: Joi.object().keys({
query: Joi.string().required()
offset: Joi.number().default(0),
limit: Joi.number().default(10)
}),
resSchema: Joi.object().keys({
users: Joi.array().items(Joi.string()).required()
}),
handle({query, offset, limit}) {
// Some ORM call
return User
.find(query)
.limit(limit)
.offset(offset)
.then(users => users.map(u => u.name));
}
});
// Good service call
getUsers({
query: 'ficus'
})
.then(({users}) => {
// users => ['ficus', 'ficus tree', 'ficus plant']
});
// Bad sevice call
getUsers({})
.catch(err => {
// err => Bad Request Error, 'query' is required
});
As you can see, with just a little bit of prep work we can have strict and simple service methods. Its easy to compose service methods from other services as they are just simple method calls with a request object and Promise
result.
However, what really makes these service methods useful is linking them with your routes. That's where wrap()
comes in.
wrap(handler)
The wrap()
function takes a service method generated by handle()
as an argument, and returns a fully qualified Express route handler. It does this by combing the req.params
, req.body
, and req.query
objects into one object, and using it as the request data for handle()
.
@param handler {func}
@returns {func} (req, res, next)
Express route handler
Example
import {wrap} from 'ficus';
// from `handle()` example above
import {getUsers} from './services/user';
app.get('/users/:query?', wrap(getUsers));
// GET /users?query=ficus
// RESPONSE { users: ['ficus', 'ficus tree', 'ficus plant'] }
// GET /users/ficus
// RESPONSE { users: ['ficus', 'ficus tree', 'ficus plant'] }
Errors
There are some handy Http Errors available for you as part of Ficus. They provide quick and semantic ways to "error out" in your service handlers. It is also very easy to extend these errors to add your own. Take a look at the available errors and how to extend them here.
For example:
import {
handle,
ForbiddenError
} from 'ficus';
handle({
reqSchema: Joi.any(),
resSchema: Joi.any(),
handler(reqData, ctx) {
if (!ctx.req.session.isAdmin) {
throw new ForbiddenError('You must be an admin to do that');
}
}
})
Frequent Questions
How do I get to session variables?
Use the context object (second argument of handle()
):
handle({
reqSchema: Joi.any(),
resSchema: Joi.any(),
handler(reqData, ctx) {
// ctx.req.session => Your session data
}
})
How do I change the response code from 200?
Access the response on the context object before returning:
handle({
reqSchema: Joi.any(),
resSchema: Joi.any(),
handler(reqData, ctx) {
ctx.res.status(401);
return {
hello: 'world'
};
}
})
How do I make good use of the errors in Express?
A simple formula for bootstrapping your Express app:
import {
NotFoundError,
HttpError,
InternalServerError
} from 'ficus';
// ...
// Routes
// ...
// Not Found Handler
app.use(function(req, res, next) {
next(
new NotFoundError(`Route: ${req.url}`)
);
});
// Error handler
app.use(function(err, req, res, next) {
if (!(err instanceof HttpError)) {
console.error(err.stack); // or some logger
err = new InternalServerError();
}
res.status(err.status).json(err.toObject());
});