[JS]

John Siu's personal blog

Tech - Business Tool, Personal Toys

Simple API handler for node.js / expressjs

simple-api-express is an expressjs api handler (NOT middleware) that work with simple-api-client-ng2, an Angular 2 api service.

Index

Install

npm install simple-api-express

Usage Flow

simple-api-express depends on expressjs middleware bodyParser for json body decode.

const express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.listen(8080);

Import simple-api-express:

const SimpleApi = require('simple-api-express').SimpleApi;

Create api object with base url:

const apiDemoUrl = '/demo';
var apiDemo = new SimpleApi(apiDemoUrl, true); // enable debug

Register a function as api callback:

apiDemo.register('echo2',param => 'echo2:' + param);

You can also register all functions of an object as api callbacks:

apiDemo.registerObject(require('./api-object').DemoObj);

Use express post and SimpleApi.response() to handle incoming api request:

// Post request + API response
app.post(path.join(apiDemoUrl, '*'), (req, res) => apiDemo.response(req, res))

SimpleApi.handler() can be use if additioanl action(eg: customing response header or error page) is required before reply:

// Post request + API handler
app.post(path.join(apiDemoUrl, '*'), (req, res) => {
  // Log request body before process
  console.log(req.body);
  try {
    // Manual handler used, server code responsible to send result and handle error
    // Use manual handler if custom header or custom 404 error are needed
    let result = apiDemo.handler(req);

    // Result must be return in json format
    res.json(result);
  }
  catch (e) {
    // Catch api not found error
    res.status(e.status).end(e.error);
  }
})

API

constructor

SimpleApi(baseUrl:string, debug:boolean)

  • baseUrl will prefix all api url registered to this SimpleApi instance.
  • debug will enable/disable debug log. Default to false.
const SimpleApi = require('simple-api-express').SimpleApi;
const apiDemoUrl = '/demo';
var apiDemo = new SimpleApi(apiDemoUrl, true); // enable debug

debug

debug(enable: boolean) can enable/disable debug log.

apiDemo.debug(false);

list

list() return a string[] containing all registered api url.

console.log(apiDemo.list());

Output:

[ '/demo/echo', '/demo/echo2' ]

register

register(url:string,callback) register a callback function to url

  • url : Api url path after baseUrl. The resulting url for the api is baseUrl/url.
  • callback : a function that take a single argunment as api parameter, and return a result.
apiDemo.register('echo2',param => 'echo2:' + param);

registerObject

registerObject(object) register all functions of an object as api callbacks.

All functions of the object should take a single argunment as api parameter, and return a result.

The function name will be used api url.

var DemoObj = {
  echo(r) {
    return r;
  }
}

apiDemo.registerObject(DemoObj);

response

SimpleApi.response(req, res) is a handle function for incoming api post request. Api parameter will be passed to corresponding callback. Callback result will be passed back to api client.

req, res are request and response object pass in from expressjs post.

// Post request + API response
app.post(path.join(apiDemoUrl, '*'), (req, res) => apiDemo.response(req, res))

handler

SimpleApi.handler(req) is an api handler function. It will invoke the corresponding callback base on the request url, and return the result.

IT WILL NOT send out the result.

IT IS NOT a expressjs post handler function. It needed to be called INSIDE the post handler function.

Api handler can be use if additioanl action(eg: customing response header or error page) is required:

// Post request + API handler
app.post(path.join(apiDemoUrl, '*'), (req, res) => {
  // Log request body before process
  console.log(req.body);
  try {
    // Manual handler used, server code responsible to send result and handle error
    // Use manual handler if custom header or custom 404 error are needed
    let result = apiDemo.handler(req);

    // Result must be return in json format
    res.json(result);
  }
  catch (e) {
    // Catch api not found error
    res.status(e.status).end(e.error);
  }
})

Error Handleing

There are two types of error.

404 Not Found

When response() is called with an non-exist api url, it will response with a HTTP 404 Not Found.

When handle() is called with an non-exist api url, it will throw an error, which can be caught in the post handle function.

Callback throw

When response() is called, and the invoked api callback throw an error, which will be passed to remote client.

The remote client, using simple-api-client-ng2, will throw an exception with the error.

When handle() is called, and the invoked api callback throw an error, the error can be inspected from the result object.

let result = apiDemo.handler(req);

// If api callback return
if(result.error) {
  console.log(result.error);
}

// Result must be return in json format
res.json(result);

The remote client, using simple-api-client-ng2, will throw an exception with the error.

Example

A detail example for both simple-api-express and simple-api-client-ng2.

11 Oct 2016 #javascript #angular #expressjs #typescript

comments powered by Disqus