### Install lambda-api Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Installs the lambda-api package using npm. ```bash npm i lambda-api --save ``` -------------------------------- ### Basic Lambda API Setup and Route Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md This snippet demonstrates how to set up the Lambda API framework, define a simple GET route for '/status', and configure the AWS Lambda handler to run the API. ```javascript // 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); }; ``` -------------------------------- ### Lambda API TypeScript Example Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Demonstrates how to set up a basic API route using lambda-api with TypeScript. It shows importing necessary types, instantiating the API, defining a GET route, and exporting the Lambda handler. ```typescript import { APIGatewayEvent, Context } from 'aws-lambda'; import createAPI from 'lambda-api'; const api = createAPI(); api.get('/status', async (req, res) => { return { status: 'ok' }; }); exports.run = async (event: APIGatewayEvent, context: Context) => { return await api.run(event, context); }; ``` -------------------------------- ### sendFile Usage Examples Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Examples demonstrating various ways to use the sendFile method, including serving local files, configuring cache age, referencing S3 files, and using a callback function with error handling. ```javascript res.sendFile('./img/logo.png') res.sendFile('./img/logo.png', { maxAge: 3600000 }) res.sendFile('s3://my-bucket/path/to/file.png', { maxAge: 3600000 }) res.sendFile(, 'my-file.docx', { maxAge: 3600000 }, (err) => { if (err) { res.error('Custom File Error') } }) ``` -------------------------------- ### JavaScript Example: Lambda API Logging Configuration Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md An example demonstrating how to configure the Lambda API logger with various options, including custom log level, access logging, custom message keys, and a custom timestamp function. ```javascript const api = require('lambda-api')({ logger: { level: 'debug', access: true, customKey: 'detail', messageKey: 'message', timestamp: () => new Date().toUTCString(), // custom timestamp stack: true, }, }); ``` -------------------------------- ### Define API Routes with Convenience Methods Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Defines API routes using convenience methods like get(), post(), delete(), and supports middleware functions. ```javascript 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 }) ``` -------------------------------- ### Lambda API Wildcard Route for OPTIONS Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Defines a wildcard route for the OPTIONS method to handle CORS headers. This route matches any path starting with '/'. ```javascript api.options('/*', (req, res) => { // Return CORS headers res.cors().send({}); }); ``` -------------------------------- ### Lambda API Cookie Management Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Provides examples of setting cookies using the `cookie` method in the Lambda API. It illustrates setting various cookie attributes like domain, expiration, httpOnly, maxAge, path, secure, and sameSite. ```javascript res.cookie('foo', 'bar', { maxAge: 3600 * 1000, secure: true }).send(); ``` ```javascript res .cookie( 'fooObject', { foo: 'bar' }, { domain: '.test.com', path: '/admin', httpOnly: true } ) .send(); ``` ```javascript res .cookie('fooArray', ['one', 'two', 'three'], { path: '/', httpOnly: true }) .send(); ``` -------------------------------- ### Method-Based Middleware Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Applies middleware to specific HTTP methods (GET, POST, etc.) on particular paths. Multiple middleware functions can be chained for each method. ```javascript const middleware1 = (req, res, next) => { // middleware code }; const middleware2 = (req, res, next) => { // middleware code }; // Execute middleware1 and middleware2 on /users route api.get('/users', middleware1, middleware2, (req, res) => { // handler function }); // Execute middleware1 on /users route api.get('/users', middleware1); // Add middleware2 and handler api.get('/users', middleware2, (req, res) => { // handler function }); ``` -------------------------------- ### Lambda API Request Object Properties Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md The REQUEST object in lambda-api provides access to various properties derived from an API Gateway request. These include parsed headers, query parameters, body, authentication details, and context-specific information like cold start status and client IP. ```APIDOC REQUEST Object Properties: - app: Reference to the app instance. - version: Initialization version. - id: Lambda context awsRequestId. - interface: Interface used (apigateway, alb, edge). - params: Dynamic path parameters. - method: HTTP request method. - path: Request path including base and prefix. - query: Parsed querystring parameters. - multiValueQuery: Querystring parameters with multiple values. - headers: Lowercase request headers (HTTP/2 compliant). - rawHeaders: Original request headers with preserved case. - multiValueHeaders: Header values as multi-value arrays. - body: Decoded request body (auto-decodes base64, parses JSON/urlencoded). - rawBody: Original base64 encoded body. - route: Matched route of the request. - requestContext: API Gateway requestContext. - pathParameters: API Gateway pathParameters. - stageVariables: API Gateway stageVariables. - isBase64Encoded: Base64 encoded flag. - auth: Authorization header details (type, value, user/pass for Basic, OAuth pairs). - namespace or ns: Reference to modules in the app's namespace. - cookies: Cookies sent from the browser. - context: Lambda handler context reference. - coldStart: Boolean indicating a cold start invocation. - requestCount: Total invocations of the current function container. - ip: Client IP address. - userAgent: Client User-Agent header. - clientType: Client type (desktop, mobile, etc.) based on User-Agent. - clientCountry: Two-letter country code from CloudFront. - stack: Array of function names in the execution stack. ``` -------------------------------- ### Instantiate lambda-api with Version and Base Path Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Demonstrates how to require the lambda-api module and instantiate it with optional version and base path parameters for your Lambda handler script. ```javascript const api = require('lambda-api')({ version: 'v1.0', base: 'v1' }); ``` -------------------------------- ### Route Configuration Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Explains how to define routes and HTTP methods within the framework, including path parameters and wildcard routes. ```APIDOC Routes and HTTP Methods: Define routes with specific HTTP methods (GET, POST, PUT, DELETE, etc.). Path Parameters: Use placeholders in the route path to capture dynamic values. Wildcard Routes: Use wildcards to match multiple paths. ``` -------------------------------- ### Lambda API Route Prefixing with register() Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Illustrates how to use the register() method in Lambda API to load routes from external files and apply prefixes, enabling versioning of APIs. It shows how nested registrations create hierarchical routes. ```javascript // 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); }; // Example with nested registration // module.exports = (api, opts) => { // api.get('/product', handler_v1); // api.register(require('./v2/products.js'), { prefix: '/v2' }); // }; ``` -------------------------------- ### Handling ANY Method and Method Overrides Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Demonstrates using the any() method to respond to all HTTP methods and how specific method routes override ANY routes. ```javascript api.any('/users', (req, res) => { res.send('any'); }); api.get('/users', (req, res) => { res.send('get'); }); ``` -------------------------------- ### Lambda API Initialization with Logging Enabled Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Initializes the Lambda API instance with the logging engine enabled. This allows for detailed logging within the application. ```javascript const api = require('lambda-api')({ logger: true }); ``` -------------------------------- ### lambda-api Configuration Options Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Provides a detailed breakdown of the configuration properties available for the lambda-api framework, including their types and descriptions. ```APIDOC Configuration Options: - 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 - s3Config: (Object) Optional object to provide as config to S3 sdk. [S3ClientConfig](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-s3/interfaces/s3clientconfig.html) ``` -------------------------------- ### Middleware Execution Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Demonstrates how to apply middleware to specific paths or HTTP methods, and how to specify multiple middleware functions. ```APIDOC Middleware: Restricting middleware execution to certain path(s): Specify the path(s) when defining the middleware. Specifying multiple middleware: Chain middleware functions in the order of execution. Method-based middleware: Apply middleware only to specific HTTP methods (e.g., GET, POST). ``` -------------------------------- ### Lambda API Route Debugging with routes() Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Explains how to use the routes() method in Lambda API to retrieve a list of all configured routes, including their HTTP methods and full paths. It also shows how to log these routes to the console in a formatted table. ```javascript const api = require('lambda-api')(); api.get('/', (req, res) => {}); api.post('/test', (req, res) => {}); api.routes(); // => [ [ 'GET', '/' ], [ 'POST', '/test' ] ] // To log in table format: // api.routes(true) ``` -------------------------------- ### Logging Configuration Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Details the various aspects of logging, including configuration, format, levels, custom levels, serializers, and sampling. ```APIDOC Logging: Logging Configuration: Set up logging behavior. Log Format: Define the structure of log messages. Access Logs: Configure logging for incoming requests. Logging Levels: Control the verbosity of logs (e.g., DEBUG, INFO, WARN, ERROR). Custom Logging Levels: Define your own logging levels. Adding Additional Detail: Include custom data in log messages. Serializers: Customize how objects are serialized in logs. Sampling: Control the rate at which logs are recorded. ``` -------------------------------- ### Adding Namespaces Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Demonstrates how to map modules to namespaces using the `api.app()` method for easier access within other modules. Supports adding single namespaces or multiple namespaces at once. ```javascript // Use app() function to add 'data' namespace api.app('data', require('./lib/data.js')); // Create a get route to load user details api.get('/users/:userId', require('./lib/users.js')); ``` ```javascript api.app('namespace', require('./lib/ns-functions.js')); ``` ```javascript api.app({ namespace1: require('./lib/ns1-functions.js'), namespace2: require('./lib/ns2-functions.js'), }); ``` -------------------------------- ### Advanced Features Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Highlights advanced features such as compression, namespaces, reusing persistent connections, and TypeScript support. ```APIDOC Advanced Features: Compression: Enable automatic response compression. Namespaces: Organize routes using namespaces. Reusing Persistent Connections: Optimize performance by reusing connections. TypeScript Support: Utilize TypeScript for enhanced development. ``` -------------------------------- ### Async/Await with Return Value Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Demonstrates using async/await to fetch data and return it directly as the response. ```javascript api.get('/users', async (req, res) => { let users = await getUsers(); return users; }); ``` -------------------------------- ### Returning Responses with Callbacks Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Shows how to return responses using callbacks like send() on the RESPONSE object. ```javascript api.get('/users', (req, res) => { res.send({ foo: 'bar' }); }); ``` -------------------------------- ### AWS Integration Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Explains how lambda-api integrates with AWS services like Lambda Proxy Integration, ALB, and API Gateway configuration. ```APIDOC AWS Integration: Lambda Proxy Integration: How the framework works with API Gateway's proxy integration. ALB Integration: Support for Application Load Balancer integration. Configuring Routes in API Gateway: Guidance on setting up routes in AWS API Gateway. ``` -------------------------------- ### Promises with Response Callback Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Illustrates handling Promises and using a response callback like res.send() to send the resolved value. ```javascript api.get('/users', (req, res) => { getUsers().then((users) => { res.send(users); }); }); ``` -------------------------------- ### Returning Responses by Returning Data Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Illustrates returning data directly from route functions to be sent as the response body. ```javascript api.get('/users', (req, res) => { return { foo: 'bar' }; }); ``` -------------------------------- ### Automatic Compression Configuration Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Configures Lambda API to automatically compress responses based on the 'Accept-Encoding' header. Supports Gzip and Deflate, with optional Brotli support. ```javascript const api = require('lambda-api')({ compression: true, }); ``` ```javascript const api = require('lambda-api')({ compression: ['br', 'gzip'], }); ``` -------------------------------- ### Lambda API Requirements Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Specifies the requirements for running lambda-api, including the Node.js version and AWS API Gateway integration type. ```markdown AWS Lambda running **Node 8.10+** AWS API Gateway using [Proxy Integration](#lambda-proxy-integration) ``` -------------------------------- ### Lambda API Path Parameters Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Explanation of how path parameters are handled in the Lambda API. Parameters are extracted from the request path and made available in the `req.params` object, allowing for dynamic routing. ```APIDOC Path Parameters: - Defined in routes using a colon prefix (e.g., /users/:userId). - Extracted from the request path sent by API Gateway. - Values are available in the `req.params` object. - Static paths take precedence over dynamic paths. - Path parameters only match the segment they are defined on. - Multiple path parameters can be used in a single route (e.g., /users/:param1/:param2). Example: api.get('/users/:userId', (req, res) => { res.send('User ID: ' + req.params.userId); }); ``` -------------------------------- ### Promises with Return Value Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Demonstrates returning a resolved Promise directly to send its value as the response. ```javascript api.get('/users', (req, res) => { return getUsers().then((users) => { return users; }); }); ``` -------------------------------- ### Response Methods Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Details various methods available on the response object for setting status codes, headers, sending responses, and handling content types. ```APIDOC RESPONSE: status(code) Sets the HTTP status code for the response. sendStatus(code) Sends the HTTP status code as the response body. header(key, value [,append]) Sets a response header. If append is true, the value is appended to the existing header value. getHeader(key [,asArray]) Retrieves the value of a response header. If asArray is true, returns all values for the header. getHeaders() Returns all response headers. hasHeader(key) Checks if a response header exists. removeHeader(key) Removes a response header. getLink(s3Path [, expires] [, callback]) Generates a pre-signed S3 URL for a file. send(body) Sends a response body. json(body) Sends a JSON response body. jsonp(body) Sends a JSONP response body. html(body) Sends an HTML response body. type(type) Sets the Content-Type header. location(path) Sets the Location header for redirects. redirect([status,] path) Sends a redirect response. cors([options]) Configures CORS headers for the response. error([code], message [,detail]) Sends an error response. cookie(name, value [,options]) Sets a cookie. clearCookie(name [,options]) Clears a cookie. etag([boolean]) Enables or disables ETag generation. cache([age] [, private]) Sets cache control headers. modified(date) Sets the Last-Modified header. attachment([filename]) Sets the Content-Disposition header to attachment. download(file [, filename] [, options] [, callback]) Sends a file as a download. sendFile(file [, options] [, callback]) Sends a file as the response body. ``` -------------------------------- ### Define API Routes with METHOD() Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Defines API routes using the generic METHOD() function, allowing specification of HTTP methods and multiple handlers. ```javascript 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 } ) ``` -------------------------------- ### Async/Await with Response Callback Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Shows using async/await with a response callback like res.send() to send the result. ```javascript api.get('/users', async (req, res) => { let users = await getUsers(); res.send(users); }); ``` -------------------------------- ### Download File Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Transfers a file (local path, S3 reference, or Buffer) as an attachment, prompting download. Combines attachment() and sendFile(). Optionally takes a filename to overwrite, options for sendFile(), and a callback. ```javascript res.download(file [, filename] [, options] [, callback]) // Example usage: res.download('./files/sales-report.pdf') res.download('./files/sales-report.pdf', 'report.pdf') res.download('s3://my-bucket/path/to/file.png', 'logo.png', { maxAge: 3600000 }) res.download(, 'my-file.docx', { maxAge: 3600000 }, (err) => { if (err) { res.error('Custom File Error') } }) ``` -------------------------------- ### Request Object Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Provides access to request details, including path parameters, query strings, headers, and body. ```APIDOC REQUEST: Path Parameters: Access parameters defined in the route path. Query String Parameters: Access parameters from the query string. Headers: Access request headers. Body: Access the request body. ``` -------------------------------- ### Lambda API Logging Configuration Properties Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md This section details the available properties for configuring the logger in the Lambda API. It includes property names, types, descriptions, and default values. ```APIDOC Logging Configuration Properties: access: boolean | string Enables/disables automatic access log generation for each request. See [Access Logs](#access-logs). Default: false errorLogging: boolean Enables/disables automatic error logging. Default: true customKey: string Sets the JSON property name for custom data passed to logs. Default: custom detail: boolean Enables/disables adding REQUEST and RESPONSE data to all log entries. Default: false level: string Minimum logging level to send logs for. See [Logging Levels](#logging-levels). Default: info levels: object Key/value pairs of custom log levels and their priority. See [Custom Logging Levels](#custom-logging-levels). log: function Custom function for overriding standard console.log. Default: console.log messageKey: string Sets the JSON property name of the log "message". Default: msg multiValue: boolean Enables multi-value support for querystrings. If enabled, the qs parameter will return all values as arrays and will include multiple values if they exist. Default: false nested: boolean Enables/disables nesting of JSON logs for serializer data. See [Serializers](#serializers). Default: false timestamp: boolean | function By default, timestamps will return the epoch time in milliseconds. A value of false disables log timestamps. A function that returns a value can be used to override the default format. Default: true sampling: object Enables log sampling for periodic request tracing. See [Sampling](#sampling). serializers: object Adds serializers that manipulate the log format. See [Serializers](#serializers). stack: boolean Enables/disables the inclusion of stack traces in caught errors. Default: false ``` -------------------------------- ### Lambda API sendFile Method Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md The sendFile method allows serving files from local storage, S3, or as Buffers. It supports options for caching, headers, and a callback for custom error handling or response manipulation. The callback can also return a promise for asynchronous operations. ```APIDOC sendFile(file [, options] [, callback]) Parameters: file: Local filename, S3 reference (s3://bucket/path), or JavaScript Buffer. options (Object, optional): Configuration for the response. maxAge (Number): Cache expiration time in milliseconds. Sets 'Expires' header. Default: 0. root (String): Root directory for relative filenames. lastModified (Boolean or String): Sets 'last-modified' header. Can be disabled (false) or set to a Date object. headers (Object): Key-value pairs for additional headers. cacheControl (Boolean or String): Enable/disable 'cache-control' header. Can be overridden with a string. private (Boolean): Sets 'cache-control' to 'private'. Default: false. callback (Function, optional): Function to handle errors or manipulate the response. Supports promises. Notes: - Lambda function needs 'GetObject' access for S3 files. - Enable binary support in API Gateway settings by adding '*/*' to 'Binary Media Types'. ``` -------------------------------- ### Multiple Middleware Functions Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Assigns multiple middleware functions to the same path or globally using a single 'use' method call for code minimization. ```javascript const middleware1 = (req, res, next) => { // middleware code }; const middleware2 = (req, res, next) => { // some other middleware code }; // Restrict middleware1 and middleware2 to /users route api.use('/users', middleware1, middleware2); // Add middleware1 and middleware2 to all routes api.use(middleware1, middleware2); ``` -------------------------------- ### Error Handling Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Covers the framework's error handling capabilities, including different error types and error logging. ```APIDOC Error Handling: Error Types: Understand and define different error categories. Error Logging: Configure how errors are logged. ``` -------------------------------- ### Enable Default Sampling Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Enables default sampling by setting the `sampling` property to `true` or by providing a configuration object with `target`, `rate`, and `period` properties. ```javascript const api = require('lambda-api')({ logger: { sampling: { target: 2, rate: 0.1, period: 30, }, }, }); ``` -------------------------------- ### Path-Specific Middleware Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Restricts middleware execution to specific paths using string, wildcard, or array of paths. Path matching considers parameterized routes. ```javascript // Single path api.use('/users', (req, res, next) => { next(); }); ``` ```javascript // Wildcard path api.use('/users/*', (req, res, next) => { next(); }); ``` ```javascript // Multiple path api.use(['/users', '/posts'], (req, res, next) => { next(); }); ``` ```javascript // Parameterized paths api.use('/users/:userId', (req, res, next) => { next(); }); ``` ```javascript // Multiple paths with parameters and wildcards api.use(['/comments', '/users/:userId', '/posts/*'], (req, res, next) => { next(); }); ``` -------------------------------- ### Lambda API Error Handling Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Demonstrates how to trigger an error response using the `error` method in the Lambda API. It covers setting custom status codes, error messages, and additional details. ```javascript api.get('/users', (req, res) => { res.error('This is an error'); }); ``` ```javascript api.get('/users', (req, res) => { res.error(403, 'Not authorized'); }); ``` ```javascript api.get('/users', (req, res) => { res.error('Error', { foo: 'bar' }); }); ``` ```javascript api.get('/users', (req, res) => { res.error(404, 'Page not found', 'foo bar'); }); ``` -------------------------------- ### Access Log Format (Automatic Logging) in Lambda API Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Demonstrates the JSON format for access logs in Lambda API, which includes standard log data plus additional information about the request, such as path, IP address, user agent, API version, device, country, and query string parameters. ```javascript { ... Standard Log Data ..., "path": "/user/123", // path accessed "ip": "12.34.56.78", // client ip address "ua": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6)..", // User-Agent "version": "v1", // specified API version "device": "mobile", // client device (as determined by CloudFront) "country": "US", // client country (as determined by CloudFront) "qs": { // query string parameters "foo": "bar" } } ``` -------------------------------- ### Lambda API Route with Request Logging Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Demonstrates how to use the request logger within a route handler to log information. The logger is attached to the request object. ```javascript api.get('/status', (req, res) => { req.log.info('Some info about this route'); res.send({ status: 'ok' }); }); ``` -------------------------------- ### Add Additional Detail to Logs in Lambda API Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Shows how to specify additional detail with each log entry by supplying any variable type as a second parameter to the logger function. If an object is provided, the keys will be merged into the main log entry's JSON. ```javascript req.log.info('This is the main log message', 'some other detail'); // string req.log.info('This is the main log message', { foo: 'bar', isAuthorized: someVar, }); // object req.log.info('This is the main log message', 25); // number req.log.info('This is the main log message', ['val1', 'val2', 'val3']); // array req.log.info('This is the main log message', true); // boolean ``` -------------------------------- ### Custom Logging Levels in Lambda API Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Demonstrates how to add custom logging levels in Lambda API by specifying an object containing level names as keys and their priorities as values. You can also adjust the priority of standard levels by adding it to the object. ```javascript const api = require('lambda-api')({ logger: { levels: { test: 5, // low priority 'test' level customLevel: 35, // between info and warn trace: 70, // set trace to the highest priority }, }, }); ``` -------------------------------- ### Standard Log Format (Manual Logging) in Lambda API Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Shows the standard JSON format for manual logging in Lambda API, including log level, timestamp, request ID, route, method, message, timer, custom data, remaining time, function name, memory, interface, and sampling status. ```javascript { "level": "info", // log level "time": 1534724904910, // request timestamp "id": "41b45ea3-70b5-11e6-b7bd-69b5aaebc7d9", // awsRequestId "route": "/user/:userId", // route accessed "method": "GET", // request method "msg": "Some info about this route", // log message "timer": 2, // execution time up until log was generated "custom": "additional data", // addditional custom log detail "remaining": 2000, // remaining milliseconds until function timeout "function": "my-function-v1", // function name "memory": 2048, // allocated function memory "int": "apigateway", // interface used to access the Lambda function "sample": true // is generated during sampling request? } ``` -------------------------------- ### Accessing Namespaced Modules Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Shows how to access functions or data from a namespaced module via the `req.namespace` object within a route handler. ```javascript module.exports = (req, res) => { let userInfo = req.namespace.data.getUser(req.params.userId); res.json({ userInfo: userInfo }); }; ``` -------------------------------- ### Custom Compression with Base64 Serialization Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Provides custom control over response compression by setting 'isBase64' to true and defining a serializer function that returns a base64 encoded compressed string. Ensures the correct 'content-encoding' header is set. ```javascript const zlib = require('zlib'); const api = require('lambda-api')({ isBase64: true, headers: { 'content-encoding': ['gzip'], }, serializer: (body) => { const json = JSON.stringify(body); return zlib.gzipSync(json).toString('base64'); }, }); ``` -------------------------------- ### CORS Support with OPTIONS Route Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Implements CORS support by handling OPTIONS requests and setting appropriate headers. This allows cross-origin requests to your API. ```javascript api.options('/*', (req, res) => { // Add CORS headers res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE, OPTIONS'); res.header( 'Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With' ); res.status(200).send({}); }); ``` -------------------------------- ### Custom Error Handling Middleware Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Demonstrates how to define and use custom middleware for handling errors in Lambda API. Error handling middleware requires four arguments (err, req, res, next). ```javascript api.use((err, req, res, next) => { // do something with the error next(); }); ``` ```javascript const errorHandler1 = (err,req,res,next) => { // do something with the error next() }) const errorHandler2 = (err,req,res,next) => { // do something else with the error next() }) api.use(errorHandler1,errorHandler2) ``` -------------------------------- ### JSONP Response Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Sends a JSONP response by stringifying the body, setting the content type to application/json, and wrapping the result in a callback function. The callback name can be customized via URL parameters or API initialization options. ```javascript res.jsonp({ foo: 'bar' }); // => callback({ "foo": "bar" }) res.status(500).jsonp({ error: 'some error' }); // => callback({ "error": "some error" }) // ?callback=foo res.jsonp({ foo: 'bar' }); // => foo({ "foo": "bar" }) const api = require('lambda-api')({ callback: 'cb' }); // ?cb=bar res.jsonp({ foo: 'bar' }); // => bar({ "foo": "bar" }) ``` -------------------------------- ### HTML Response Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Sends an HTML response by setting the content type to text/html and passing through the provided content. ```javascript api.get('/users', (req, res) => { res.html('
This is HTML
'); }); ``` -------------------------------- ### Set Content Type Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Sets the Content-Type header based on a file extension or a full MIME type string. It supports a predefined list of common MIME types and allows custom types to be added during API instantiation. ```javascript res.type('.html'); // => 'text/html' res.type('html'); // => 'text/html' res.type('json'); // => 'application/json' res.type('application/json'); // => 'application/json' res.type('png'); // => 'image/png' res.type('.doc'); // => 'application/msword' res.type('text/css'); // => 'text/css' ``` -------------------------------- ### Handling Specific Error Types Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Shows how to differentiate and handle specific error types like RouteError and FileError within a custom error handling middleware. ```javascript const errorHandler = (err,req,res,next) => { if (err.name === 'RouteError') { // do something with route error } else if (err.name === 'FileError') { // do something with file error } // continue next() }) ``` -------------------------------- ### Configure Sampling Rules Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Adds custom sampling rules to apply specific sampling logic to different routes or HTTP methods. Rules can disable sampling by setting target and rate to 0, or enable it for specific routes. ```javascript const api = require('lambda-api')({ logger: { sampling: { rules: [ { route: '/status', target: 0, rate: 0 }, { route: '/user', target: 1, rate: 0.1 }, { route: '/posts/*', target: 1, rate: 0.1 }, { route: '/user', target: 0, rate: 0, method: ['GET', 'POST'] }, ], target: 0, rate: 0, }, }, }); ``` -------------------------------- ### Error Logging Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Illustrates how to trigger error logs using the RESPONSE object's `error()` method. Differentiates between 'error' level logs for messages and 'fatal' level logs for Error objects or thrown errors. ```javascript api.get('/somePath', (res, req) => { res.error('This is an error message'); // creates 'error' log }); ``` ```javascript api.get('/someOtherPath', (res, req) => { res.error(new Error('This is a fatal error')); // creates 'fatal' log }); ``` ```javascript api.get('/anotherPath', (res, req) => { throw new Error('Another fatal error'); // creates 'fatal' log }); ``` ```javascript api.get('/finalPath', (res, req) => { try { // do something } catch (e) { res.error(e); // creates 'fatal' log } }); ``` -------------------------------- ### Enable ETag Generation Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Enables ETag generation for the response. If true, Lambda API generates an ETag based on the response body. If the request includes an If-No-Match header matching the generated Etag, a 304 Not Modified response is returned. ```javascript res.etag([boolean]) ``` -------------------------------- ### Configure Logging Level in Lambda API Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md Shows how to set the logging level in Lambda API to control which log messages are written to CloudWatch Logs based on severity. Logs are written only if they are the same or higher severity than specified in the `level` log configuration. ```javascript // Logging level set to "warn" const api = require('lambda-api')({ logger: { level: 'warn' } }); api.get('/', (req, res) => { req.log.trace('trace log message'); // ignored req.log.debug('debug log message'); // ignored req.log.info('info log message'); // ignored req.log.warn('warn log message'); // write to CloudWatch req.log.error('error log message'); // write to CloudWatch req.log.fatal('fatal log message'); // write to CloudWatch res.send({ hello: 'world' }); }); ``` -------------------------------- ### Generate Signed S3 URL Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md The getLink method generates a signed URL for an S3 object. It takes an S3 path and an optional expiration time in seconds (defaults to 900). It returns a promise that resolves with the URL. An optional error handler callback can be provided. ```javascript // async/await api.get('/getLink', async (req, res) => { let url = await res.getLink('s3://my-bucket/my-file.pdf'); return { link: url }; }); // promises api.get('/getLink', (req, res) => { res.getLink('s3://my-bucket/my-file.pdf').then((url) => { res.json({ link: url }); }); }); ``` -------------------------------- ### Lambda API Response Object Methods Source: https://github.com/jeremydaly/lambda-api/blob/main/README.md The RESPONSE object in lambda-api allows manipulation of responses sent back to API Gateway. Key methods include setting the HTTP status code and sending the response body. ```APIDOC RESPONSE Object Methods: status(code) Sets the HTTP status code for the response. - Parameters: - code (integer): The HTTP status code (e.g., 200, 304, 404). - Returns: The RESPONSE object for chaining. - Example: ```javascript api.get('/users', (req, res) => { res.status(304).send('Not Modified'); }); ``` send(body) Sends the response body back to API Gateway. This method triggers the response and is not chainable. - Parameters: - body: The content to send in the response body. ```