4.1.0 • Published 3 months ago

node-rest-server v4.1.0

Weekly downloads
10
License
MIT
Repository
github
Last release
3 months ago

node-rest-server

NPM

Configuration only node rest server

Get your own rest based nodejs server within minutes by just providing endpoints and controller.

Repo is migrated to publish module js bundle along with typescript typings.

Features

  • Ready to use rest server in minutes.
  • Free from all boilerplate code for creating and managing the server, so that developer can focus on actual business logic.
  • Simple configuration to generate response data.
  • Supports all http methods along with async connections

Where you can use

  • Can be used as a stub server for any application(like ReactJS, AngularJS) to mock server response during development.

  • Can be used for creating rest micro-service in minutes (help me improve this library)

Do you use for anything else!

Installation

This is a Node.js module available through the npm registry and github packages. Install using below command.

From NPM Registry

npm install --save node-rest-server 

From Github packages

npm install @nishant-labs/node-rest-server

Importing

import NodeRestServer from 'node-rest-server'; // ES6
// or
const NodeRestServer = require('node-rest-server'); // ES5
// or
import { NodeRestServer } from 'node-rest-server'; // If you like to use named export

// Invoke it as function and pass configuration
const serverInstance = NodeRestServer(routeConfig, serverConfig);

serverInstance.addListener('<event name>', () => void); // Add event listener
serverInstance.close(); // explicitly close server

Usage Example

import NodeRestServer from 'node-rest-server';

const routeConfig = {
	'/api1': {
		method: 'GET',
		status: 200,
		header: { 'x-data': 'value' },
		controller: () => 'Data',
	},
};

NodeRestServer(routeConfig);

Sample

example directory provides a sample application explaining the use of this library.

Route Configuration

A route configuration is an object with key(route path) value(route options) pair:-

  1. Path: Uri which will serve a resource in rest server
  2. Route Options: Options which define working of the path and also decide status and response payload.

Route Options

NameTypeDefaultDescription
methodStringGETMethod defines the type of request controller will handle
headers (optional)Record<String, String>Specify static headers to be passed in response
status (optional)String200An appropriate HTTP response status code which server will give response for a request
controllerfunction\|ObjectThis function/object will contain the business logic for the route path. For a function an object is passed which will contain request url, body, params and header and response of filter to be used.

Controller method

A controller can either return

  • an object with status, headers and payload;
{
  status: 500, // should be a number
	headers: { 'x-data': 'value' }, // optional header, should be a string record
  payload: "Hello world" // user can send any valid json converted using JSON.stringify()
}

or

  • a response data object (valid as per JSON.stringify() json spec)

  • a Promise which then resolves to return data with above spec

Route config Example

const routeConfig = {
	'/endpoint1': {
		method: 'GET',
		status: 200,
		headers: { 'x-data': 'value' },
		controller: () => 'Data',
	},
	'/endpoint2': {
		method: 'POST',
		controller: async (requestData, { getDatabaseConnection }) => {
			const dataFromDB = await getDatabaseConnection();
			return { status: 200, payload: { data: 'Data', dataFromDB } };
		},
	},
	'/endpoint3': [
		{
			method: 'POST',
			controller: async (requestData, { getDatabaseConnection }) => {
				// requestData.method will be POST
				const dataFromDB = await getDatabaseConnection();
				return { status: 200, payload: { data: 'Data', dataFromDB } };
			},
		},
		{
			method: 'GET',
			controller: (requestData) => {
				// requestData.method will be GET
				return { status: 200, payload: { data: 'Async data' } };
			},
		},
	],
	'/async/endpoint': {
		method: 'POST',
		controller: (requestData) => {
			// Some DB/api calls
			return { status: 200, payload: { data: 'Async data' } };
		},
	},
};

Server Configuration (optional)

This manages how the server will be configured

NameTypeDefaultDescription
basePathStringCommon prefix for all the routes
portNumber8000Port on which server will serve the content
delay (sec)Number0Forcefully delay the response timing in seconds
loggerObject\|BooleantrueEnable logging for application, a boolean value will enable/disable all logging features, an object can be passed with property enable to toggle the logging and debug to enable/disable debug logs
getDatabaseConnectionfunctionProvides a mechanism to get DB connection using globally available method passed (supports Promise) to controller in second parameter.
filterfunctionEnable application level filter and pass returned value(supports Promise) to controller.
corsObjectundefinedConfig should be as per cors package
headersObject\|FunctionundefinedAny object with headers or a function which returns object with headers

Server config Example

const serverConfig = {
  basePath: '/base/api',
  port: 8080,
  delay: 2,
  logger: {
      enable: true,
      debug: false,
  },
  getDatabaseConnection: async () => {
		return Promise.resolve('db connection');
	}
  filter: (requestData) => {
      return { data: 'calculate' };
  },
  cors: {
    origin: '*'
  },
	headers: () => {
		return {
			'x-data': 'my header',
		};
	},
};
4.1.0

3 months ago

4.0.0-7

6 months ago

4.0.0-8

6 months ago

4.0.0-5

7 months ago

4.0.0-6

7 months ago

4.0.0-9

6 months ago

4.0.0

6 months ago

4.0.0-3

9 months ago

4.0.0-1

11 months ago

4.0.0-2

9 months ago

4.0.0-0

1 year ago

3.2.0

2 years ago

3.1.0

2 years ago

3.0.0

3 years ago

2.1.0

3 years ago

2.0.0

4 years ago

1.2.2

4 years ago

1.2.1

4 years ago

1.2.0

4 years ago

1.1.0

6 years ago

1.0.1

6 years ago

1.0.0

6 years ago

0.0.7

9 years ago

0.0.6

9 years ago

0.0.5

9 years ago

0.0.4

9 years ago