Package Exports
- node-rest-server
Readme
node-rest-server
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-serverFrom Github packages
npm install @nishant-labs/node-rest-serverImporting
The package supports multiple import patterns:
ES Modules (recommended)
// Default import
import NodeRestServer from 'node-rest-server';
// Named import
import { NodeRestServer } from 'node-rest-server';
// With TypeScript
import NodeRestServer, { RouteConfiguration, ServerConfiguration } from 'node-rest-server';CommonJS
// Default import
const NodeRestServer = require('node-rest-server');
// Named import
const { NodeRestServer } = require('node-rest-server');Usage
// Initialize server with configuration
const serverInstance = NodeRestServer(routeConfig, serverConfig);
// Add event listeners if needed
serverInstance.addListener('listening', () => console.log('Server started'));
serverInstance.addListener('close', () => console.log('Server shutdown complete'));
// Server Events
// - 'listening': Emitted when server starts listening
// - 'close': Emitted when server is fully shutdown
// - 'connection': Emitted when new connection is established
// - 'error': Emitted when server encounters an errorServer Shutdown
The server provides two shutdown modes:
// Graceful shutdown - waits for existing requests to complete (recommended)
await serverInstance.close();
// Forced shutdown - immediately closes all connections
await serverInstance.close(true);Shutdown behavior:
- Graceful shutdown waits for existing requests to complete
- Forced shutdown immediately closes all connections
- Built-in 30-second timeout protection
- Automatic cleanup of resources and event listeners
- Returns Promise<Error | undefined>
Example with error handling:
try {
// Attempt graceful shutdown
await serverInstance.close();
console.log('Server shutdown complete');
} catch (error) {
if (error.message.includes('timed out')) {
// Timeout occurred, try forced shutdown
await serverInstance.close(true);
} else {
console.error('Shutdown failed:', error);
}
}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:-
- Path: Uri which will serve a resource in rest server
- Route Options: Options which define working of the path and also decide status and response payload.
Route Options
| Name | Type | Default | Description |
|---|---|---|---|
| method | String |
GET |
Method defines the type of request controller will handle |
| headers (optional) | Record<String, String> |
Specify static headers to be passed in response | |
| status (optional) | String |
200 |
An appropriate HTTP response status code which server will give response for a request |
| controller | function|Object |
This 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. |
|
| middlewares | Function |
undefined |
List of ExpressJS compliant middlewares |
Controller method
A controller receives two parameters:
requestData: Contains request information including:url: Full request URLbody: Request bodypathParams: URL path parametersqueryParams: URL query parametersheaders: Request headersmethod: HTTP methodrawRequest: Original Express request object (optional)filter: Data from global filter if configured
controllerOptions: Contains configured options likegetDatabaseConnection
A controller can return:
- an object with
status,headersandpayload;
{
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
Promisewhich 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 }) => {
// Access request data
const { method, body, pathParams, rawRequest } = requestData;
// method will be 'POST'
const dataFromDB = await getDatabaseConnection(requestData);
return { status: 200, payload: { data: 'Data', dataFromDB } };
},
},
{
method: 'GET',
controller: (requestData) => {
// Access filter data if global filter is configured
const { filter } = requestData;
return { status: 200, payload: { data: 'Data', filterData: filter } };
},
},
],
'/async/endpoint': {
method: 'POST',
controller: (requestData) => {
// Access original Express request if needed
const { rawRequest } = requestData;
return { status: 200, payload: { data: 'Async data' } };
},
},
};Server Configuration (optional)
This manages how the server will be configured
| Name | Type | Default | Description |
|---|---|---|---|
| basePath | String |
Common prefix for all the routes | |
| port | Number |
8000 |
Port on which server will serve the content |
| delay (sec) | Number |
0 |
Forcefully delay the response timing in seconds |
| logger | Object|Boolean |
true |
Enable 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 |
| getDatabaseConnection | function |
Provides a mechanism to get DB connection using globally available method passed (supports Promise) to controller in second parameter. |
|
| filter | function |
Enable application level filter and pass returned value(supports Promise) to controller. |
|
| cors | Object |
undefined |
Config should be as per cors package |
| headers | Object|Function |
undefined |
Any object with headers or a function which returns object with headers |
| middlewares | Function |
undefined |
List of ExpressJS compliant middlewares |
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',
};
},
};