1.5.0 • Published 4 years ago

ams-http-service v1.5.0

Weekly downloads
-
License
ISC
Repository
-
Last release
4 years ago

ams-http-service

Install

Quickly generating a project directory using yeoman
npm install -g generator-ams-http-service
npx yo ams-http-service cool-service
Otherwise
npm install --save ams-http-service

API

const {Env, Service} = 'ams-http-service'

const env = new Env()
const handler = async () => {result: 'hello world'}

const service = new Service(env, handler)
service.listen()

class Env (options)

This class wraps nconf and dotenv in order to provide sane defaults and added functionality.

By default it loads everything in the environment, dotenv and config.json files.

Notable defaults: {parseValues: true, separator: '__'}

Parameters

options.defaults

If present, must be an object mapping keys to their default values.

options.required

If present, must be an array of strings specifiying the required env variables.

Methods

assign(a: Object|(async) function)

If the parameter is an Object, all of its keys are assigned to the env.

If it is a function, it is eventually called, awaited, and any return value is assigned to the env.

async init()

When called, immediately executes and awaits the functions passed to assign().

This is called by Service instances before accepting any requests.

Defaults

PORT 9083

class Service (env, handler, options)

Parameters

env: Object required

env.PORT: number required

env.ALLOWED_CLIENT_IDS: string|array optional

​ Any clientid that is not in this list will receive a 401 (Unauthorized).

​ May contain *, in which case any clientid is acceptable, but one must be present in the request.

handler: (async) function(requestBody, ctx)required

​ May also be a map of requestBody.action to specific handlers. ​

function connectToDB (config, driverOptions)

const mongoDb = await connectToDB(env.MONGO)

Parameters

config: Object|string

If this parameter is a string, it must be a valid mongodb connection uri.

If is is an Object, then it should contain keys such as host, username, password, along with any options.

driverOptions: Object

Second parameter of MongoClient

Returns

MongoClient.Database instance

Code samples

Async env initialization
// *env.js*
const {Env, connectToDB} = require('ams-http-service')

const env = new Env({required: ['MONGO:HOST', 'MONGO:REPLICASET']})

env.assign(async () => {
  return {mongo: await connectToDB(env.MONGO)}
})

module.exports = env
// *index.js*
const {Service} = require('ams-http-service')
const env = require('./env')

const handler = async () => {return {result: 'hello'}}
const service = new Service(env, handler)

service.listen()