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

remix-api-router

v1.2.0

Published

Library for implementing APIs in Remix using a chaining approach, similar to Express middleware

Downloads

9

Readme

Remix API Router

Build status Coverage Status semantic-release npm npm

Library for creating APIs in Remix using a chaining approach, similar to Express middleware.

Note: originally I was planning to implement a chain-of-responsibility pattern with the same contract as Express, but I wasn't sure how much adoption it will have. If you are interesting in it, let's talk!.

Installation

npm i remix-api-router

or

yarn add remix-api-router

Usage

For example, create a products.tsx file inside a Remix app, under the app/routes/api folder, and paste the following code:

import { apiRouter } from "remix-api-router";
import { checkAuth } from "auth";
import { json } from "@remix-run/node";
import type { ActionFunction, LoaderFunction, DataFunctionArgs } from "@remix-run/node";

/**
 * /api/products
 */

// Define all routes for this endpoint and their handlers
const router = apiRouter();
router
  .get(checkAuth, async (args: DataFunctionArgs) => {
    await fetch("https://google.com");
    return json({ message: "GET" }, 200);
  })
  .post(checkAuth, (args: DataFunctionArgs) => json({ message: "POST" }, 200))
  .put((args: DataFunctionArgs) => json({ message: "PUT" }, 200))
  .patch((args: DataFunctionArgs) => json({ message: "PATCH" }, 200))
  .delete((args: DataFunctionArgs) => {
    throw new Error("unexpected error");
  })
  .error((err) => {
    return json({ error: "Custom message: Server unavailable!" }, 500);
  });

export const loader: LoaderFunction = router.loader();
export const action: ActionFunction = router.actions();

Note see a fully working example here.

Features

  • Same API as Remix for developing handlers: it's just sugar syntax to provide a chaining-like approach.
  • Provides a handler for errors/exceptions of your code by default, returning 500 (you can provide your own).
  • Provides a handler for no matching routes, returning 405 (you can provide your own).
  • Lightweight (~ 4.5KB) => Suitable for serverless environment.
  • TypeScript support.

API

General rules

  1. Create a single router instance per file.
  2. A handler that returns a value stops the chaining process. The expected return value is a Response object, just what Remix expects.
  3. A handler that returns either nothing or a Promise with no return value (void or Promise<void> will tell the chain to continue processing the request with the other handlers.
  4. A handler that throws an error will also tell the chain to stop processing the request. You can configure the error handling with your own logic by configuring the router.error handler.
  5. If a request arrives and no handler is configured, it will return a default response: 405 Method not allowed. You can configure this with your own logic by configuring the router.noMatch handler.
  6. Always connect the router with Redux via the named exports loader and action.
  7. Configure handlers once per router, as other configurations will override the previous ones.

Configuration

You can initialize the router using either a class instantiation or a factory instantiation:

  • Use the default export for a class instantiation:

    import ApiRouter from "remix-api-router";
    import { json } from "@remix-run/node";
    
    const router = new ApiRouter();
    router.get(() => json({ hello: "world" }, 200)).post(() => json({ hello: "world" }, 201));
  • Use the named export "apiRouter" for the factory instantiation:

    import { apiRouter } from "remix-api-router";
    import { json } from "@remix-run/node";
    
    const router = new ApiRouter();
    router.get(() => json({ hello: "world" }, 200)).post(() => json({ hello: "world" }, 201));

Last, hook the router with the Remix loader and action by simply exporting the following at the end of the file:

import { apiRouter } from "remix-api-router";
import { json } from "@remix-run/node";

const router = apiRouter();
router
  .get(() => json({ hello: "world" }, 200))
  .post(() => json({ hello: "world" }, 201))
  ...

export const loader: LoaderFunction = router.loader();
export const action: ActionFunction = router.actions();

Route handling

It supports all HTTP Methods by adding a handler with the same contract provided by Remix. For example:

To handle GET /api/categories/$id requests, use the following code:

import { apiRouter } from "remix-api-router";
import { json } from "@remix-run/node";
import type { ActionFunction, LoaderFunction, DataFunctionArgs } from "@remix-run/node";

/**
 * /api/categories/$id
 */

const router = apiRouter();

router.get(({ request, context, params }: DataFunctionArgs) => {
  return json({ message: `Requested category with ID ${params.id}` }, 200);
});

export const loader: LoaderFunction = router.loader();
export const action: ActionFunction = router.actions();

To handle GET /api/categories and POST /api/categories requests, use:

import { apiRouter } from "remix-api-router";
import { json } from "@remix-run/node";
import type { ActionFunction, LoaderFunction, DataFunctionArgs } from "@remix-run/node";

/**
 * /api/categories
 */

const router = apiRouter();

router
  .get(async ({ request, context, params }: DataFunctionArgs) => {
    // See https://remix.run/docs/en/v1/guides/data-loading#url-search-params
    const url = new URL(request.url);
    const term = url.searchParams.get("term");
    return json(await fakeProductSearch(term));
  })
  .post(async ({ request, context, params }: DataFunctionArgs) => {
    const body = await request.json();
    return json({ message: `Sent body ${JSON.stringify(body)}` });
  });

async function fakeProductSearch(term: string | null) {
  return [
    { id: 1, name: "Category A" },
    { id: 2, name: "Category B" },
  ];
}

export const loader: LoaderFunction = router.loader();
export const action: ActionFunction = router.actions();