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

@ctt/crud-api

v1.0.0-rc.1.8.10

Published

A microservice boilerplate

Downloads

96

Readme

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