1.4.7 • Published 5 years ago

@tne/express-app v1.4.7

Weekly downloads
15
License
MIT
Repository
github
Last release
5 years ago

@tne/express-app

A library that encapsulates the Web Application framework Express.js and other common middleware tools such as compression, cors, morgan, serve-favicon and also the joi the famous javascript schema validation tool, in order to provide you a base to load easily the resources and services for your web application.


Menu

Installation

Creating a web service with @tne/express-app

ExpressApplication

Foundation Libraries

Decorators

Interfaces


Back to Menu

Installation

You can install through the node package managers:

NPM

$ npm install --save @tne/express-app

Yarn

$ yarn add @tne/express-app

Back to Menu

ExpressApplication

This Object is an interface that provides us with the methods that will allow you to create, destroy or obtain the instance of our web application.

Methods

Example usage

import { ExpressApplication } from '@tne/express-app';
// code here

Back to Menu

construct()

This method will build a singleton instance of class ExpressCoreApplication, start the http service and return a reference to the built instance.

The method has two overloads:

  • string
  • IAppSettings

String Example

file: src/index.ts

import { ExpressApplication } from '@tne/express-app';

ExpressApplication.construct(__dirname);

IAppSettings Example

file: src/index.ts

import { ExpressApplication, IAppSettings } from '@tne/express-app';

const config: IAppSettings = {
	appPath: __dirname,
	// ... other IAppSettings here
};

ExpressApplication.construct(config);

Back to Menu

destruct()

This method will stop the http service created by Express.js and destroy the singleton instance of the ExpressCoreApplication class (if they existed).

Example

import { ExpressApplication } from '@tne/express-app';

ExpressApplication.destruct();

Back to Menu

getInstance()

This method returns a reference to the singleton instance of class ExpressCoreApplication, if it exists, otherwise it will return null.

Example

import { ExpressApplication } from '@tne/express-app';

const app = ExpressApplication.getInstance();

Back to Menu

getExpressApp()

This method returns a reference to the app property (which is the Express.js application) of the singleton instance of the ExpressCoreApplication class, if it exists, otherwise it will return null.

Example

import { ExpressApplication } from '@tne/express-app';

const expressApp = ExpressApplication.getExpressApp();

Back to Menu

Express

There is not much to add, just the Express.js library on which this library works, free to use it as you wish.

For example, you can use this export to create a mock Server for your unit tests.

Example

import { express } from '@tne/express-app';

const app = express();

Back to Menu

joi

just the joi to create amazing schema-based validations.

Example

import { joi } from '@tne/express-app';

const pager = joi.object().keys({
	page: joi.number().integer().positive().min(1).required(),
	per_page: joi.number().integer().positive().min(1).required(),
});

const { error, value } = joi.validate({ page: 1, per_page: 50 }, pager);
// result.error === null -> valid

Back to Menu

Decorators

This library provides you with some decorators that will help you simplify or extend the functionalities of your web application.


Back to Menu

@Config

The class decorator @config will freeze the decorating class as well as its prototype, so that it can not be modified externally.

Example

import { Config } from '@tne/express-app';

@Config
export class ExampleClass {
	// class that I do not want to modify externally
}

Back to Menu

@FinalClass

This "class decorator" transforms the class into a "Final class", so it can not be extended by any other class.

Example

import { FinalClass } from '@tne/express-app';

@FinalClass
export class SomeFinalClass {
	// class that I do not want to extend
}

export class OtherClass extends SomeFinalClass {
	// code here!
}

The above code will throw an error when loading the "OtherClass" class.


Back to Menu

@Prefix

This "property decorator" prefixes the value of the property of the string or property provided in the argument to the decorated property.

Parameters

ParamTypeRequired?Description
propToPrefixstringtrueThe property that will be prefixed to the property that is being decorated.

Constraints

It only works if all the properties of the decorated class are static.

Example

import { Config, Prefix } from '@tne/express-app';

@Config
export class Routes {
	static baseUrl = '/';
	static apiUrl = '/api/v1/';

	@Prefix('apiUrl')
	static users = '/users/';

	@Prefix('apiUrl')
	static user = '/users/:id/';

	@Prefix('apiUrl')
	static users = '/users/';

	@Prefix('baseUrl')
	static view_users = '/users/:id/';

	@Prefix('baseUrl')
	static view_user = '/users/:id/';
}

Example output

import { Routes } from 'config/route';

console.log(Routes.user) // -> /api/v1/users/:id/;
console.log(Routes.view_user) // -> /users/:id/;

Back to Menu

@Endpoint

This "method decorator" is used in conjunction with @ExpressRouter to transform the methods of a class into usable Route handler of Express.js.

