1.0.0-rc.1.8.10 • Published 5 months ago

@ctt/crud-api v1.0.0-rc.1.8.10

Weekly downloads
56
License
SEE LICENSE IN <L...
Repository
github
Last release
5 months ago

CircleCI Coverage Status

crud-api

A CRUD microservice module exposing key features of a RESTful API as injected dependencies.

Installation

$ yarn add @ctt/crud-api

bootstrapping

To create a new CRUD service API, simply bootstrap the application by injecting the dependencies as depicted in the example below.

import { server, mysqlConnect, mongooseConnect, config } from '@ctt/crud-api';
import { schema as mongooseSchema } from './persistence/mongoose/schema';
import routes from './routes';
import services from './services';
import { Server } from 'hapi';

const application = (): Promise<Server> => server({
  dbConnect: mongooseConnect,   // Connect to db
  schema: mongooseSchema,       // Load the queries and models
  config,                       // Application configuration
  routes,                       // Application Routing
  services,                     // Service response formatter
  swaggerOptions: {             // Swagger options
    tags: [
       {
          description: 'Operation for handling user records',
          name: 'users',
      }
    ],
    info: {
      title: 'Microservice CRUD API Server',
      description: 'Powering Craft Turf\'s microservice projects',
      version: '0.0.1'
    }
  },

});

Then start the app as shown in the example below

(async (): Promise<void> => {
  const app = await application();

  await app.start();
  app.log('App runninng on', app.info.uri);
})();

setting up environment variables

node-convict and dotenv are both used to manage application configuration. It is a requirement to create a file named .env at root of project and setup as follows:

# Application
PORT=4015
TLS_CERT=/path/to/server.crt
TLS_KEY=/path/to/server..key

# Either... MYSQL Database
MYSQL_USER=username
MYSQL_PASS=passwd
MYSQL_DB=mydb

# OR... Mongo Database
MONGO_DB=mydb

You can console log process.env to find out available environment variables. You can also inspect the imported config object from @ctt/crud-api.

APIs

Details of each of the exposed APIs will now be explained.

database connectors

import { mysqlConnect, mongooseConnect, server } from '@ctt/crud-api';

server({
  ...
  dbConnect: mysqlConnect,   // Connect to db
  ...
});

Simply import either mysqlConnect (uses knex) to connect to mysql database or mongooseConnect (uses mongoose) to connect to mongo database.

schema

Depending on the choice of db connector, a schema/model will need to be implemented to query and manipulate the database.

import schema from 'path/to/my/models';

server({
  ...
  schema,
  ...
});

The exported models are each expected to receive the db connector (client) as an argument, for example...

import users from './User/queries';
import books from './Book/queries';

export default client => ({
  users: users(client),
  books: books(client),
});

routes

HapiJs is the core building block of this module. All routing and handling of client requests are managed by handlers defined.

import routes from 'path/to/my/routes';

server({
  ...
  routes,
  ...
});

Firstly, export all handlers of client requests, for example...

import createUser, { destroyUser } from './users/routes';
import createBook from './books/routes';

export default () => ([
  createUser,
  destroyUser,
  createBook,
  ...
]);

Each route handler will receive in its arguments...

export const createUser = ({
  services,     // Service response formatter
  config,       // Application configuration
  validate,     // joi validator
  json,        // Composite type  (schema: object) => (payload: object) => string;
}) => ({
  ...
});

Find out more about the passed in features:

  • Application configuration using convict
  • Object schema validation with joi

plugins

Prior to routes, HapiJs custom plugins can be loaded. In the following example the hapi-auth-jwt2 plugin module is configured as follows:

import hapiAuthJwt2 from 'hapi-auth-jwt2';

server({
  ...
  plugins: [{ plugin: hapiAuthJwt2, options: {} }],
  postRegisterHook: async app => {
    app.auth.strategy('jwt', 'jwt', {
      key: 'NeverShareYourSecret',
      validate: await validate,
      verifyOptions: { algorithms: [ 'HS256' ] }
    });
    
    app.auth.default('jwt');
  },
  ...
});

