0.4.6 • Published 2 months ago

koa-abstract-route v0.4.6

Weekly downloads
-
License
MIT
Repository
github
Last release
2 months ago

koa-abstract-route

npm license build codecov

API Router for Koa@2 middleware

Features

  • Easy to define your custom API routes
  • Handles higher level content types of request/response
  • Stream friendly

Setup

koa-abstract-route requires Node.js v16 or higher for ES2015 and async function support.

  1. Add koa-abstract-route dependency to your project
$ npm install --save koa-abstract-route

Example

  • MyAPI.ts
import { AbstractRoute, APIParam } from 'koa-abstract-route';

export default class MyAPI extends AbstractRoute {
  constructor() {
    super({ prefix: '/api/v1' });

    /*
     * API Parameter definitions.
     */
    const apiParams: APIParam[] = [
      {
        /* Gets current server time.
         * @example
         * ```bash
         * $ curl -i http://127.0.0.1/api/v1/time
         * ```
         */
        method: 'GET',
        interface: {
          name: 'time',
          options: [
            {
              key: 'format',
              type: 'string',
              required: false,
              default: 'epoch',
              validate: {
                match: /^(epoch|iso)$/
              }
            }
          ]
        },
        response: {
          contentType: 'application/json'
        },
        observer: ({ request, response }, format: string): object => {
          return {
            timeStamp:
              format === 'epoch' ? Date.now() : new Date().toISOString()
          };
        }
      }
    ];

    try {
      this.routeAdd(apiParams);
    } catch (err) {
      console.error(err);
    }
  }
}
  • Server.ts
import Koa from 'koa';
import MyAPI from './MyAPI';

const app = new Koa();
const api = new MyAPI();
app.use(api.router.routes());

const server = app.listen(80, () => {
  api.router.stack.forEach((route) => {
    console.info(`Route ${route.methods.join(', ')} ${route.path}`);
  });
});

Constructor Options

prefix

  • Type: String
  • Default: ''

Prefix of URL routes.

Development

  1. Clone this repository
  2. Install dependencies using yarn install or npm install
  3. Start development server using npm run dev

License

MIT License

Copyright (c) SAL Ltd.

0.4.6

2 months ago

0.4.5

6 months ago

0.4.4

7 months ago

0.4.3

11 months ago

0.4.2

12 months ago

0.4.1

1 year ago

0.3.0

2 years ago

0.4.0

1 year ago

0.3.1

1 year ago

0.2.0

2 years ago

0.1.1

2 years ago

0.1.0

2 years ago