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.
- 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
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;
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();
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();
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.
History of releases is in the changelog.
The code is released under the MIT License.