Socket
Socket
Sign inDemoInstall

18h

Package Overview
Dependencies
Maintainers
1
Versions
44
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

18h

A Next.js style dynamic API router for Koa-based APIs.


Version published
Weekly downloads
140
increased by16.67%
Maintainers
1
Weekly downloads
 
Created
Source

18h

npm version

Installation   |   Get Started   |   Examples   |   Contributions

What is 18h?

18h is a Next.js-inspired Koa-router wrapper, which allows you to create routes that match the pattern of your filesystem. This speeds up iteration, while maintaining a serverful architecture.

This library is best used with Node.js & TypeScript in order to unlock all the type-safety capabilities it has to offer.

Why is it named 18h?

That is how long Koala's sleep, and all the cooler names were taken.

Get Started

Getting started is pretty snappy.

Installation

In order to install the package, in your root directory simply use your favourite package manager in order to install the package. It is registered on the NPM under the name 18h.

npm install 18h

Creating the Router

First, using your favourite file manager, or the command line, create the folder in which your routes will be stored in. This folder will mirror the structure of your API.

mkdir routes

Once this is complete, we will be able to instantiate our router object by referencing this folder. It's best practice to use the Node.js path module, along with the global __dirname constant in order to ensure the application runs correctly once it is transpiled to JavaScript.

import { join } from "path";
import { createRouter } from "18h";

createRouter({
  routesFolder: join(__dirname, "routes"),
  port: 4000,
  hostname: "localhost",
});

We can also instantiate the 18h router with global middleware that will run prior to every API call.

const logRequest = async (context, next) => {
  console.log(context);
  await next();
};

createRouter({
  // ...
  middleware: [logRequest],
});

Creating Routes

Its important to remember that the structure of the filesystem within the routes folder you provide as the routesFolder key is going to mirror the structure of your URLs.


Example

Assuming you provided a folder called routes as the routesFolder when creating your router object, creating a file at routes/index.ts it will allow consumers to interact with that endpoint at the http://localhost/ URL.

Creating a file called routes/example.ts will allow consumers to interact with that endpoint at the http://localhost/example URL.

Creating a file called routes/example/index.ts will produce the same result as mentioned above.

Note

Placing square brackets [] around the entire name of a folder or file in the routes folder will allow for route parameters to be accepted through that endpoint.

/a/[b]/c would become the endpoint path /a/:b/c.


The following file structure would generate the corresponding API endpoint structure.

File Structure
package.json
package-lock.json
node_modules/
src/
├── index.ts
└── routes/
    ├── index.ts
    ├── feed/
    │   └── index.ts
    ├── user/
    │   ├── delete.ts
    │   ├── index.ts
    │   └── settings/
    │       ├── private.ts
    │       └── name.ts
    ├── users/
    │   └── [userId]/
    │       ├── block.ts
    │       ├── index.ts
    │       └── follow.ts
    └── posts/
        ├── create.ts
        ├── delete.ts
        ├── index.ts
        ├── like.ts
        └── share.ts
tsconfig.json
Resulting API Path Structure
/
/feed
/user/
/user/delete
/user/settings
/user/settings/private
/user/settings/name
/users/:userId
/users/:userId/block
/users/:userId/follow
/posts
/posts/create
/posts/delete
/posts/like
/posts/share
Adding Logic to Paths

Of course, we want the paths to do things when someone interacts with them, that logic is defined in RouteController object, which takes multiple MethodControllers in which we define the logic of that endpoint.

Let's start off by creating the logic for the /users/[userId]/block endpoint so we can get a better feel for all the features.

// src/routes/users/[userId]/block

import { RouteController, MethodController } from "18h";
import { object, string, StringSchema } from "yup";

import { checkIsAuthenticated, canUserBlockUser } from "@/example/ambiguous";

/**
 * We can define the structure of the response.
 */
type ResponseStructure = {
  success: boolean;
};

/**
 * Notice that the request body schema is defined
 * using types from the "yup" validation library.
 *
 * This is so that validation can occur, it will
 * resolve to the output type within the context
 * so we can still get type-safe usage.
 */
type RequestBodySchema = {
  reason: StringSchema;
};

/**
 * Since the API route uses a route parameter, that
 * being :userId, we can define that here.
 */
type RouteParameters = {
  userId: string;
};

const route: RouteController<
  {
    post: MethodController<ResponseStructure, RequestBodySchema>;
  },
  RouteParameters
> = {
  post: {
    /**
     * When a request body schema is present, you
     * must provide an array of accepted types, that
     * being "json", "form", or both.
     */
    accept: ["json"],
    /**
     * When a request body schema is present, you
     * must provide a "yup" data validation object schema.
     * This wil ensure data integrity, and reject it if not.
     */
    validation: object({
      reason: string().required("reason is required"),
    }),
    /**
     * You may provide an array of middleware. These are
     * to be asynchronous functions. `pre` middleware will
     * run before the handler, `post` will run after.
     */
    middleware: {
      pre: [checkIsAuthenticated, canUserBlockUser],
      post: [],
    },
    /**
     * The handler should be where the core logic is run,
     * and where the response is handled.
     *
     * The only required field in the return of the handler
     * function is the `body` *if* the response body structure
     * is defined.
     */
    async handler(context) {
      console.log(context.params.userId);
      const requestingUser = context.request.user;

      return {
        headers: {
          "x-user-id": requestedUser?.id,
        },
        body: { success },
        code: 200,
      };
    },
  },
};

Examples

We can create a simple endpoint that just responds with the node package version of the current project we're in. The endpoint will work on all HTTP methods, not just GET, but we could change it to do that by changing all occurances of all to get.

const { npm_package_version: version } = process.env;

type VersionResponseBody = {
  version?: string;
};

const controller: RouteController<{
  all: MethodController<VersionResponseBody>;
}> = {
  all: {
    async handler(context) {
      return { body: { version } };
    },
  },
};

export default controller;

Contributions

Contributions are welcome! Happy hacking! 🎉

Keywords

FAQs

Package last updated on 13 May 2022

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc