Skip to the content.

OneBlink API CLI

Handlers

Handlers are the files that hold the function(s) that are executed for HTTP requests.

Note: ES Modules are now supported natively by the OneBlink API CLI. See how to upgrade here.

Exports

A handler file can export either a single function or an object with HTTP request methods for properties.

Function

Will be executed for all HTTP request methods

module.exports = function (request, response) {
  // Will be executed for all HTTP request methods
}

Object

Must have properties containing functions for each supported HTTP request method

module.exports.get = function (request, response) {
  // Will only be executed for GET HTTP method requests
}

module.exports.post = function (request, response) {
  // Will only be executed for POST HTTP method requests
}

module.exports.put = function (request, response) {
  // Will only be executed for PUT HTTP method requests
}

module.exports.delete = function (request, response) {
  // Will only be executed for DELETE HTTP method requests
}
Notes

Function Arguments

The handler function(s) will always have the request and response arguments passed to them when executed.

Request

interface request = {
  body: any,
  headers: {
    [id:string]: string
  },
  method: 'get' | 'post' | 'put' | 'delete' | 'patch'
  url: {
    host: string,
    hostname: string,
    params: {
      [id:string]: string
    },
    pathname: string,
    protocol: 'http:' | 'https:',
    querystring: string,
    query: {
      [id:string]: string | string[]
    }
  }
}
Example
module.exports = function (request, response) {
  return request
}

The handler above would return the following json object when executing the curl command below into from a terminal

curl "http://localhost:3000/request?key=123"
{
  "body": null,
  "headers": {
    "host": "localhost:3000",
    "user-agent": "curl/7.49.1",
    "accept": "*/*"
  },
  "method": "get",
  "route": "/request/{id}",
  "url": {
    "protocol": "http:",
    "host": "localhost:3000",
    "hostname": "localhost",
    "query": {
      "key": "123"
    },
    "pathname": "/request/abc",
    "params": {
      "id": "abc"
    }
  }
}

Response

interface Response = {
  headers: {
    [id:string]: string
  },
  payload: any,
  statusCode: number,
  setHeader: (key: string, value: string) => Response,
  setPayload: (payload: any) => Response,
  setStatusCode: (code: number) => Response
}