A 7KB and 0 dependencies AWS Lambda library which supports middleware and easy debug.

栏目: IT技术 · 发布时间: 5年前

Micro AWS Lambda

A 7KB and 0 dependencies AWS Lambda library which supports middleware and easy debug.

Intro

  • Ready to go Lambda Proxy library
  • Written in Typescript
  • Zero runtime dependencies
  • Tiny: 7KB after minified
  • Extendable with middlewares
    • before (handler) hooks
    • after (handler) hooks
    • early exit for just throw httpError() or anything
    • pass values among middlewares
  • Return response
    • an object, it will be converted to a Lambda compatible response
    • a customizable httpResponse() / success()
    • a customizable httpError() / badRequest() / internalError()
    • or string, number, boolean
  • Easy debug:
    • Adding debug info to response object
    • console.log event / context

Usage

1. Install

npm install micro-aws-lambda

2. Quick start

import { Middleware, lambdaWrapper } from 'micro-aws-lambda';

const lambda: Middleware = ({event, context, passDownObj}) => {}

const handler = lambdaWrapper({
  handler: lambda,
  beforeHooks: [],
  afterHooks: [],
  config: {
      addTraceInfoToResponse: false;
      logRequestInfo: false;
  }
});
  • The execution order is: beforeHooks -> handler -> afterHooks .
  • beforeHooks , handler , afterHooks all have the same signature:
type Middleware = ({
  event,
  context,
  passDownObj,
}: MiddlewareParams) =>
  | string
  | number
  | boolean
  | PlainObject
  | APIGatewayProxyResult
  | Promise<PlainObject | APIGatewayProxyResult>
  | HttpError
  | HttpResponse
  | void;

event and context is immutable, if you want to pass any info down, attach it to the passDownObj as a property, like passDownObj.value = { message: 'checked' } , the passDownObj object is mutable.

3. Simple handler

Writing an API which will return a JSON and logging things like APIGatewayID and CloudWatchID , blah blah

import { lambdaWrapper, Middleware } from 'micro-aws-lambda';

const lambda: Middleware = ({ event, context, passDownObj }) => {
  return {
    message: 'it works',
  };
};

const handler = lambdaWrapper({
  handler: lambda,
});

// call the API, you will get json response: {message: ""it works"}

4. Before hooks

What about I want to validate this request before executing my lambda? Easy, you just add a hook.

In the following case, if the request name is 'albert', only validateRequest will be called.

import { badRequest } from 'micro-aws-lambda';

const validateRequest: Middleware = ({ event }) => {
  if (event.request.name === 'albert') {
    throw badRequest({
      message: 'bad user, bye bye',
    });
  }
};

const handler = lambdaWrapper({
  // adding to the array
  // omitting the other things for briefing
  beforeHooks: [validateRequest],
});

5. After hooks

You can add afterHooks as well for changing response. The following handler will only return { message: 'bad user, bye bye' } Every middleware in the afterHooks array will receive an additional response as the response.

import { badRequest } from 'micro-aws-lambda';

const validateResponse: Middleware = ({ response }) => {
  if (response?.name === 'albert') {
    throw badRequest({
      message: 'bad user, bye bye',
    };
  })
};

const testHandler = lambdaWrapper({
  handler: () => ({
    name: 'albert',
  }),
  afterHooks: [validateResponse],
});

6. Response

There are 2 types for response, httpError() for throw , and httpResponse() for return , each one of them has some shortcuts to use.

import { httpError, httpResponse } from 'micro-aws-lambda';

// It gives you an instance of HttpError, which extends from Error
const error = httpError({
  // default status code is 400 if not set
  statusCode: 401,
  body: {
    message: 'test',
  },
  headers: {
    'x-http-header': 'fake-header',
  },
});

// It gives you a plain JS object.
const response = httpResponse({
  // default status code is 200 if not set
  statusCode: 200,
  body: {
    message: 'test',
  },
  headers: {
    'x-http-header': 'fake-header',
  },
});

The commons headers are:

  • 'Access-Control-Allow-Origin': '*',
  • 'Access-Control-Allow-Credentials': true,
  • 'Content-Type': 'application/json',

Supports multiValueHeaders and isBase64Encoded in case you need them.

6.1. Shortcuts

Compare to the above methods, the only difference is the shortcuts just sets the status code, you can still modify them if you want.

  • httpError :
    badRequest()
    internalRequest()
    
  • httpResponse :
    • success() : 200

7. Config

7.1 addTraceInfoToResponse

It will add debug info into the response object

{
  debug: {
    endpoint: "",
    requestBody: "",
    requestMethod: "",

    country: "",
    lambdaRequestId: "",
    logStreamName: "",
    logGroupName: "",
    apiGatewayId: ""
  }
}

7.2 logRequestInfo

It will console.log :

event
context
Aws-Api-Gateway-Request-Id
Identity-Source-Ip

8. Credits

This project was bootstrapped with TSDX .


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

HTTP/2基础教程

HTTP/2基础教程

Stephen Ludin、Javier Garza / 罗正龙、郑维智 / 人民邮电出版社 / 2018-1 / 49.00元

让网站和应用更快速、更简洁、更稳健,从而有效提升用户体验,这无疑是众多开发者梦寐以求的。然而互联网发展日新月异,HTTP/1.1协议已经难以满足现今的需求。在众多Web性能提升方案中,HTTP/2值得尝试。 本书是HTTP/2实用指南,介绍了HTTP/2的设计初衷和新特性,以及如何才能充分利用这些特性来打造高性能网站及应用。作者用定量分析方法,对比了不同网络环境下及不同浏览器上HTTP/1.......一起来看看 《HTTP/2基础教程》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具