Notice the postRegisterHook, you can define a post plugin registration hook to be executed before the routes are loaded.

services

services is the layer between the router and the schema layers. It's main responsibility is to pass on the payload from the router to the schema. It also creates the HAL+JSON format resource response payload coming from the schema layer.

Firstly define the services; For example...

import users from './users/services';
import books from './books/services';

export default db => ({
  users: users(db),
    users: users(db),
    books: books(db),
    ...
});

Each service handler will receive in its arguments (passed down from router)...

export const create = async ({
  db,         // db connector
  payload,    // request payload
  config,     // app config
  client
}) => {
  ...
};

swagger

Automatically expose the API features using hapi-swagger For full list of options available, please check the official documentation

server({
  ...
  swaggerOptions: {             // Swagger options
    tags: [
       {
          description: 'Operation for handling user records',
          name: 'users',
      }
    ],
    info: {
      title: 'Microservice CRUD API Server',
      description: 'Powering Craft Turf\'s microservice projects',
      version: '0.0.1'
    }
  },

});

Ensure to add a tag to each route options...

options: {
  ...
  tags: ['api'],
  ...
},

logging and monitoring

The application has been configured with hapi-pino high performant logger. You can provide options as follows:

server({
  ...,
  loggerOptions: {
    redact: {
      paths: [
        'req.headers.authorization',
        '*.password',
        'pid',
        'hostname',
        'app',
        'responseTime',
        'req.id',
        'req.method',
        'req.headers',
        'req.remoteAddress',
        'req.remotePort',
        'res',
      ],
      remove: true,
    },
  },
});

For full list of options available, please check the official documentation

1.0.0-rc.1.8.10

5 months ago

1.8.9

1 year ago

1.8.8

1 year ago

1.8.7

1 year ago

1.8.6

2 years ago

1.8.5

2 years ago

1.8.2

2 years ago

1.8.4

2 years ago

1.8.3

2 years ago

1.8.1

2 years ago

1.8.0

2 years ago

1.7.2

2 years ago

1.7.1

2 years ago

1.7.0

2 years ago

1.6.27

4 years ago

1.6.26

4 years ago

1.6.25

4 years ago

1.6.20

4 years ago

1.6.22

4 years ago

1.6.21

4 years ago

1.6.24

4 years ago

1.6.23

4 years ago

1.6.19

4 years ago

1.6.17

4 years ago

1.6.16

4 years ago

1.6.15

4 years ago

1.6.11

4 years ago

1.6.10

4 years ago

1.6.13

4 years ago

1.6.12

4 years ago

1.6.14

4 years ago

1.6.9

4 years ago

1.6.8

4 years ago

1.6.7

4 years ago

1.6.6

4 years ago

1.6.4

4 years ago

1.6.5

4 years ago

1.6.3

4 years ago

1.6.2

4 years ago

1.6.1

4 years ago

1.6.0

4 years ago

1.5.0

4 years ago

1.4.9

4 years ago

1.4.8

4 years ago

1.4.7

4 years ago

1.4.6

4 years ago

1.4.5

4 years ago

1.4.4

4 years ago

1.4.3

4 years ago

1.4.1

4 years ago

1.4.0

4 years ago

1.3.0

5 years ago

1.2.1

5 years ago

1.2.0

5 years ago

1.1.0

5 years ago

1.0.0

5 years ago

0.4.0

5 years ago

0.3.0

5 years ago

0.2.1

5 years ago

0.2.0

6 years ago

0.1.1

6 years ago

0.1.0

6 years ago

0.0.6

6 years ago

0.0.5

6 years ago

0.0.4

6 years ago

0.0.3

6 years ago

0.0.2

6 years ago

0.0.1

6 years ago