• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

jeremydaly/lambda-api: Lightweight web framework for your serverless application ...

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称:

jeremydaly/lambda-api

开源软件地址:

https://github.com/jeremydaly/lambda-api

开源编程语言:

JavaScript 100.0%

开源软件介绍:

Lambda API

Build Status npm npm Coverage Status

Lightweight web framework for your serverless applications

Lambda API is a lightweight web framework for AWS Lambda using AWS API Gateway Lambda Proxy Integration or ALB Lambda Target Support. This closely mirrors (and is based on) other web frameworks like Express.js and Fastify, but is significantly stripped down to maximize performance with Lambda's stateless, single run executions.

Simple Example

// Require the framework and instantiate it
const api = require('lambda-api')();

// Define a route
api.get('/status', async (req, res) => {
  return { status: 'ok' };
});

// Declare your Lambda handler
exports.handler = async (event, context) => {
  // Run the request
  return await api.run(event, context);
};

For a full tutorial see How To: Build a Serverless API with Serverless, AWS Lambda and Lambda API.

Why Another Web Framework?

Express.js, Fastify, Koa, Restify, and Hapi are just a few of the many amazing web frameworks out there for Node.js. So why build yet another one when there are so many great options already? One word: DEPENDENCIES.

These other frameworks are extremely powerful, but that benefit comes with the steep price of requiring several additional Node.js modules. Not only is this a bit of a security issue (see Beware of Third-Party Packages in Securing Serverless), but it also adds bloat to your codebase, filling your node_modules directory with a ton of extra files. For serverless applications that need to load quickly, all of these extra dependencies slow down execution and use more memory than necessary. Express.js has 30 dependencies, Fastify has 12, and Hapi has 17! These numbers don't even include their dependencies' dependencies.

Lambda API has ZERO dependencies. None. Zip. Zilch.

Lambda API was written to be extremely lightweight and built specifically for SERVERLESS applications using AWS Lambda and API Gateway. It provides support for API routing, serving up HTML pages, issuing redirects, serving binary files and much more. Worried about observability? Lambda API has a built-in logging engine that can even periodically sample requests for things like tracing and benchmarking. It has a powerful middleware and error handling system, allowing you to implement just about anything you can dream of. Best of all, it was designed to work with Lambda's Proxy Integration, automatically handling all the interaction with API Gateway for you. It parses REQUESTS and formats RESPONSES, allowing you to focus on your application's core functionality, instead of fiddling with inputs and outputs.

Single Purpose Functions

You may have heard that a serverless "best practice" is to keep your functions small and limit them to a single purpose. I generally agree since building monolith applications is not what serverless was designed for. However, what exactly is a "single purpose" when it comes to building serverless APIs and web services? Should we create a separate function for our "create user" POST endpoint and then another one for our "update user" PUT endpoint? Should we create yet another function for our "delete user" DELETE endpoint? You certainly could, but that seems like a lot of repeated boilerplate code. On the other hand, you could create just one function that handled all your user management features. It may even make sense (in certain circumstances) to create one big serverless function handling several related components that can share your VPC database connections.

Whatever you decide is best for your use case, Lambda API is there to support you. Whether your function has over a hundred routes, or just one, Lambda API's small size and lightning fast load time has virtually no impact on your function's performance. You can even define global wildcard routes that will process any incoming request, allowing you to use API Gateway or ALB to determine the routing. Yet despite its small footprint, it gives you the power of a full-featured web framework.

Table of Contents

Installation

npm i lambda-api --save

Requirements

Configuration

Require the lambda-api module into your Lambda handler script and instantiate it. You can initialize the API with the following options:

Property Type Description
base String Base path for all routes, e.g. base: 'v1' would prefix all routes with /v1
callbackName String Override the default callback query parameter name for JSONP calls
logger boolean or object Enables default logging or allows for configuration through a Logging Configuration object.
mimeTypes Object Name/value pairs of additional MIME types to be supported by the type(). The key should be the file extension (without the .) and the value should be the expected MIME type, e.g. application/json
serializer Function Optional object serializer function. This function receives the body of a response and must return a string. Defaults to JSON.stringify
version String Version number accessible via the REQUEST object
errorHeaderWhitelist Array Array of headers to maintain on errors
// Require the framework and instantiate it with optional version and base parameters
const api = require('lambda-api')({ version: 'v1.0', base: 'v1' });

Recent Updates

For detailed release notes see Releases.

v0.11: API Gateway v2 payload support and automatic compression

Lambda API now supports API Gateway v2 payloads for use with HTTP APIs. The library automatically detects the payload, so no extra configuration is needed. Automatic compression has also been added and supports Brotli, Gzip and Deflate.

v0.10: ALB support, method-based middleware, and multi-value headers and query string parameters

Lambda API now allows you to seamlessly switch between API Gateway and Application Load Balancers. New execution stacks enables method-based middleware and more wildcard functionality. Plus full support for multi-value headers and query string parameters.

Routes and HTTP Methods

