Research
Security News
Quasar RAT Disguised as an npm Package for Detecting Vulnerabilities in Ethereum Smart Contracts
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
An extremely simple set of utilities for building service-based APIs in ExpressJS.
An extremely simple set of utilities for building service-based APIs in ExpressJS.
npm install --save ficus
import {
// utility functions
handle,
wrap,
// errors
AppError,
HttpError,
NotFoundError,
ForbiddenError,
InternalServerError,
UnauthorizedError,
BadRequestError,
ConflictError
} from 'ficus';
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 handler
reqData
: The request data validated and sanitized through reqSchema
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.
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
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'] }
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');
}
}
})
Use the context object (second argument of handle()
):
handle({
reqSchema: Joi.any(),
resSchema: Joi.any(),
handler(reqData, ctx) {
// ctx.req.session => Your session data
}
})
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'
};
}
})
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());
});
FAQs
An extremely simple set of utilities for building service-based APIs in ExpressJS.
The npm package ficus receives a total of 1 weekly downloads. As such, ficus popularity was classified as not popular.
We found that ficus demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
Security News
Research
A supply chain attack on Rspack's npm packages injected cryptomining malware, potentially impacting thousands of developers.
Research
Security News
Socket researchers discovered a malware campaign on npm delivering the Skuld infostealer via typosquatted packages, exposing sensitive data.