Giter Site home page Giter Site logo

somod-http-extension's Introduction

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.

somod-http-extension's People

Contributors

raaghu avatar lokeshgcl avatar

Watchers

 avatar  avatar

Forkers

raaghu

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.