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

@restless/restless

v0.4.2

Published

Express.js api, validations and more

Downloads

648

Readme

NPM CircleCI License

Restless

Express.js api, validations and more.

  1. Easy to write and read
  2. Declarative
  3. Type safe
import express from 'express'
import { asyncHandler, responseOf, sanitize } from '@restless/restless'
import { asNumber } from '@restless/sanitizers'

const app = express()
app.get('/add/:a/:b', asyncHandler(
  sanitize({
    a: asNumber,
    b: asNumber
  }),
  ({ a, b }) => responseOf(a + b)
))

Later:

GET /add/1/2 -> 200: 3
GET /add/foo/2 -> 400: { path: 'params.a', expected: 'number' }

Installation

npm install @restless/restless
yarn add @restless/restless

Api

asyncHandler

This function is essentially an async pipe. It takes a set of possibly async functions that are called with the return value of the previous function. It returns an express middleware that should be passed as a route handler to express.

Every function passed to asyncHandler takes two arguments:

  1. Return value of the previous function (undefined in case of the first one)
  2. The express Request object

Example:

import express from 'express'
import { asyncHandler, responseOf } from '@restless/restless'

const app = express()
app.get('/:foo', asyncHandler(
  (_, request) => request.params.foo,
  (foo) => responseOf(`Param foo is: ${foo}`)
))

Response functions

These are simple higher-order helper functions used to construct express responses. The asyncHandler requires that the last function passed to it returns a response function.

responseOf

Used to send json data:

responseOf({ foo: 'bar' }) // default 200 status
responseOf({ error: 'NOT_FOUND' }, 404) // custom status-code

responseOfBuffer

Used to send binary data from Buffer, use the first argument to specify data type:

responseOfBuffer('png', Buffer.from('ABC', 'ascii')) // default 200 status
responseOfBuffer('jpeg', Buffer.from('ABC', 'ascii'), 404) // custom status-code

Custom responses

In order to create a custom response all you need to do is write a custom function for it. Let's see how to create a response function for rendering views. First we need to consult the express documentation. There we see that in order to send a rendered view to the client we must call res.render. Writing a function for restless is now a piece of cake:

import { ResponseFunction } from '@restless/restless'
import { Response } from 'express'

export const responseOfView = (view: string, locals?: any, status = 200): ResponseFunction =>
  res => res
    .status(status)
    .render(view, locals)

Sanitization

This library exports all sanitizers from the @restless/sanitizers library.

sanitize

The sanitize function is a transformer. It transforms the request into an object that matches a schema you provide.

The keys in the provided schema correspond to the url parameters or the values on the request object from express. This means that if you try to sanitize a request to /users/:id calling sanitize({ id: ..., body: ... }) will check the req.params.id and req.body.

sanitize returns a function that is to be passed to asyncHandler.

Example:

import express from 'express'
import { asyncHandler, responseOf, sanitize } from '@restless/restless'
import { asObject, asNumber } from '@restless/sanitizers'

const app = express()
app.get('/:foo', asyncHandler(
  sanitize({
    foo: asNumber,
    body: asObject({
      bar: asNumber
    }),
    query: asObject({
      baz: asNumber
    })
  })
  (data) => responseOf(data)
))

For this declaration a valid request is as follows:

GET /123?baz=456 '{"bar":789}'

SanitizeError

This is the error that is thrown when sanitize function receives data that does not match the schema.