serverlet
TypeScript icon, indicating that this package has built-in type declarations

0.1.3 • Public • Published

serverlet

Build Status JavaScript Style Guide

A serverlet is a function that accepts an HTTP request and returns an HTTP response:

const helloRoute = (request: HttpRequest): HttpResponse => {
  return {
    headers: { 'content-type': "text/plain" }
    body: 'Hello, world!'
  }
}

You can use a serverlet as an Express route:

import { makeExpressRoute } from 'serverlet/express'

app.get('/', makeExpressRoute(helloRoute))

You can also use a serverlet to mock the fetch function:

import { makeFetchFunction } from 'serverlet'

window.fetch = makeFetchFunction(helloRoute)

// Now run some tests...

Of course, just serving a single route isn't very interesting. A more complete server will combine many serverlets together:

import { pickPath, pickMethod, withCors } from 'serverlet'

const server = pickPath({
  '/hello': withCors(helloRoute),
  '/api/user': pickMethod({
    GET: getUserRoute,
    POST: postUserRoute
  })
}, missingRoute)

The pickPath and pickMethod helper functions combine multiple smaller serverlets together into a bigger serverlet, so the returned server is just another serverlet.

The withCors helper function is an example of a middleware. It accepts a serverlet, and returns an enhanced serverlet that sets the appropriate headers.

You can easily create your own middleware functions:

export const withApiKey = (route: Serverlet): Serverlet => request => {
  // Bail out if we don't have an API key:
  if (request.headers.authorization !== expectedApiKey) {
    return { status: 401 }
  }

  // Otherwise, run the route:
  return route(request)
}

The Serverlet type is generic, so middleware can add properties to the request or response objects, and it's all type-safe.

Readme

Keywords

none

Package Sidebar

Install

npm i serverlet

Weekly Downloads

75

Version

0.1.3

License

MIT

Unpacked Size

32.3 kB

Total Files

21

Last publish

Collaborators

  • swansontec