Options
All
  • Public
  • Public/Protected
  • All
Menu

@fiquu/lambda-http-event-handler

Lambda event handler for API Gateway HTTP requests.

Installation

npm i @fiquu/lambda-http-event-handler

Usage

HTTP Event

This will generate the necessary objects to handle an HTTP request graciously:

/configs/http-event.ts

import { conflict, badRequest } from '@fiquu/lambda-http-event-handler/lib/responses';
import { HTTPEventConfig } from '@fiquu/lambda-http-event-handler';

const handlers = new Map();

handlers.set(11000, conflict);
handlers.set('ValidationError', badRequest);

const config: HTTPEventConfig = {
  res: {
    handlers
  }
};

export default config;

/service/my-function/handler.ts

import { noContent } from '@fiquu/lambda-http-event-handler/lib/responses';
import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda';
import { createHTTPEvent } from '@fiquu/lambda-http-event-handler';
import { createLogger } from '@fiquu/logger';

import config from '../../configs/http-event';

const log = createLogger('HTTP /api/my-path');

/**
 * My Function handler function.
 */
export default function handler(event: APIGatewayProxyEvent): APIGatewayProxyResult {
  const { req, res } = createHTTPEvent(event, config);

  log.debug(req.headers);
  log.debug(req.params);
  log.debug(req.query);
  log.debug('Body:', req.body);

  try {
    return res.send(noContent());
  } catch (err) {
    log.error('It failed...', { err });
    return res.handle(err);
  }
}

View Rendering

/configs/http-event.ts

import { StaticFileHandlerConfig } from '@fiquu/lambda-http-event-handler/statics';

const config: StaticFileHandlerConfig = {
  res: {
    nonce: true,
    views: {
      basedir: join(__dirname, '..', 'fixtures', 'views'),
      locals: {}
    }
  }
};

export default config;

/api/my-path/handler.ts

import { noContent } from '@fiquu/lambda-http-event-handler/lib/responses';
import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda';
import { createHTTPEvent } from '@fiquu/lambda-http-event-handler';
import { createLogger } from '@fiquu/logger';

import config from './configs/http-event';

const log = createLogger('HTTP /view-path');

export default function handler(event: APIGatewayProxyEvent): APIGatewayProxyResult {
  const { req, res } = createHTTPEvent(event, config);

  try {
    return res.render('the-view', {
      body: req.body
    });
  } catch (err) {
    log.error('It failed...', { err });
    return res.render(err);
  }
}

Static File Serving

/configs/statics.ts

import { StaticFileHandlerConfig } from '@fiquu/lambda-http-event-handler/statics';

const config: StaticFileHandlerConfig = {
  basedir: join('..', 'static')
};

export default config;

/statics/handler.ts

import { createStaticFileHandler, StaticFileHandler } from '@fiquu/lambda-http-event-handler/statics';
import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda';

import config from '../configs/statics';

const staticFileHandler: StaticFileHandler = createStaticFileHandler(config);

