0.20.1 • Published 4 months ago

@blastz/nico v0.20.1

Weekly downloads
4
License
MIT
Repository
github
Last release
4 months ago

Nico blastZ

NPM version David deps node version npm download

This package is still in development.

Nico is a modern backend framework build on koa, it's inspired by sails. Ultimately nico is an effort to provide a more clear way to build api services.

Installation

npm install @blastz/nico

Hello Nico

import nico from '@blastz/nico';
// const nico = require('@blastz/nico').default

nico.init({
  routes: {
    'GET /users': {
      controller: async (ctx) => {
        return (ctx.body = []);
      },
    },
  },
});

nico.start();

Router

Basic Router

Nico use routes config to register routes, the basic usage like:

nico.init({
  routes: {
    'GET /users': {
      // ...
    },
  },
});

This will register a route whose path is /users and http method is Get.

Nested Router

Nesetd router also supported:

nico.init({
  routes: {
    '/api/v3': {
      '/users': {
        GET: {
          // ...
        },
        POST: {
          // ...
        },
        '/:id': {
          DELETE: {
            // ...
          },
        },
      },
    },
  },
});

This config will register three routes

  • GET /api/v3/users
  • POST /api/v3/users
  • DELETE /api/v3/users/:id

Body Parser

By default, body parser only works when request method is POST, PUT or PATCH, change it by parsedMethods config.

You need to manually enable body parser on specific route, otherwise it won't work.

nico.init({
  routes: {
    '/api/v3': {
      '/users': {
        POST: {
          bodyParser: true,
          // ...
        },
      },
    },
  },
});

By default It will only parse json and form types.

Multipart

To support multipart form data, you need to enable it.

nico.init({
  //...
  POST: {
    bodyParser: {
      multipartOpts: {
        enable: true,
      },
    },
    // ...
  },
  //...
});

You can pass formidable options directly in multipartOpts like this:

nico.init({
  //...
  POST: {
    bodyParser: {
      multipartOpts: {
        enable: true,
        formidable: {
          maxFileSize: 10 * 1024 * 1024,
        },
      },
    },
    // ...
  },
  //...
});

XML And Text

Same as multipart, you need to enable them by xmlOpts and textOpts configs.

More options

Check more options in config types.

Responses

Use responses to change response format.

nico.init({
  routes: {
    'GET /users': {
      controller: (ctx) => {
        return ctx.ok([]); // { data: [], message: 'execute success', success: true }
      },
    },
  },
  responses: {
    ok: function ok(data, message = 'execute success', success = true) {
      this.status = 200;
      this.body = {
        success,
        data,
        message,
      };
    },
  },
});

Validate

Nico support validate params, query, body and files, It's recommend to use it with Joi.

nico.init({
  routes: {
    'POST /users': {
      controller: (ctx) => {
        ctx.logger.info(ctx.state.body.name); // validated value will be mounted at ctx.state
      },
      bodyParser: true, // enable body parser middleware
      validate: {
        body: Joi.object({
          username: Joi.string().trim().required().min(1).max(50),
        }),
      },
    },
  },
});

NOTE

Above validate will allow body to be undefined, use Joi.object().requried() to block it.


Nico will throw validate error by default, the error will be cached by global error handler. You can add onError, onBodyParserError, onValidateError in responses config to change default behavior.

nico.init({
  responses: {
    onError: function onError(err) {
      this.status = 200;
      return (this.body = {
        message: err.message,
        success: false,
      });
    }, // change global error handle
    onBodyParserError: function onBodyParserError(err) {
      this.status = 200;
      return (this.body = {
        message: err.message,
        success: false,
      });
    }, // change body parser error handle
    onValidateError: function onValidateError(err) {
      this.status = 200;
      return (this.body = {
        message: err.message,
        success: false,
      });
    }, // change validate error handle
  },
});

Static File Serve

Serve /assets directory like this:

nico.init({
  serve: {
    root: path.resolve(process.cwd(), './assets'),
  },
});

Change Route Path

nico.init({
  serve: {
    root: path.resolve(process.cwd(), './assets'),
    route: '/static',
  },
});

Get /assets/avatar.png by route {{serverUrl}}/static/avatar.png.

Serve Multiple Directories

Serve multiple directories also supported.

nico.init({
  serve: [
    {
      root: path.resolve(process.cwd(), './assets'),
      route: '/assets',
    },
    {
      root: path.resolve(process.cwd(), './static'),
      route: '/static',
    },
  ],
});

More Options

Serve configs support koa-static options.

nico.init({
  serve: {
    opts, // from koa-static
  },
});

Debug

nico has five log levels: fatal, error, warn, info, debug and trace.

Default console level is info, file level is none.

Default Logger Config

const loggerConfig: ConfigLogger = {
  fileLevel: 'none',
  consoleLevel: 'info',
};

Mutiple File Logger

