Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@axmit/express-core

Package Overview
Dependencies
Maintainers
3
Versions
31
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@axmit/express-core

A reusable module implementing express application

  • 2.0.0-beta.2
  • npm
  • Socket score

Version published
Maintainers
3
Created
Source

Common information

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

Table of contents

  • Prerequisites

  • Installation

  • Included Modules

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

Keywords

FAQs

Package last updated on 10 May 2019

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc