npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

ficus

v0.0.4

Published

An extremely simple set of utilities for building service-based APIs in ExpressJS.

Downloads

34

Readme

ficus

An extremely simple set of utilities for building service-based APIs in ExpressJS.

Build Status NPM Version NPM Downloads

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 object
  • resSchema: Joi schema representing the form of the response object
  • handler(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.

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());
});