export default function handler(event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> {
  return staticFileHandler.get(event);
}

Index

Type aliases

GetFileResult

GetFileResult: Promise<APIGatewayProxyResult>

Variables

Const _defaultResponse

_defaultResponse: APIGatewayProxyResult = Object.freeze<APIGatewayProxyResult>({statusCode: 200,body: '""',headers: {'Content-Type': 'application/json'}})

Default API Gateway response values.

Const defaults

defaults: HTTPResponseParams = Object.freeze<HTTPResponseParams>({body: '',statusCode: Number(_defaultResponse.statusCode),headers: Object.freeze({'Content-Type': 'application/json'}),options: Object.freeze({json: true})})

Default HTTP response params.

Const log

log: Logger = createLogger('HTTP Response')

Functions

Const badRequest

  • Bad Request HTTP response (400).

    Parameters

    Returns APIGatewayProxyResult

    The HTTP response object.

Const conflict

create

createHTMLResponseParams

createHTTPEvent

  • Creates a new instance of the HTTP Event class.

    Parameters

    • event: APIGatewayProxyEvent

      The API Gateway HTTP proxy event.

    • config: HTTPEventConfig

      The HTTP event configuration object.

    Returns HTTPEvent

    The HTTP Event object.

createHTTPRequest

  • createHTTPRequest(event: APIGatewayProxyEvent): HTTPRequest
  • Creates an HTTP request object.

    Parameters

    • event: APIGatewayProxyEvent

      The API Gateway HTTP event object.

    Returns HTTPRequest

    The HTTP request object.

createHTTPResponse

createResponse

  • createResponse(__namedParameters: { body: any; headers: any; isBase64Encoded: any; statusCode: any }): APIGatewayProxyResult
  • Creates an HTTP response.

    Parameters

    • __namedParameters: { body: any; headers: any; isBase64Encoded: any; statusCode: any }
      • body: any
      • headers: any
      • isBase64Encoded: any
      • statusCode: any

    Returns APIGatewayProxyResult

    The HTTP response.

createStaticFileHandler

createViewLoader

  • createViewLoader(__namedParameters: { basedir: string }): ViewLoader
  • Creates a new instance of Views.

    Parameters

    • __namedParameters: { basedir: string }
      • basedir: string

    Returns ViewLoader

    The component instance.

createViewLocals

  • Creates the view locals object.

    Parameters

    • Rest ...args: ViewLocalArg[]

      The objects to merge into the locals.

    Returns ViewLocals

    The merged locals values.

Const created

fileNotFound

  • fileNotFound(): APIGatewayProxyResult
  • Creates a file not found response.

    Returns APIGatewayProxyResult

    The HTTP response.

Const forbidden

get

  • get(basedir: string, path: string): Function
  • Retrieves a view template by path.

    Parameters

    • basedir: string

      The template basedir.

    • path: string

      The view's template relative path.

    Returns Function

    The required template function.

getBody

  • getBody(event: APIGatewayProxyEvent): object | string | number | boolean | null
  • Gets the HTTP request body as parsed JSON if possible.

    Parameters

    • event: APIGatewayProxyEvent

      The HTTP request event.

    Returns object | string | number | boolean | null

    The HTTP request body.

getHeaders

  • getHeaders(event: APIGatewayProxyEvent): Map<string, string>
  • Gets the HTTP request headers.

    Parameters

    • event: APIGatewayProxyEvent

      The HTTP request event.

    Returns Map<string, string>

    The HTTP request headers object.

getNonce

  • getNonce(size: number | boolean): string
  • Generates a nonce value from the provided config.

    Parameters

    • size: number | boolean

      The target size to generate of.

    Returns string

    The nonce value.

getParams

  • getParams(event: APIGatewayProxyEvent): Map<string, string>
  • Gets the HTTP request path parameters.

    Parameters

    • event: APIGatewayProxyEvent

      The HTTP request event.

    Returns Map<string, string>

    The HTTP request path parameters object.

getQuery

  • getQuery(event: APIGatewayProxyEvent): Map<string, string>
  • Gets the HTTP request query string parameters.

    Parameters

    • event: APIGatewayProxyEvent

      The HTTP request event.

    Returns Map<string, string>

    The HTTP request query string parameters object.

getResponseParams

handle

  • Handles response error.

    Parameters

    • config: HTTPResponseConfig

      The HTTP response configuration object.

    • Optional error: Error

      The error to handle.

    Returns APIGatewayProxyResult

    The handled HTTP response object.

Const internalServerError

  • internalServerError(): APIGatewayProxyResult
  • internalServerError(params?: HTTPResponseParams): APIGatewayProxyResult

Const movedPermanently

  • Moved Permanently HTTP response (301).

    Parameters

    Returns APIGatewayProxyResult

    The HTTP response object.

Const noContent

  • No Content HTTP response (204).

    Parameters

    Returns APIGatewayProxyResult

    The HTTP response object.

normalizeParams

Const notAcceptable

  • Not Acceptable HTTP response (406).

    Parameters

    Returns APIGatewayProxyResult

    The HTTP response object.

Const notFound

Const notModified

  • Not Modified HTTP response (302).

    Parameters

    Returns APIGatewayProxyResult

    The HTTP response object.

Const ok

Const preconditionFailed

  • Precondition Failed HTTP response (412).

    Parameters

    Returns APIGatewayProxyResult

    The HTTP response object.

render

  • render(basedir: string, path: string, locals?: object): string
  • Renders a view template.

    Parameters

    • basedir: string

      The template basedir.

    • path: string

      The view's path to render relative to the config.basedir.

    • Optional locals: object

      The locals object.

    Returns string

    The rendered HTML string.

send

  • send(config: HTTPResponseConfig, response: APIGatewayProxyResult): APIGatewayProxyResult
  • Sends a response to the request.

    Parameters

    • config: HTTPResponseConfig

      The HTTP response configuration object.

    • response: APIGatewayProxyResult

      The response object to send.

    Returns APIGatewayProxyResult

    The appropriate response object.

setAsJSON

  • setAsJSON(res: APIGatewayProxyResult): APIGatewayProxyResult
  • Creates a response as JSON.

    Parameters

    • res: APIGatewayProxyResult

      The HTTP response object.

    Returns APIGatewayProxyResult

    The JSON HTTP response object.

Const unauthorized

Legend

  • Property
  • Method

Generated using TypeDoc