Your must provide an object that implements the IEndpointConfig Interface as argument.

Example

import { Endpoint, ExpressRouter } from '@tne/express-app';
import { middlewareFunc } from 'some/path';

@ExpressRouter
export default class ExampleRouter {
	@Endpoint({
		method: 'GET'
		path: '/users'
	})
	getUsers(req,res){
		// GET Route handler code here!
	}

	@Endpoint({
		method: 'POST'
		path: '/users'
	})
	postUsers(req,res){
		// POST Route handler code here!
	}

	@Endpoint({
		method: 'PUT'
		path: '/users/:id',
		middleware: [middlewareFunc]
	})
	putUsers(req,res){
		// PUT Route handler code here!
	}
}

Back to Menu

@ExpressRouter

This "class decorator" is used in conjunction with @Endpoint to transform the methods of a class into usable Route handlers for 'Express.js'.

Example

import { Endpoint, ExpressRouter } from '@tne/express-app';
import { middlewareFunc } from 'some/path';

@ExpressRouter
export default class ExampleRouter {
	@Endpoint({
		method: 'GET'
		path: '/users'
	})
	getUsers(req,res){
		// GET Route handler code here!
	}

	@Endpoint({
		method: 'POST'
		path: '/users'
	})
	postUsers(req,res){
		// POST Route handler code here!
	}

	@Endpoint({
		method: 'PUT'
		path: '/users/:id',
		middleware: [middlewareFunc]
	})
	putUsers(req,res){
		// PUT Route handler code here!
	}
}

In runtime, above example will behave in the following way:

const { Router } = require('express');
const { middlewareFunc } = require('some/path');
const router = Router();

module.exports.default =  router
.get('/users', (req, res) => { /* GET Route handler code here! */ })
.post('/users', (req, res) => { /* POST Route handler code here! */ })
.put('/users/:id', middlewareFunc, (req, res) => { /* PUT Route handler code here! */ })

Back to Menu

Interfaces

The interfaces that this library provides and that are described here provide help to the developer that will consume this library to build incredible web applications.

Constraints

The interfaces mentioned in this section will be importable only if you are developing your web application with typescript.


Back to Menu

IAppSettings

Used as an argument for the ExpressApplication.construct method, and used to create an instance of the class ExpressCoreApplication with arguments different from those used by default.

Parameters

ParamTypeRequired?Description
appPathstringtrueThe __dirname when using from src/index.ts file..
environmentstringfalseWhen provided your app will use this env instead NODE_ENV.
appNamestringfalseYour application name.
loggerILoggerSettingsfalsevalid ILoggerSettings object.
localsanyfalseany data that you want push to app.locals.
portnumberfalseThe port for tour webApplication; defaults to 3000.
faviconPathstringfalseRelative path to favicon.
publicFolderstringfalseRelative path to Public folder.
defaultPagenumberfalseDefault Page value for req.pager helper.
defaultPerPagenumberfalseDefault Per_Page value for req.pager helper.
corsOptionsCorsOptionsfalsevalid CorsOptions object.
compressionOptionsCompressionOptionsfalsevalid CompressionOptions object.
urlEncodedOptionsOptionsUrlencodedfalsevalid OptionsUrlencoded object.
jsonOptionsOptionsJsonfalsevalid OptionsJson object.
appMiddlewareRequestHandler[]falseA valid middleware array that you want to use in your app.
routesFolderstring OR string[]falseRelative path to Route(s) Folder.
errorHandlerErrorRequestHandlerfalsevalid ErrorRequestHandler function.

Back to Menu

ILoggerSettings

Used to config the Application logger

Parameters

ParamTypeRequired?Description
formatFormatfalsevalid winston Format.
fileCfgIFileSettingsfalsevalid IFileSettings object.
customTransportsTransport[]falsearray of your own additional winston Transports

Back to Menu

IFileSettings

Used to config the Application file logger with daily rotate function.

Parameters

ParamTypeRequired?Description
logsPathstringtruevalid Path where logFiles will be placed.
logFilestringfalsebasename for fileLogs.
datePatternstringfalsedatePattern for fileLogs, defaults to YYYYMMDD.

Back to Menu

IEndpointConfig

Interface Used to describe arguments for the method decorator "@Endpoint".

It helps us to transform the decorated method into a useful Route handler for Express.js.

Parameters

ParamTypeRequired?Description
methodstring OR string[]trueMethod, list of methods delimited by commas or an array of valid methods for Express.js.
pathstringtrueRoute path valid for Express.js.
middlewareRequestHandler[]falseA valid middleware array that you want to prefix to your Express.js Route handler.