1.0.4 • Published 6 years ago

aws-lambda-proxy-router v1.0.4

Weekly downloads
3
License
ISC
Repository
github
Last release
6 years ago

aws-lambda-proxy-router

This library provides a simple router when using a lambda triggered by API Gateway lambda proxy events.

Usage

let Router = require('aws-lambda-proxy-router');

module.exports.handler = (event, context, callback) => {

    let r = new Router(event,context,callback);

    // Use any middleware function you want here
    r.use(event => {
        if(event.body)
            return Object.assign({},event,{body: JSON.stringify(event.body)})
        else
            return event;
    });

    // Bind a simple route
    // Returns a promise that resolves if the route matches.
    // The resolved value is either the event, or the output of your middleware functions.
    r.on("GET", "/Customers")
        .then(event => "Hello World")
        .then(result => callback(null,{
            statusCode:200,
            body: JSON.stringify(result)
        }))
        .catch(err => callback(null,{
            statusCode: 500,
            body: "Internal Server Error"
        }));

    // Helper methods for GET, POST, PUT, DELETE
    r.get("/Customers")
        .then(event => "Hello World")
        //...

    // Can add mappings or 'middleware' to specific routes by just promise chaining
    r.get("/Customers")
        .then(event => myCustomAuth(event))
        .then(event => event.queryStringParameters.foo)
        .then(foo => getCustomerById(foo))
        //...

    // Call r.on404() last. This will be called if no other route matches.
    r.on404()
        .then(() => callback(null,{
            statusCode:"404",
            body: "No Route Found"
        }))
};

Point-Free Syntax

Since the syntax is all promised base, you can chain calls together in a point-free style.

let Router = require('aws-lambda-proxy-router');

module.exports.handler = (event, context, callback) => {

    let r = new Router(event,context,callback);

    let Respond = (result) => callback(null,{
        statusCode:200,
        body: JSON.stringify(result)
    });

    let GetCustomers = (event) => {
        //All my async code here
        //Return a promise that resolves to the customers
    };

    // Point free!
    r.get("/Customers")
        .then(GetCustomers)
        .then(Respond)
        .catch(console.error)

    r.put("/Customers")
        .then(PutCustomer)
        .then(Respond)
        .catch(console.error)
};
1.0.4

6 years ago

1.0.3

6 years ago

1.0.2

6 years ago

1.0.1

6 years ago

1.0.0

6 years ago