/lambda-koaless

Wrap AWS Lambda functions with Koa-like functions to simplify your code

Primary LanguageJavaScriptMIT LicenseMIT

lambda-koaless

Build Status npm version codecov semantic-release

Wrap AWS Lambda functions with Koa-like functions to simplify your code

Based on Lambda Expressless by Murat Çorlu

So instead of writing this:

exports.handler = (event, context, callback) => {
  const requestBody = JSON.parse(event.body);
  const responseBody = {
    success: false,
    data: requestBody.id
  };

  callback(null, {
    statusCode: 201,
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(responseBody)
  });
}

you'll have this:

const { ApiGatewayHandler } = require('lambda-koaless')
const bodyParser = require('koa-bodyparser')
const Router = require('koa-router')

const router = Router()

// set response header
router.use(async (ctx, next) => {
  const start = Date.now()
  await next()
  const ms = Date.now() - start
  ctx.set('X-Response-Time', `${ms}ms`)
});

// parse body
router.use(bodyParser())

// handle route
router.get('/hello-world', (ctx, next) => {
  console.log(ctx.request.body) // parsed body
  ctx.status = 200
  ctx.body = { ok: true, message: 'Foo Bar' }
})

exports.handler = ApiGatewayHandler(router)

You can use many popular Koa Middlewares.

Installation

npm i lambda-koaless

Supported Features and Limitations

This project aims to implement functionalities of Koa middlewares as much as possible. Request and Response objects have properties and methods listed below.

Context Object

Properties:

Property Notes
WIP WIP

Methods:

Method Notes
WIP WIP

Request Object

Properties:

Property Notes
body You need to use body-parser
hostname -
host -
xhr -
ip -
ips -
path -
protocol -
secure -
method -
query -
params -
headers -

Methods:

Method Notes
accepts() -
acceptsEncodings() -
acceptsCharsets() -
acceptsLanguages() -
get() -
header() -
is() -

Response Object

Methods:

Method Notes
get() -
format() Doesn't support shorthand mime-types
set() Only supports key, value parameters
send() Only supports string values
status() -
end() -
json() -
type() -

Contribution

Every contribution is very welcome. Keep these in your mind when you want to make a contribution:

  1. Because of we use semantic-release you need to use Angular Commit Message Conventions in your commit messages.
  2. Keep code coverage 100% with your updated tests.
  3. Check your changes with a Lambda environment. You can use SAM-CLI to test on your local.
  4. Don't forget to update documentation(this readme file) about your changes.