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

serverless-functions

v0.5.4

Published

A toolkit for writing, testing, running and deploying serverless functions (e.g. AWS Lambda).

Downloads

48

Readme

A toolkit for writing, testing, running and deploying serverless functions (e.g. AWS Lambda).

Concepts

"Serverless" means splitting an API into a set of independent functions (API endpoints). Each function is a directory having a function.json description file and an index.js main code file (which can import any other code) which exports default async function which takes a parameters object (HTTP GET query parameters, HTTP POST body, etc) and returns a response which could be, for example, a JSON object.

Use

Create a new project.

Create a .babelrc file in it:

{
  "presets": [
    ["@babel/preset-env", {
      "targets": {
        "node": "8.10"
      }
    }]
  ],
  "plugins": [
    "@babel/plugin-proposal-object-rest-spread",
    "@babel/plugin-proposal-class-properties"
  ]
}

(The above example is for Babel 7. For Babel 6 see version 0.2.x.)

(Support for babel.config.js hasn't been tested; .babelrc seems to work)

Create a serverless.json file in it:

{
  "name": "project-name"
}

To create a function create a directory anywhere inside the project directory and put index.js and function.json files in that directory.

function.json is the description of the function, i.e. its name, which URL does it respond on, to which HTTP method, etc.

{
  "name": "function-name",
  "path": "/example-function/{parameterName}",
  "method": "GET"
}

index.js is the function code:

export default async function({ params, body, query }) {
  return {
    parameter: params.parameterName
  }
}

Install serverless-functions package:

npm install serverless-functions --save

Add a new script to package.json:

{
  "scripts": {
    "run-locally": "serverless run dev 8888"
  }
}

Run the functions locally:

npm run run-locally

Go to http://localhost:8888/example-function/123. It should respond with { parameter: 123 }.

Input

The function receives the following parameters:

  • params — URL path parameters (e.g. /users/{id}).
  • query — URL query parameters.
  • body — HTTP request body.
  • headers — HTTP request headers.

Output

The function can return anything. If it doesn't return anything then an empty object is assumed (in order for the HTTP response to be a valid JSON).

Errors

To return an error from a function one can throw an instance of Error with an optional httpStatusCode property. The HTTP Response status code is gonna be the value of the httpStatusCode property (or 500) and the HTTP Response JSON object is gonna contain error?: object and statusCode: number. The error object contains message: string and all properties from error.data, if it's present.

export default async function() {
  throw new Error('Test')
}

There are some pre-defined errors available:

  • Unauthenticated
  • Unauthorized
  • NotFound
  • Conflict
  • InputRejected
import { Unauthorized } from 'serverless-functions/errors'

export default async function() {
  // Throws a 403 Forbidden error.
  throw new Unauthorized('You are not authorized to perform this action')
}

Streaming

Currently serverless functions seem to not support streaming HTTP request/response data. Use the old-school Node.js stuff for that (e.g. express).

AWS Setup

See the AWS Lambda guide.

Extending

One can customize the code template used for generating functions. The template is:

$initialize()
export async function handler(event, context, callback) {
  try {
    await $onCall(event, context)
    const parameters = $createFunctionParameters(event, context)
    let result = await $handler(parameters)
    result = (await $onReturn(result)) || result
    callback(null, $createResponse(result))
  } catch (error) {
    await $onError(error)
    callback(null, $createErrorResponse(error))
  } finally {
    await $finally()
  }
}

Each of the $ parameters (except $handler) can be customized by adding a respective code entry in serverless.json:

{
  "name": "project-name",
  "code": {
    "initialize": "./custom/initialize.js"
  }
}

./custom/initialize.js file path is resolved against the root project directory (process.cwd()).

./custom/initialize.js

import Database from './database'
import config from './config'

function $initialize() {
  const database = new Database(config[STAGE].database)
  database.connect()
  // Make the `database` accessible from functions.
  global.database = database
}

Relative imports inside "custom" code pieces are resolved against the root project directory too.

The global database variable can then be used inside functions:

export default async function() {
  return {
    items: await database.items.findAll({ limit: 10 })
  }
}

Globals

The execution envirnoment provides the following global constants:

  • STAGE : string — the current "stage" (e.g. dev, prod, test).
  • FUNCTION : object — the contents of function.json.
  • LOCAL : boolean — whether the functions are being run locally (serverless run) rather than being deployed in a cloud.

Testing

For each function one should also create an index.test.js file with unit tests. Example using mocha/chai:

import func from '.'

describe('function-name', () => {
  it('should return some result for some input', async () => {
    expect(await func(input)).to.deep.equal(output)
  })
})

API

import { run } from 'serverless-functions'
import config from './serverless.json'

await run(stage, port, config, { cwd: process.cwd() })