@0x57/hono-array-map

1.0.0 • Public • Published

@0x57/hono-array-map

Hono middleware that allows consumers to pass ?list=map to your API in order to transform arrays of uniquely identifiable objects to a keyed object. This is useful for frontend applications that store information this way as cached state.

For example, say your API returns this JSON result:

GET /search:

{
	"results": [
		{ "id": 1, "name": "Ian" },
		{ "id": 2, "name": "Leah" }
	]
}

By instead requesting GET /search?list=map this middleware will transform the JSON response to this:

{
	"results": {
		"1": { "id": 1, "name": "Ian" },
		"2": { "id": 2, "name": "Leah" }
	}
}

Usage

Install the package with your package manager of choice

npm i @0x57/hono-array-map

Then apply the Hono middleware

import { arrayMap } from "@0x57/hono-array-map";
import { Hono } from "hono";

const app = new Hono();
app.use("*", arrayMap());

Options

This middleware exposes two options: query and extractor.

query?: string (default: list)

Set this option to change the query parameter the middleware reads from. By default, the middleware checks for ?list=map. By setting query to array, consumers would instead pass array=map.

extractor?: (value: JSONObject) => string

Set this option to override the builtin key extractor. If your API uses guid instead of id as the entity unique identifier, you would use something like this to extract the list identifier:

import { arrayMap, type JSONObject } from "@0x57/hono-camel-snake";
import { Hono } from "hono";

const app = new Hono();
app.use(
	"*",
	arrayMap({
		extractor: (value: JSONObject) => {
			if ("guid" in value) {
				if (typeof value.guid === "string") {
					return value.guid;
				}

				if (typeof value.guid === "number") {
					return value.guid.toString();
				}
			}

			return "unknown";
		},
	}),
);

Readme

Keywords

none

Package Sidebar

Install

npm i @0x57/hono-array-map

Weekly Downloads

597

Version

1.0.0

License

none

Unpacked Size

67.8 kB

Total Files

16

Last publish

Collaborators

  • ianmitchell