Package Exports
- @clipboard-health/json-api
- @clipboard-health/json-api/src/index.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@clipboard-health/json-api) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
@clipboard-health/json-api
TypeScript-friendly utilities for adhering to the JSON:API specification.
Table of contents
Install
npm install @clipboard-health/json-api
Usage
Query helpers
From the client, call toClientSearchParams
to convert from ClientJsonApiQuery
to URLSearchParams
:
import { deepEqual } from "node:assert/strict";
import { toClientSearchParams } from "@clipboard-health/json-api";
import { type ClientJsonApiQuery } from "../src/lib/types";
const [date1, date2] = ["2024-01-01", "2024-01-02"];
const query: ClientJsonApiQuery = {
fields: { user: ["age", "dateOfBirth"] },
filter: {
age: { eq: ["2"] },
dateOfBirth: { gt: [date1], lt: [date2] },
isActive: { eq: ["true"] },
},
include: ["article"],
page: {
size: "10",
},
sort: ["-age"],
};
deepEqual(
toClientSearchParams(query).toString(),
new URLSearchParams(
`fields[user]=age,dateOfBirth&filter[age]=2&filter[dateOfBirth][gt]=${date1}&filter[dateOfBirth][lt]=${date2}&filter[isActive]=true&include=article&page[size]=10&sort=-age`,
).toString(),
);
import { deepEqual } from "node:assert/strict";
import { type ServerJsonApiQuery, toServerJsonApiQuery } from "@clipboard-health/json-api";
const [date1, date2] = ["2024-01-01", "2024-01-02"];
// The URLSearchParams constructor also supports URL-encoded strings
const searchParams = new URLSearchParams(
`fields[user]=age,dateOfBirth&filter[age]=2&filter[dateOfBirth][gt]=${date1}&filter[dateOfBirth][lt]=${date2}&filter[isActive]=true&include=article&page[size]=10&sort=-age`,
);
const query: ServerJsonApiQuery = toServerJsonApiQuery(searchParams);
deepEqual(query, {
fields: { user: ["age", "dateOfBirth"] },
filter: {
age: { eq: ["2"] },
dateOfBirth: { gt: [date1], lt: [date2] },
isActive: { eq: ["true"] },
},
include: ["article"],
page: {
size: "10",
},
sort: ["-age"],
});
Local development commands
See package.json
scripts
for a list of commands.