2.0.0 • Published 5 years ago

aliyun-serverless-wrapper v2.0.0

Weekly downloads
4
License
MIT
Repository
github
Last release
5 years ago

Aliyun-serverless-wrapper

npm Codacy Badge CircleCI

This lib only works when using http-trigger

Yet this lib doesn't support multipart form data

By using this wrapper you shall write your handler function in a koa-like way.

Typescript friendly.

API

wrapper(handler: (ctx: WrappedContext, options?: WrapperOptions) => void) => void

The original request, response, context object will be merged into a more powerful WrappedContext object and passed into handler function.

WrapperOptions

  • timeout: set a timeout (ms) to limit the time range running handler

  • onError: you can set a callback like (err:Error, ctx: WrappedContext) => void for this field and do some error handler

WrappedContext

  • req: Request Request object

  • res: Response Response object

    also fields inherit from aliyun runtime context

  • credentials: AliyunContextCredentials

  • service: AliyunContextService

  • requestId: string

  • accountId: string

  • function: AliyunContextFunction

  • region: string

    and short hands for ctx.res

  • setHeader(field: string, value: string): void

  • removeHeader(field: string): void

  • get header: Headers

  • get headers: Headers

  • get status: number

  • set status(code: number): void

  • get body: any

  • set body(value: any): void

WrappedContext.Request

see request.ts

WrappedContext.Response

see response.ts

Example

Simply set the context's body, it will automatically send the response with proper status and header

const { wrapper } = require("aliyun-serverless-wrapper")

exports.someFunction = wrapper(async (ctx) => {
  ctx.body = { hello: "world" }
})

/* response shall be

  HTTP/1.1 200 OK
  Content-Type: application/json

  { "hello": "world" }

*/

exports.someFunction = wrapper(async (ctx) => {
  ctx.body = "hello world"
})

/* response shall be

  HTTP/1.1 200 OK
  Content-Type: text/plain

  "hello world"

*/

exports.someFunction = wrapper(async (ctx) => {
  ctx.body = "<html><h1>hello wordl</h1></html>"
})

/* response shall be

  HTTP/1.1 200 OK
  Content-Type: text/html

  "<html><h1>hello wordl</h1></html>"

*/

Or throw Error

exports.someFunction = wrapper(async (ctx) => {
  throw new Error("oops")
})

/* response shall be

  HTTP/1.1 500 Internal Error

*/

exports.someFunction = wrapper(
  async (ctx) => {
    await checkAuth(ctx.req) // and this will throw a Error
  },
  {
    onError: (e, ctx) => {
      ctx.status = 401
      ctx.body = { errorMessage: e.message }
    }
  }
)

/* response shall be

  HTTP/1.1 404 Not Found
  Content-Type: application/json

  { "errorMessage": "Not Authorized" }

*/
2.0.0

5 years ago

1.0.10

5 years ago

1.0.9

5 years ago

1.0.8

5 years ago

1.0.7

5 years ago

1.0.6

5 years ago

1.0.5

5 years ago

1.0.4

5 years ago

1.0.2

5 years ago

1.0.1

5 years ago

1.0.0

5 years ago