@dominiklessel/serverless-utils

1.0.0 • Public • Published

@dominiklessel/serverless-utils

Opinionated utils for serverless applications.

Intended to be used with AWS Lambda and AWS API Gateway.

Usage

// Modules
const boom = require('boom')
const { setRequestContext, parseParams, sendRes } = require('@dominiklessel/serverless-utils')
const joi = require('joi')

// Config
const cors = true
const callbackWaitsForEmptyEventLoop = false

// Schemas
const pathParamsSchema = joi.object().keys({
  idFoo: joi.number().required()
})

const queryParamsSchema = joi.object().keys({
  fields: joi.string().allow('').default('*')
})

const bodySchema = joi.object().keys({
  buz: joi.string().allow('').default(null)
})

module.exports.handler = (event, context, callback) => {
  context.callbackWaitsForEmptyEventLoop = callbackWaitsForEmptyEventLoop
  setRequestContext(event, context)

  const {
    err,
    pathParams: {
      idFoo
    } = {},
    queryStringParams: {
      fields
    } = {},
    body
  } = parseParams(event, { pathParamsSchema, queryParamsSchema, bodySchema })

  if (err) {
    return sendRes({ body: boom.badRequest(err.details[0].message), cors }, callback)
  }

  // Send body back …
  sendRes({ body, cors }, callback)
}

API

sendRes(options, handlerCallback)

Sends an AWS API Gateway integration response. If body is a boom-object, the correct status code is automatically set and AWS API Gateway can send the appropriate HTTP status code.

options

Required
Type: Object

statusCode

Type: Number
Default: 200

headers

Type: Object
Default: {}

body

Type: Object
Default: null

cors

Type: Boolean
Default: false

handlerCallback

Required
Type: Function

AWS Lambda handler callback

parseParams(lambdaHttpEvent, schemas)

Parse an AWS Lambda HTTP event

lambdaHttpEvent

Required
Type: Object

AWS Lambda HTTP event

schemas

Type: Object

queryParamsSchema

Type: Joi Schema
Default: joi.object().empty({})

pathParamsSchema

Type: Joi Schema
Default: joi.object().empty({})

bodySchema

Type: Joi Schema
Default: joi.object().empty({})

setRequestContext(lambaEvent, lambaContext)

Initializes the request context, which is necessary for proper logging.

log.debug(msg, params)
log.info(msg, params)
log.warn(msg, params)
log.error(msg, params)

Structured Logging Helper

msg

Required
Type: String

params

Type: Object or Error
Default: {}

License

This project is licensed under the terms of the MIT license.

Package Sidebar

Install

npm i @dominiklessel/serverless-utils

Weekly Downloads

1

Version

1.0.0

License

MIT

Unpacked Size

8.96 kB

Total Files

6

Last publish

Collaborators

  • dominiklessel