2.0.1 • Published 5 years ago

@axmit/express-core v2.0.1

Weekly downloads
-
License
ISC
Repository
gitlab
Last release
5 years ago

Common information

This package provide reusable module for creating express applications using TypeScript and NodeJS

Table of contents

Prerequisites

Before using this package you need to authorize yourself into npm registry using npm adduser

Installation

npm i @axmit/express-core or yarn add @axmit/express-core

Included Modules

This library includes modules to help you build your applications faster you only need to specify .env to configure
your environment. Available .env variables:

PORT = 3030 //defines your server port
BASE_URL = /

ExpressApplication

Class ExpressApplicaion is base express application class which contains almost all you need to create your awesome app
Usage example:

import { ExpressApplication } from '@axmit/express-core';

class YourApplicationName extends ExpressApplication {
  async start() {
    await super.start(yourConfigFile, pathToLogs);
  }
}

new YourApplicationName().start();

After calling start method your express server will start on specified by yourself port or on port 3030 by default

Also ExpressApplication provides build in Dependency Injector(DI) To add custom module define it like this

export function yourModuleName(dependency1, dependency2) {
 //do something cooll here}yourModuleName.$inject = ['dependency1', 'dependency1'];

And register it in your application class

this.registerService('yourModuleName', yourModuleName);

Note: this is an instance of the ExpressApplication class

Now you can inject it in other modules using

moduleName.$inject = ['yourModuleName'];

Also you can provide optional dependencies using

moduleName.$inject = ['?yourModuleName'];

You can get registered service in ExpressApplication class using

this.container.get('yourModuleName');

Available ExpressApplication methods

.addRouter(url, provider): void

Params:

  • url {String} - base url to connect your router
  • provider {(container) => router} - function returning router instance see ApplicationRouter section

This method add new router to your application

.registerService(id: string, service: Function)

Register service in DI container
Params

  • id {String} - service identification string
  • service {Function} - function your want to use as injectable

.addModule(module)

Add module to your application see Module section

.addBaseSwaggerSchema(schema)

Add base definitions for swagger (ex. Errors, BaseEntities etc.)

.start(config, logPath, additionalMiddlewares = [])

Start application
Params:

  • config {Object} - application config (automatically injected as DI container)
  • logPath {String} - path to your application logs
  • additionalMiddlewares {Array} - additional express middlewares to be used before anything else (specific error handling as an example), this param must provide array of express middlewares functions ((req, res, nex) => void)

Config variables:

withoutServer?: boolean; //if true will not start express server
validateRequests?: boolean; //if true will validate every request using json swagger schema
swaggerInfo?: ISwaggerInfo; //Swagger UI information

.addJob(schedule, provider)

Schedules cron job to be fulfilled
Params:

  • schedule {String} - crontab time mask
  • provider {Function} - callback returning function to execute by crontab mask (by default first param is DI container to get injected service)

Usage:

function getDateJob() {
  console.log(new Date());
}

this.addJob('* * * * * *', () => getDateJob);

This will print current time every second

.stop()

Stops application destroying database connections and stopping jobs and modules

httpClient

Base http promise wrapped service to make http request
Usage:

import { httpClient } from '@axmit/express-core';
await httpClient.request(options | url);

See request npm module for more info

ApplicationRouterBuilder

Builder for express routing implementation, it provides extended version of express router by adding methods to write swagger docs (see example)
Using:

import { ApplicationRouterBuilder } from '@axmit/express-core';

const builder = new ApplicationRouterBuilder();
builder
  .useNamespace('/yourPath')
  .addSwaggerSchema({
    swagerSchemaName: {
      type: 'object',
      required: ['id', 'name'],
      properties: {
        id: {
          type: 'number',
          description: 'id of something'
        },
        name: {
          type: 'string',
          description: 'name of somethiing'
        }
      }
    }
  })
  .useSwaggerDocs({
    get: {
      tags: ['Your Tags'],
      summary: 'Summary',
      description: 'Descrition',
      consumes: ['application/json'],
      produces: ['application/json'],
      parameters: [
        {
          name: 'filter',
          description: 'filter',
          required: false,
          type: 'string',
          in: 'query'
        }
      ],
      responses: {
        '200': {
          description: 'description',
          type: 'array',
          items: {
            $ref: '#/definitions/swagerSchemaName'
          }
        }
      }
    }
  })
  .buildNamespace()
  .get(yourMiddlewaresGoesHere);

export const awesomeRouter = builder.buildRouter();

By using useSwaggerDocs and addSwaggerSchema methods you can define your swagger docs which will be automatically compile and be available at http://yourHost:port/swagger domain

To add this router into your application just call

this.addRouter('/', awesomeRouter);

in your base Application class

API:

.useNamespace(namespace: string)

Define route namespace (ex. /users, /users/:id)

.useSwaggerDocs(docs)

Adds swagger docs to namespace

.addSwaggerSchema(schema)

Adds swagger definitions to router

.buildNamespace()

Builds namespace and return express router route instance, where you can add any request methods

Example:
builder
  .useNamespace('/test')
  .buildNamespace()
  .get((req, res, next) => {
    res.json({
      sampleString: 'string'
    });
  });

This code will create GET /test endpoint which will return {"sampleString": "string"} json object

.buildRouter()

Builds router to be implemented using ExpressApplication addRouter method