Routes are defined by using convenience methods or the METHOD method. There are currently eight convenience route methods: get(), post(), put(), patch(), delete(), head(), options() and any(). Convenience route methods require an optional route and one or more handler functions. A route is simply a path such as /users. If a route is not provided, then it will default to /* and will execute on every path. Handler functions accept a REQUEST, RESPONSE, and optional next() argument. These arguments can be named whatever you like, but convention dictates req, res, and next.

Multiple handler functions can be assigned to a path, which can be used to execute middleware for specific paths and methods. For more information, see Middleware and Execution Stacks.

Examples using convenience route methods:

api.get('/users', (req,res) => {
  // do something
})

api.post('/users', (req,res) => {
  // do something
})

api.delete('/users', (req,res) => {
  // do something
})

api.get('/users',
  (req,res,next) => {
    // do some middleware
    next() // continue execution
  }),
  (req,res) => {
    // do something
  }
)

api.post((req,res) => {
  // do something for ALL post requests
})

Additional methods are support by calling METHOD. Arguments must include an HTTP method (or array of methods), an optional route, and one or more handler functions. Like the convenience methods above, handler functions accept a REQUEST, RESPONSE, and optional next argument.

api.METHOD('trace','/users', (req,res) => {
  // do something on TRACE
})

api.METHOD(['post','put'],'/users', (req,res) => {
  // do something on POST -or- PUT
})

api.METHOD('get','/users',
  (req,res,next) => {
    // do some middleware
    next() // continue execution
  }),
  (req,res) => {
  // do something
  }
)

All GET methods have a HEAD alias that executes the GET request but returns a blank body. GET requests should be idempotent with no side effects. The head() convenience method can be used to set specific paths for HEAD requests or to override default GET aliasing.

Routes that use the any() method or pass ANY to api.METHOD will respond to all HTTP methods. Routes that specify a specific method (such as GET or POST), will override the route for that method. For example:

api.any('/users', (req, res) => {
  res.send('any');
});
api.get('/users', (req, res) => {
  res.send('get');
});

A POST to /users will return "any", but a GET request would return "get". Please note that routes defined with an ANY method will override default HEAD aliasing for GET routes.

Returning Responses

Lambda API supports both callback-style and async-await for returning responses to users. The RESPONSE object has several callbacks that will trigger a response (send(), json(), html(), etc.) You can use any of these callbacks from within route functions and middleware to send the response:

api.get('/users', (req, res) => {
  res.send({ foo: 'bar' });
});

You can also return data from route functions and middleware. The contents will be sent as the body:

api.get('/users', (req, res) => {
  return { foo: 'bar' };
});

Async/Await

If you prefer to use async/await, you can easily apply this to your route functions.

Using return:

api.get('/users', async (req, res) => {
  let users = await getUsers();
  return users;
});

Or using callbacks:

api.get('/users', async (req, res) => {
  let users = await getUsers();
  res.send(users);
});

Promises

If you like promises, you can either use a callback like res.send() at the end of your promise chain, or you can simply return the resolved promise:

api.get('/users', (req, res) => {
  getUsers().then((users) => {
    res.send(users);
  });
});

OR

api.get('/users', (req, res) => {
  return getUsers().then((users) => {
    return users;
  });
});

IMPORTANT: You must either use a callback like res.send() OR return a value. Otherwise the execution will hang and no data will be sent to the user. Also, be sure not to return undefined, otherwise it will assume no response.

A Note About Flow Control

While callbacks like res.send() and res.error() will trigger a response, they will not necessarily terminate execution of the current route function. Take a look at the following example:

api.get('/users', (req, res) => {
  if (req.headers.test === 'test') {
    res.error('Throw an error');
  }

  return { foo: 'bar' };
});

The example above would not have the intended result of displaying an error. res.error() would signal Lambda API to execute the error handling, but the function would continue to run. This would cause the function to return a response that would override the intended error. In this situation, you could either wrap the return in an else clause, or a cleaner approach would be to return the call to the error() method, like so:

api.get('/users', (req, res) => {
  if (req.headers.test === 'test') {
    return res.error('Throw an error');
  }

  return { foo: 'bar' };
});

res.error() does not have a return value (meaning it is undefined). However, the return tells the function to stop executing, and the call to res.error() handles and formats the appropriate response. This will allow Lambda API to properly return the expected results.

Route Prefixing

Lambda API makes it easy to create multiple versions of the same api without changing routes by hand. The register() method allows you to load routes from an external file and prefix all of those routes using the prefix option. For example:

// handler.js
const api = require('lambda-api')();

api.register(require('./routes/v1/products'), { prefix: '/v1' });
api.register(require('./routes/v2/products'), { prefix: '/v2' });

module.exports.handler = (event, context, callback) => {
  api.run(event, context, callback);
};
// routes/v1/products.js
module.exports = (api, opts) => {
  api.get('/product', handler_v1);
};
// routes/v2/products.js
module.exports = (api, opts) => {
  api.get('/product', handler_v2);
};

Even though both modules create a /product route, Lambda API will add the prefix to them, creating two unique routes. Your users can now access:

  • /v1/product
  • /v2/product

You can use register() as many times as you want AND it is recursive, so if you nest register() methods, the routes will build upon each other. For example:

module.exports = (api, opts) => {
  api.get('/product', handler_v1);
  api.register(require('./v2/products.js'), { prefix: '/v2' });
};

This would create a /v1/product and /v1/v2/product route. You can also use register() to load routes from an external file without the prefix. This will just add routes to your base path. NOTE: Prefixed routes are built off of your base path if one is set. If your base was set to /api, then the first example above would produce the routes: /api/v1/product and /api/v2/product.

Debugging Routes

Lambda API has a routes() method that can be called on the main instance that will return an array containing the METHOD and full PATH of every configured route. This will include base paths and prefixed routes. This is helpful for debugging your routes.

const api = require('lambda-api')();

api.get('/', (req, res) => {});
api.post('/test', (req, res) => {});

api.routes(); // => [ [ 'GET', '/' ], [ 'POST', '/test' ] ]

You can also log the paths in table form to the console by passing in true as the only parameter.

 const api = require('lambda-api')()

 api.get('/', (req,res) => {})
 api.post('/test', (req,res) => {})

 api.routes(true)

// Outputs to console
╔═══════════╤═════════════════╗
  METHOD     ROUTE          
╟───────────┼─────────────────╢
  GET        /              
╟───────────┼─────────────────╢
  POST       /test          
╚═══════════╧═════════════════╝


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap