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" }
}
}
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());
This middleware exposes two options: query
and extractor
.
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
.
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";
},
}),
);