const loggerConfig: ConfigLogger = {
  fileLevel: ['trace', 'error'],
};

Default Output directories are log/trace and log/error.

Usage Example

ctx.logger.fatal('fatal');
ctx.logger.debug('debug');

Custom Middlewares

Nico use appMiddlewares and routeMiddlewares to store middleware informations, app middlewares will execute when nico.init() is called, route middlewares will execute when http request come.

The default appMiddleware is ['error-handler', 'not-found-handler', 'global-cors', 'responses', 'serve', 'routes'].

The default routeMiddleware is ['debug', 'controller-cors', 'csp', 'xframes', 'policies', 'body-parser', 'validate', 'controller'].

Change default middlewares:

nico.appMiddlewares = [
  InnerAppMiddleware.ERROR_HANDLER,
  InnerAppMiddleware.GLOBAL_CORS,
  InnerAppMiddleware.ROUTES,
];
nico.routeMiddlewares = [InnerRouteMiddleware.CONTROLLER];

Define custom middlewares:

nico.useAppMiddleware(async (ctx, next) => {
  await next();
  ctx.set('custom', 'custom');
});

nico.useRouteMiddleware(async (ctx, next) => {
  await next();
  ctx.set('custom', 'custom');
}, InnerRouteMiddleware.DEBUG);

nico.init();

The second argument is the middleware name, above example shows custom middleware will execute after debug middleware. Custom middleware will be added to the middlewares after use middleware function, the name in the middlewares is the name of the function.

The default second argument of useAppMiddleware is global-cors and useRouteMiddleware is controller-cors.

If the second argument is null or not found in middlewares, the custom middleware will be execute before all middlewares.

Graceful Shutdown

Nico will handle SIGINT and SIGTERM by default, you can add custom signal handler like this:

nico.useSignalHandler('SIGINT', () => {
  closeDB();
});

Nico will automatically await all requests end and close the server, you only need to add some side effects.

The process will force exit after 10 seconds, you can change it in nico.config.advancedConfigs.forceExitTime.

Cluster Mode

Nico support cluster mode internal, use nico.startCluster(port: number, instances?: number) to start nico with cluster mode. The default instances will be cpu numbers.

Plugins

License

MIT

0.20.1

4 months ago

0.20.0

4 months ago

0.19.1

6 months ago

0.19.0

7 months ago

0.18.7

9 months ago

0.18.6

9 months ago

0.18.2

9 months ago

0.18.1

10 months ago

0.18.0

10 months ago

0.17.3

10 months ago

0.17.2

10 months ago

0.17.1

11 months ago

0.17.0

11 months ago

0.16.1

11 months ago

0.16.0

1 year ago

0.15.0

1 year ago

0.14.2

1 year ago

0.14.0

1 year ago

0.14.1

1 year ago

0.13.2

1 year ago

0.13.1

1 year ago

0.13.0

1 year ago

0.12.2

1 year ago

0.12.1

1 year ago

0.12.0

1 year ago

0.11.3

1 year ago

0.11.2

1 year ago

0.11.1

1 year ago

0.10.1

1 year ago

0.10.0

1 year ago

0.9.13

1 year ago

0.9.11

1 year ago

0.9.10

1 year ago

0.9.9

1 year ago

0.9.8

1 year ago

0.9.7

1 year ago

0.9.6

1 year ago

0.9.5

1 year ago

0.9.4

1 year ago

0.9.3

1 year ago

0.9.2

1 year ago

0.9.1

1 year ago

0.9.0

1 year ago

0.8.9

1 year ago

0.8.8

1 year ago

0.8.7

1 year ago

0.8.6

1 year ago

0.8.5

1 year ago

0.8.3

1 year ago

0.8.2

1 year ago

0.8.1

1 year ago

0.7.11

1 year ago

0.7.10

1 year ago

0.7.9

1 year ago

0.7.13

1 year ago

0.7.12

1 year ago

0.8.0

1 year ago

0.7.7

1 year ago

0.7.6

1 year ago

0.7.5

1 year ago

0.7.4

1 year ago

0.7.3

1 year ago

0.7.2

1 year ago

0.7.1

1 year ago

0.7.0

1 year ago

0.6.17

1 year ago

0.6.16

1 year ago

0.6.15

1 year ago

0.6.14

1 year ago

0.6.13

1 year ago

0.6.12

1 year ago

0.6.10

1 year ago

0.6.11

1 year ago

0.6.9

1 year ago

0.6.7

1 year ago

0.6.8

1 year ago

0.6.6

1 year ago

0.6.5

1 year ago

0.6.4

1 year ago

0.6.3

1 year ago

0.6.2

1 year ago

0.6.1

1 year ago

0.6.0

1 year ago

0.5.4

1 year ago

0.5.3

1 year ago

0.5.2

1 year ago

0.5.1

1 year ago

0.5.0

1 year ago