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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@brokkr/rest-api-server

v0.15.2

Published

The library provides a set of types that specifies HTTP protocol.

Readme

@brokkr/rest-api-server

The library provides a set of types that specifies HTTP protocol.

Aside of the types it also implements the core logic of an HTTP server that on the one hand routinely handles incoming requests and does the routing in a similar fashion express does it and on the other hand leverages type specifications to validate the incoming requests.

Routes

The core building block of a server is a route.

The route is a combination of essentially 3 things:

  • request object specification
  • response object specification
  • handler that gets a valid request object as its only parameter and returns a valid response object
import { route, Route } from '@brokkr/rest-api-server'
import { expectType } from '@brokkr/test-utils/expectType'
import {
  segmentField as $, choiceField, numberField, stringField
} from '@brokkr/validator/fields'

const routeObject = route('GET', 201)
  .path($._('pathKey', stringField()))
  .headers({
    headerKey: stringField(),
  })
  ._resp_
  .body(numberField())
  ._or_(202)
  .body(choiceField('one', 'two'))
  .headers({
        headerKey: stringField(),
  })
  .handler(async (request) => ({
    statusCode: 202,
    body: 'one',
    headers: {
      headerKey: request.pathParams.pathKey,
    },
  }))

expectType<Route, typeof routeObject>(true)

Note, the routes do not handle trafic in any meaningful way, they are just a specification for the handlers.

Fluent API for the most common case

There is a fluent API aiming to simplify route configuration in the most common case (one 200ish response per handler, known status codes for various request methods).

import { createRouteCollection  } from '@brokkr/rest-api-server'

const itemSpec = {
  title: stringField(),
  description: stringField(),
}

// 'routes' is a list that effectively will aggregate the routes
// defined via a '_' helper object
const _ = createRouteCollection()

// As an alternative you may import '_' singleton object that is
// not linked to any routes collection. In that case you would need
// to add routes to the collections explicitly via 'routes.push'

/**
import { _ } from '@brokkr/rest-api-server'

const routes: Route[] = []

routes.push(_.GET(...).spec(...).handler(...))
*/

const getRoute = _.GET($._('/items'))._resp_.body(
  [itemSpec],
).handler(
  async () => ({
    body: [
      {
        title: 'Item N',
        description: 'Description',
      },
    ],
  }),
)

expectType<Route, typeof getRoute>(true)

const postRoute = _.POST($._('/items')).body(itemSpec)._resp_.body(
  numberField(),
).headers({
  title: stringField(),
}).handler(
  async () => ({
    body: 42,
    headers: {
      title: 'Foo',
    },
  }),
)

expectType<Route, typeof postRoute>(true)

Server object

For any arbitrary set of routes it is possible to join those with extra parameters to craft server configs:

import { createServer } from '@brokkr/rest-api-server'

import http from 'http'

const server = createServer({
  baseUrl: 'http://localhost:8080',
  routes: _.routes
})

expectType<http.Server & { serve: () => http.Server }, typeof server>(true)

Running the app

To actually run the server and handle trafic using it, run serve method:


server.serve()

Once the app is started you may run the following curl command to obtain the payload from the endpoint:

curl -X GET "http://localhost:8080/items"

Or post a new entry:

curl -X POST "http://localhost:8080/items" -H  "Content-Type: application/json" \
  -d "{\"title\":\"string\",\"description\":\"string\"}"

The following call will produce a 400 (validation) error:

curl -X POST "http://localhost:8080/items" -H  "Content-Type: application/json" \
  -d "{\"title\":true,\"description\":\"string\"}"

Cheat sheet

Response with cookies:

import { headerObjectField } from '@brokkr/rest-api-server/fields'

const withCookies = _.GET($._('/with-cookies'))
  ._resp_
  .body([itemSpec])
  .headers({
    cookies: headerObjectField({
      cookieStr: stringField(),
      cookieNum: numberField()
    })
  })
  .handler(async () => ({
    body: [
      {
        title: 'Item N',
        description: 'Description',
      },
    ],
    headers: {
      cookies: {
        cookieStr: 'foo',
        cookieNum: 42
      }
    }
  }))

expectType<Route, typeof withCookies>(true)

Request with authorization:

const withAuthorization = _.POST($._('/with-cookies'))
  .headers({
      authorization: $._('type', stringField())._(' ')._('credentials', stringField())
  })
  ._resp_
  .handler(async () => undefined)

expectType<Route, typeof withAuthorization>(true)