npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

somod-http-extension

v1.2.3

Published

SOMOD middleware to intercept and validate Lambda event for AWS APIGateway

Downloads

49

Readme

SOMOD Http Extension


The SOMOD Extension Configure HTTP routes and validate incoming HTTP Requests in Serverless Functions.

The middlware in this extension works with Functions of type HttpApi Only.

Install

Install as an npm package in somod modules

npm install somod-http-extension

Usage

Attach the middleware to the Serverless Function

Resources:
  MyHttpHandler:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri:
        SOMOD::Function:
          # ...
          middlewares:
            - module: somod-http-extension
              resource: SomodHttpMiddleware
      # ...

Refer to SOMOD's Middleware reference for more information

Configure Routes and Schemas

Routes configuration for each serverless function can be provided using a yaml file at serverless/functions/<function_name>.http.yaml.

Example:

# serverless/functions/user.http.yaml

/user/{userId}:
  GET:
    parameters:
      - in: path
        name: userId
        schema:
          type: string
          maxLength: 32
        required: true
  POST:
    parameters:
      - in: path
        name: userId
        schema:
          type: string
          maxLength: 32
        required: true
    body:
      parser: json
      schema:
        type: object
        required: [name]
        properties:
          name:
            type: string
            maxLength: 32
          email:
            type: string
            format: email

Access Sanitized Request

The sanitized request can be accessed using the middleware's context using the somod-http-request key.

Example:

// serverless/functions/user.ts

const UserService = event => {
  const request = event.somodMiddlewareContext.get("somod-http-request");
  // use request to read the data from the incoming http request
};

export default UserService;

This module also provides a utility library to create Serverless Functions with multiple routes easily. Refer to RouteBuilder for more details

Specification

Structure of Routes configuration file

In general, routes configuration in <function_name>.http.yaml file follows the below structure

<path>:
  <method>:
    parameters?:
      - in: <"path", "query" or "header">
        name: <name of the parameter>
        schema: <json schema>
        required: <true if the parameter is mandatory>
    body?:
      parser?: <"text"|"json"|"formdata">. If not provided, automatically choosen based on the Content-Type Header (text is considered if automatic detection fails)
      schema: <json schema>

The complete JSONSchema is available here

Type of the Request object

The request object accessed using event.somodMiddlewareContext.get("somod-http-request") has this type.

type Request<
  T = unknown,
  PT extends Record<string, unknown> = Record<string, unknown>,
  QT extends Record<string, unknown> = Record<string, unknown>,
  HT extends Record<string, unknown> = Record<string, unknown>
> = {
  route: string;
  method: string;
  parameters: {
    path: PT;
    query: QT;
    header: HT;
  };
  body: T;
};

The Request Type is available from this module to use (import as shown below)

import { Request } from "somod-http-extension";

HTTP Error Types

The validation middleware returns the following HTTP error codes

  • 404 - When the method and path in the incoming http request do not match any of the configured routes.
  • 400 - When the parsing or validating of the incoming request fails (following the configuration in <function_name>.http.yaml).
  • 500 - Any other failures.

RouteBuilder

The RouteBuilder is a wrapper javascript utility library to create serverless functions with multiple routes.

Using the RouteBuilder

// serverless/function/user.ts
import { RouteBuilder } from "somod-http-extension";

const builder = new RouteBuilder();

builder.add("/user/{userId}", "get", getUserFunction);
builder.add("/user/{userId}", "post", updateUserFunction);

export default builder.getHandler();

RouteBuilder Specification

RouteBuilder has 2 methods

  • add

    function add(
      path: string,
      method: string,
      handler: (request: Request, event: RawEvent) => Promise<Response>
    ): void {
      //
    }

    The handler receives the sanitized request object and the raw event from AWS. The handler has to return a promise which resolves to the Response object.

    The Raw Event type and Response type is documented here in the AWS specification.
    This module works with HTTP Payload format version 2.0 only

  • handle

    function handle(): (event: RawEvent) => Promise<Response> {
      //
    }

    handle function returns the function which is a lambda function handler

Issues

The project issues, features, and milestones are maintained in this GitHub repo.

Create issues or feature requests at https://github.com/somod-dev/somod-http-extension/issues

Contributions

Please read our CONTRIBUTING guide before contributing to this project.