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

@tsndr/aws-lambda-router

v1.0.5

Published

AWS Lambda Router is a super lightweight router (2.30 KiB) with middleware support and **ZERO dependencies** for [AWS Lambda](https://aws.amazon.com/lambda/).

Downloads

13

Readme

AWS Lambda Router

AWS Lambda Router is a super lightweight router (2.30 KiB) with middleware support and ZERO dependencies for AWS Lambda.

I worked a lot with Express.js in the past and really enjoyed their middleware approach.

This is a port of @tsndr/cloudflare-worker-router.

Contents

Usage

Simple Example

import Router from '@tsndr/aws-lambda-router'

// Initialize router
const router = new Router()

// Enabling buildin CORS support
router.cors()

// Register global middleware
router.use(({ req, res, next }) => {
  res.headers.set('X-Global-Middlewares', 'true')
  next()
})

// Simple get
router.get('/user', ({ req, res }) => {
  res.body = {
    data: {
      id: 1,
      name: 'John Doe'
    }
  }
})

// Post route with url parameter
router.post('/user/:id', ({ req, res }) => {

  const userId = req.params.id
  
  // Do stuff...
  
  if (errorDoingStuff) {
    res.status = 400
    res.body = {
      error: 'User did stupid stuff!'
    }
    return
  }
  
  res.status = 204
})

// Delete route using a middleware
router.delete('/user/:id', ({ req, res, next }) => {

  if (!apiTokenIsCorrect) {
    res.status = 401
    return
  }
  
  await next()
}, ({ req, res }) => {

  const userId = req.params.id
  
  // Do stuff...
})

// Listen AWS API Gateway Event
export const handler = (event, context) => {
  return router.handle(event, context)
}

Reference

router.debug([state = true])

Enable or disable debug mode. Which will return the error.stack in case of an exception instead of and empty 500 response. Debug mode is disabled by default.

state

State is a boolean which determines if debug mode should be enabled or not (default: true)

router.use([...handlers])

Register a global middleware handler.

handler(ctx)

Handler is a function which will be called for every request.

ctx

Object containing env, req, res, next

router.cors([config])

If enabled will overwrite other OPTIONS requests.

config (object, optional)

Key | Type | Default Value ---------------------- | --------- | ------------- allowOrigin | string | * allowMethods | string | * allowHeaders | string | * maxAge | integer | 86400 optionsSuccessStatus | integer | 204

router.any(url, [...handlers])

router.connect(url, [...handlers])

router.delete(url, [...handlers])

router.get(url, [...handlers])

router.head(url, [...handlers])

router.options(url, [...handlers])

router.patch(url, [...handlers])

router.post(url, [...handlers])

router.put(url, [...handlers])

router.trace(url, [...handlers])

url (string)

The URL starting with a /. Supports the use of dynamic parameters, prefixed with a : (i.e. /user/:userId/edit) which will be available through the req-Object (i.e. req.params.userId).

handlers (function, optional)

An unlimited number of functions getting req and res passed into them.

ctx-Object

Key | Type | Description --------- | ------------------- | ----------- env | object | Environment req | req-Object | Request Object res | res-Object | Response Object next | next-Handler | Next Handler

req-Object

Key | Type | Description --------- | ------------------- | ----------- body | object / string | Only available if method is POST, PUT, PATCH or DELETE. Contains either the received body string or a parsed object if valid JSON was sent. headers | object | Request Headers Object method | string | HTTP request method params | object | Object containing all parameters defined in the url string query | object | Object containing all query parameters

res-Object

Key | Type | Description ----------- | ------------------- | ----------- body | object / string | Either set an object (will be converted to JSON) or a string headers | object | Response Headers Object status | integer | Return status code (default: 204) webSocket | WebSocket | Upgraded websocket connection

Setup

npm i -D @tsndr/aws-lambda-router

and replace your index.ts / index.js with one of the following scripts

import Router from '@tsndr/aws-lambda-router'

const router = new Router()

// TODO: add your routes here

export const handler: APIGatewayProxyHandlerV2<APIGatewayProxyEventV2> = (event, context) => {
    return router.handle(event, context)
}
import Router from '@tsndr/aws-lambda-router'

const router = new Router()

// TODO: add your routes here

export const handler = (event, context) => {
  return router.handle(event, context)
}