2.0.3 • Published 10 months ago
@j-o-r/apiserver v2.0.3
@j-o-r/apiserver
Fast http api server An easy way to expose a class/object as an API for micro http services
npm install --save @j-o-r/apiserverProject Overview: This project is an HTTP API server designed to expose classes or objects as APIs.
Simple Usage Example:
import {server} from '@j-o-r/apiserver';
// This also could be an object
class TestController {
static async index(client) {
// Local endpoint: http://127.0.0.1:9022/testcontroller/index
await client.serve(200, { 'joe': ['bar'] });
}
static async visitme(client) {
// Local endpoint: http://127.0.0.1:9022/testcontroller/visitme?q=yes
// @example:
const params = client.parameters();
const query = client.query();
const method = client.method();
await client.serve(200, { params, query, method});
}
/**
* Stream/Chunk javascript content
* @param {ClientWrapper} client
*/
static async stream(client) {
// Local endpoint: http://127.0.0.1:9022/testcontroller/stream
// Create a stream
client.writeHeaders(200);
// Open object with an array
await client.write('{"test":[');
let i = 0;
let len = 10;
for (; i < len; i++) {
// The last object should not have a ','
const SEP = (i + 1 === len) ? '' : ',';
await client.write(JSON.stringify({
id: i,
date: new Date(),
collection: ['one', 'two'],
escape: ' escape " me'
}) + SEP);
}
await client.write(']}');
await client.end();
}
static error(client) {
// Local endpoint: http://127.0.0.1:9022/testcontroller/error
await client.serve(500, 'Error: an error');
}
}
await server.create('testcontroller', { port: 9022, host: '127.0.0.1' }, TestController);@see scenarios/apiObject.js for a more complete example.
Use case
A typical use case would be to launch this service on a high port (> 1024) as a regular 'linux' user. And create a VHOST in 'apache' or 'nginx' and re-route requests to the internal port.
NGINX example:
server {
# --------------- customer conf ------------------
server_name my.test.com;
set $proxy_port 9022; # local port
# ------------------------------------------------
client_max_body_size 50M;
client_body_timeout 60s;
keepalive_timeout 70;
add_header X-Robots-Tag "none" always;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
location / {
# no se encuentra para todas las solicitudes
return 404;
}
# This should reflects the namespace used on `server.create`
location /testcontroller {
# pasar solicitudes a punto final
proxy_pass http://127.0.0.1:$proxy_port$request_uri;
}
# listen to IPV6 and http2
listen [::]:443 ssl http2;
# listen to IPV4 and http2
listen 443 ssl http2;
ssl_certificate /etc/cert//my.test.com/fullchain.pem;
ssl_certificate_key /etc/cert/my.test.com/privkey.pem;
}The url now would be:
https://my.test.com/testcontroller/indexLicense
This project is licensed under the Apache License, Version 2.0.