2.0.3 • Published 3 years ago

@jalik/rest-server v2.0.3

Weekly downloads
3
License
MIT
Repository
github
Last release
3 years ago

@jalik/rest-server

GitHub package.json version Build Status GitHub GitHub last commit GitHub issues npm

Introduction

This is a REST API server based on the excellent Express web server. The main goal is to simplify the management of any APIs. Note that this server is independent and cannot work as a middleware in an existing express application, it needs to run on a dedicated port.

Why using this ?

  • The server restarts automatically when a route is added or removed, or if the port changed
  • Routes are objects which can be used to generate API documentation
  • You can use any express middleware as it is based on it

Creating a REST API

When creating an API, you must at least define a method, a path and a handler. Note that the handler is an Express handler (see https://expressjs.com/en/starter/basic-routing.html).

Since you may have a lot of APIs, it's recommended to put them in separate files like below.

import { Route } from '@jalik/rest-server';

const GetDateAPI = new Route({
  cors: false,
  method: 'GET',
  path: '/v1/date',
  handler(req, resp) {
    resp.status(200).end(JSON.stringify({ 
      date: new Date().toISOString()
    }));
  }
});

export default GetDateAPI;

Creating a server

To serve the APIs you've created, you need a web server, so let see how to do that.

import Server from '@jalik/rest-server';

// Setup server
const server = new Server({
  port: 3001,
  // Automatically restart the server
  // if an API has been added or removed.
  restartOnChange: true,
});

// Add routes
// ... server.addRoute(route);
// ... server.addRoute(route);

// Finally start the server
server.start();

Adding a middleware

import Server from '@jalik/rest-server';

// Setup server
const server = new Server({
  port: 3001
});

// Log request date, method and URL to the console
server.addMiddleware((req, resp, next) => {
  console.log(`${new Date()} ${req.method} ${req.url}`);
  next();
});

server.start();

Enabling CORS

To enable CORS on a route, just set the cors option to true when creating a route, and eventually define the corsOptions for more control.

import { Route } from '@jalik/rest-server';

const AuthAPI = new Route({
  cors: true,
  corsOptions: {
    origin: 'http://example.com'
  },
  method: 'POST',
  path: '/auth',
  handler(req, resp, next) {
    // logic...
  }
});

For more details, see https://expressjs.com/en/resources/middleware/cors.html#configuring-cors.

Changelog

History of releases is in the changelog.

License

The code is released under the MIT License.

2.0.3

3 years ago

2.0.2

4 years ago

2.0.1

4 years ago

2.0.0

4 years ago

1.1.3

5 years ago

1.1.2

6 years ago

1.1.1

6 years ago

1.1.0

6 years ago

1.0.0

6 years ago