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

decade

v1.0.2

Published

Dead simple HTTP/s Server

Downloads

3

Readme

Decade ☄️

Travis CI badge Codeclimate maintainability Dependabot Status

Dead simple HTTP/s Server Wrapper with zero dependencies written with Typescript in about 200 lines.

This library encourages users to work with built in Node modules and the built in Router only supports two Http verbs, GET and POST, because the other ones are trash.

Install

Install with yarn.

yarn add decade

Usage

Create a http and https server.

import { Server } from "decade";

const server = new Server({
  http: 3080,
  https: 3443,
  options: {
    key: "...",
    cert: "...",
  },
});

Plugin

Decade provides a simple Plugin system, a plugin should be something with a register method which will receive the Server instance and a Logger instance, from there you can listen for and emit events.

import { Server, Logger } from "decade";
export class MyPlugin implements Server.Plugin {
  ...
  async register(server: Server, logger: Logger): Promise<void> {
    this.server = server;
    this.logger = logger;
    server.on("request", this.doSomething.bind(this));
  }

  async someOtherMethod() {
    this.logger.info("something happened!");
    this.server.emit("customevent", "foo");
  }
}

To use a plugin, pass it into the Server.plugin method.

import { Server } from "decade";
import { FooPlugin } from "decade-foo-plugin";

const server = new Server({...});
server.plugin(new FooPlugin("bar"));

Router

There's a built in Router plugin available for import which can be initialized with an array of Router.Route objects.

import { Server, Router } from "decade";
import * as routes from "./routes";

const server = new Server({...})

const router = new Router(Object.values(routes));

server.plugin(router);

For simple JSON responses you can return a Router.Route.Payload object from a handler which will be parsed and sent to the client.

import { Router } from "decade";

export const simpleRoute: Router.Route = {
  path: /^\/[a-z]+$/,
  method: "GET",
  handler: [
    async () => {
      return {
        status: 200,
        headers: {
          "Foo-Bar": "Baz-Qak",
        },
        body: {
          foo: "bar",
        },
      };
    },
  ]
}

If you need more control, you can craft your own response and simply return void from the handler - handlers are called in-order so you can drop in middleware wherever suits.

import { Router } from "decade";
import { fooMiddleware } from "./middleware"

export const detailedRoute: Router.Route = {
  path: /^\/proxy$/,
  method: "GET",
  handler: [
    fooMiddleware,
    async (request, response) => {
      https.get('https://www.example.com', (proxy) => {
        response.setHeader('Content-Type', proxy.headers['content-type']);
        proxy.pipe(response);
      });
    },
  ]
}

Routes resolve sequentially so if you have multiple routes which match the request URL they will all be called in the order that they were added to the Router.

A common oversight is resolving routes too early, like the proxy route above which resolves immediately. Routes should only resolve once they are finished interacting with the request and response objects.

Middleware

By default incoming request objects aren't parsed for JSON or URL Encoded payloads but you can use built in Middleware to do this.

json

import { Server, Router } from "decade";

export const jsonRoute: Router.Route = {
  ...
  handler: [
    Server.Middleware.json,
    ...
  ]
}

urlencoded

import { Server, Router } from "decade";

export const jsonRoute: Router.Route = {
  ...
  handler: [
    Server.Middleware.urlencoded,
    ...
  ]
}

If you need support for Multipart form data or anything else you can write your own middleware or use a fully featured library like body-parser.

Examples

404 Not Found

There is no built in helper to detect that no routes match the request, however when a request is received all matching routes will be called in order of instantiation so you can craft your own 404 handler by adding a "catch all" path /.*/ as the last route.

export const notFoundRoute: Router.Route = {
  path: /.*/,
  method: "GET",
  handler: [
    async (request, response) => {
      if(response.headersSent) {
        return
      }

      return {
        status: 404,
        body: "Not Found",
      };
    },
  ],
}

Cookies

If you're adventurous you can bake your own cookies but it's recommended to use a library like cookie, afterwards you can set them as usual.

import * as cookie from "cookie";

export const cookieRoute: Router.Route = {
  ...
  handler: [
    async (request, response) => {
      return {
        status: 200,
        headers: {
          "Set-Cookie": "foo=bar",
          // or
          "Set-Cookie": cookie.serialize("foo", "bar", {...}),
        },
        body: "Cookies!",
      };
    },
  ],
}

Outgoing Transformations

It's pretty common practice to log or tag requests as they head back to the client, as an example let's create a middleware that adds a timestamp header to responses - if you're using the "simple" method of returning a Router.Route.Payload it is passed along to future middlewares as the third argument.

You can do this in two ways, the first by using the http.ServerResponse object and the setHeader() method, the second by mutating the Router.Route.Payload object's headers property.

export const timestampMiddleware: Router.Route.Handler = async (request, response, payload) => {
  response.setHeader("timestamp", new Date().getTime().toString());

  return payload;

  // or

  payload.headers = {
    ...payload.headers,
    timestamp: new Date().getTime().toString(),
  }

  return payload;
}

export const transformedRoute: Router.Route = {
  ...
  handler: [
    async () => {
      return {
        ...
      };
    },
    timestampMiddleware,
  ],
}