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

node-rest-server-2

v3.3.4

Published

Configurable node rest server

Downloads

32

Readme

node-rest-server-2

NPM

Configuration only node rest server

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

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. Install using below command.

npm install --save node-rest-server-2

Importing

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

// call it as function and pass configuration
NodeRestServer(routeConfig, serverConfig);

Usage Example

import NodeRestServer from 'node-rest-server-2';

const routeConfig = {
	'/api1': {
		method: 'GET',
		status: 200,
		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

| Name | Type | Default | Description | | :------------------ | :----------------- | :------ | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | method | String | GET | Method defines the type of request controller will handle | | 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. | | status (optional) | String | 200 | An appropriate HTTP response status code which server will give response for a request |

Controller method

A controller can either return

  • an object with status and payload;
{
  status: 500, // should be a number
  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,
		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: async (requestData) => {
				// requestData.method will be GET 
				return { status: 200, payload: { data: 'Async data' } };
			},
		}
	],
	'/async/endpoint': {
		method: 'POST',
		controller: async (requestData) => {
			// Some DB/api calls
			return { status: 200, payload: { data: 'Async data' } };
		},
	}, 
	'/image': {
		method: 'GET',
		controller: async (requestData) => {
			return { status: 200, filePath: 'path/to/image' };
		}
	}
};

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 |

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: '*'
  },
};