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

@tne/express-app

v1.4.7

Published

TNE - wrapper for Express js application

Downloads

26

Readme

@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

| Param | Type | Required? | Description | |-|-|-|-| | propToPrefix | string | true | The 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

| Param | Type | Required? | Description | |-|-|-|-| | appPath | string | true | The __dirname when using from src/index.ts file.. | | environment | string | false | When provided your app will use this env instead NODE_ENV. | | appName | string | false | Your application name. | | logger | ILoggerSettings | false | valid ILoggerSettings object. | | locals | any | false | any data that you want push to app.locals. | | port | number | false | The port for tour webApplication; defaults to 3000. | | faviconPath | string | false | Relative path to favicon. | | publicFolder | string | false | Relative path to Public folder. | | defaultPage | number | false | Default Page value for req.pager helper. | | defaultPerPage | number | false | Default Per_Page value for req.pager helper. | | corsOptions | CorsOptions | false | valid CorsOptions object. | | compressionOptions | CompressionOptions | false | valid CompressionOptions object. | | urlEncodedOptions | OptionsUrlencoded | false | valid OptionsUrlencoded object. | | jsonOptions | OptionsJson | false | valid OptionsJson object. | | appMiddleware | RequestHandler[] | false | A valid middleware array that you want to use in your app. | | routesFolder | string OR string[] | false | Relative path to Route(s) Folder. | | errorHandler | ErrorRequestHandler | false | valid ErrorRequestHandler function. |


Back to Menu

ILoggerSettings

Used to config the Application logger

Parameters

| Param | Type | Required? | Description | |-|-|-|-| | format | Format | false | valid winston Format. | | fileCfg | IFileSettings | false | valid IFileSettings object. | | customTransports | Transport[] | false | array of your own additional winston Transports |


Back to Menu

IFileSettings

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

Parameters

| Param | Type | Required? | Description | |-|-|-|-| | logsPath | string | true | valid Path where logFiles will be placed. | | logFile | string | false | basename for fileLogs. | | datePattern | string | false | datePattern 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

| Param | Type | Required? | Description | |-|-|-|-| method | string OR string[] | true | Method, list of methods delimited by commas or an array of valid methods for Express.js. path | string | true | Route path valid for Express.js. middleware | RequestHandler[] | false | A valid middleware array that you want to prefix to your Express.js Route handler.