Home Manual Reference Source

KoaSmart is a framework based on Koajs2, which allows you to develop RESTful APIs with : Class, Decorator, Params checker

Build Status NPM version

A framework based on Koajs2 with Decorator, Params checker and a base of modules (cors, bodyparser, compress, I18n, etc... ) to allow you to develop a smart api easily

  export default class RouteUsers extends Route {

    // get route: http://localhost:3000/users/get/:id
    @Route.Get({
      path: 'get/:id'
    })
    async get(ctx) {
      const user = await this.models.users.findById(ctx.params.id);
      this.assert(user, 404, 'User not found');
      this.sendOk(ctx, user);
    }

    // post route: http://localhost:3000/users/add
    @Route.Post({
      accesses: [Route.accesses.public],
      bodyType: Types.object().keys({
        email: Types.string().required(), // return an 400 if the body doesn't contain email key
        name: Types.string().uppercase(), // optional parameter
      }),
    })
    async add(ctx) {
      const body = this.body(ctx); // or ctx.request.body
      // body can contain only an object with email and name field
      const user = await this.models.user.create(body);
      this.sendCreated(ctx, user);
    }

  }

Api documentation

Summary

What is in this framework ?

This framework gives you the tools to use a set of modules:

Install

npm install koa-smart

Router with decorator

All routes have to extend the Route class in order to be mount

Koa smart allows accesses to be handled in a simple and efficient manner.

function admin() {
  return false;
};

function user(ctx) {
  // work with ctx...
  return ctx.user.id != null;
};

export default class RouteAccess  extends Route {
  constructor(params) {
    super({ ...params });
  }
  @Route.Post({
    accesses: [admin, users], // pass an array of functions
  })
  async myRoute(ctx) {
    this.sendOk(ctx, this.body(ctx));
  }
}

Each function passed to accessers will be given the koa context as a parameter, and must return a boolean to express whether is grants access to the route or not.

If at least one of the function given returns true, access to the route will be granted.

Params checker: See the doc of Types for more information

Automatic documention generation: See the manual for more information

Get Started (quick-start boilerplate)

in order to get started quickly, look at this boilerplate, or follow the instructions below:

Full example

License

MIT © YSO Corp