@clipboard-health/json-api 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,83 @@
1
+ # @clipboard-health/json-api
2
+
3
+ Utilities for adhering to the [JSON:API](https://jsonapi.org/) specification.
4
+
5
+ ## Table of Contents
6
+
7
+ - [Install](#install)
8
+ - [Usage](#usage)
9
+ - [Local development commands](#local-development-commands)
10
+
11
+ ## Install
12
+
13
+ ```bash
14
+ npm install @clipboard-health/json-api
15
+ ```
16
+
17
+ ## Usage
18
+
19
+ ### Query helpers
20
+
21
+ From the client, call `toSearchParams` to convert from `ClientJsonApiQuery` to `URLSearchParams`:
22
+
23
+ <!-- prettier-ignore -->
24
+ ```ts
25
+ // ./examples/toSearchParams.ts
26
+
27
+ import { deepEqual } from "node:assert/strict";
28
+
29
+ import { toSearchParams } from "@clipboard-health/json-api";
30
+
31
+ import { type ClientJsonApiQuery } from "../src/lib/types";
32
+
33
+ const isoDate = "2024-01-01T15:00:00.000Z";
34
+ const query: ClientJsonApiQuery = {
35
+ fields: { dog: ["age"] },
36
+ filter: { age: [2], createdAt: { gte: new Date(isoDate) }, isGoodDog: true },
37
+ include: ["owner"],
38
+ page: { size: 10 },
39
+ sort: ["-age"],
40
+ };
41
+
42
+ deepEqual(
43
+ toSearchParams(query).toString(),
44
+ new URLSearchParams(
45
+ "fields[dog]=age&filter[age]=2&filter[createdAt][gte]=2024-01-01T15:00:00.000Z&filter[isGoodDog]=true&include=owner&page[size]=10&sort=-age",
46
+ ).toString(),
47
+ );
48
+
49
+ ```
50
+
51
+ From the server, call `toJsonApiQuery` to convert from `URLSearchParams` to `ServerJsonApiQuery`:
52
+
53
+ <!-- prettier-ignore -->
54
+ ```ts
55
+ // ./examples/toJsonApiQuery.ts
56
+
57
+ import { deepEqual } from "node:assert/strict";
58
+
59
+ import { type ServerJsonApiQuery, toJsonApiQuery } from "@clipboard-health/json-api";
60
+
61
+ const isoDate = "2024-01-01T15:00:00.000Z";
62
+ // The URLSearchParams constructor also supports URL-encoded strings
63
+ const searchParams = new URLSearchParams(
64
+ `fields[dog]=age&filter[age]=2&filter[createdAt][gte]=${isoDate}&filter[isGoodDog]=true&include=owner&page[size]=10&sort=-age`,
65
+ );
66
+
67
+ const query: ServerJsonApiQuery = toJsonApiQuery(searchParams);
68
+
69
+ deepEqual(query, {
70
+ fields: { dog: ["age"] },
71
+ filter: { age: ["2"], createdAt: { gte: isoDate }, isGoodDog: ["true"] },
72
+ include: ["owner"],
73
+ page: {
74
+ size: "10",
75
+ },
76
+ sort: ["-age"],
77
+ });
78
+
79
+ ```
80
+
81
+ ## Local development commands
82
+
83
+ See [`package.json`](./package.json) `scripts` for a list of commands.
package/package.json ADDED
@@ -0,0 +1,26 @@
1
+ {
2
+ "name": "@clipboard-health/json-api",
3
+ "description": "",
4
+ "version": "0.0.0",
5
+ "bugs": "https://github.com/clipboardhealth/core-utils/issues",
6
+ "dependencies": {
7
+ "tslib": "2.6.3"
8
+ },
9
+ "keywords": [],
10
+ "license": "MIT",
11
+ "main": "./src/index.js",
12
+ "publishConfig": {
13
+ "access": "public"
14
+ },
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/clipboardhealth/core-utils.git",
18
+ "directory": "packages/json-api"
19
+ },
20
+ "scripts": {
21
+ "embed": "embedme README.md"
22
+ },
23
+ "type": "commonjs",
24
+ "typings": "./src/index.d.ts",
25
+ "types": "./src/index.d.ts"
26
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ export * from "./lib/toJsonApiQuery";
2
+ export * from "./lib/toSearchParams";
3
+ export * from "./lib/types";
package/src/index.js ADDED
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const tslib_1 = require("tslib");
4
+ tslib_1.__exportStar(require("./lib/toJsonApiQuery"), exports);
5
+ tslib_1.__exportStar(require("./lib/toSearchParams"), exports);
6
+ tslib_1.__exportStar(require("./lib/types"), exports);
7
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../packages/json-api/src/index.ts"],"names":[],"mappings":";;;AAAA,+DAAqC;AACrC,+DAAqC;AACrC,sDAA4B"}
@@ -0,0 +1,7 @@
1
+ import { type ServerJsonApiQuery } from "./types";
2
+ /**
3
+ * Call this function from servers to convert from {@link URLSearchParams} to {@link ServerJsonApiQuery}.
4
+ *
5
+ * @see [Example](https://github.com/ClipboardHealth/core-utils/blob/main/packages/json-api/examples/toJsonApiQuery.ts)
6
+ */
7
+ export declare function toJsonApiQuery(searchParams: URLSearchParams): ServerJsonApiQuery;
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.toJsonApiQuery = toJsonApiQuery;
4
+ const REGEX = {
5
+ fields: /^fields\[(.*?)]$/i,
6
+ filter: /^filter\[([^\]]*?)]$/i,
7
+ filterType: /^filter\[(.*?)]\[(.*?)]$/i,
8
+ include: /^include$/i,
9
+ page: /^page\[(.*?)]$/i,
10
+ sort: /^sort$/i,
11
+ };
12
+ /**
13
+ * Call this function from servers to convert from {@link URLSearchParams} to {@link ServerJsonApiQuery}.
14
+ *
15
+ * @see [Example](https://github.com/ClipboardHealth/core-utils/blob/main/packages/json-api/examples/toJsonApiQuery.ts)
16
+ */
17
+ function toJsonApiQuery(searchParams) {
18
+ return [...searchParams].reduce((accumulator, [key, value]) => {
19
+ const match = Object.entries(REGEX).find(([, regex]) => regex.test(key));
20
+ if (!match) {
21
+ return accumulator;
22
+ }
23
+ const [type, regex] = match;
24
+ const groups = regex.exec(key)?.slice(1);
25
+ if (type === "fields" && groups?.[0]) {
26
+ return {
27
+ ...accumulator,
28
+ fields: {
29
+ ...accumulator.fields,
30
+ [groups[0]]: value.split(","),
31
+ },
32
+ };
33
+ }
34
+ if ((type === "filter" || type === "filterType") && groups?.length) {
35
+ const [field, fieldType] = groups;
36
+ if (field) {
37
+ return {
38
+ ...accumulator,
39
+ filter: {
40
+ ...accumulator.filter,
41
+ [field]: fieldType
42
+ ? { ...accumulator.filter?.[field], [fieldType]: value }
43
+ : value.split(","),
44
+ },
45
+ };
46
+ }
47
+ }
48
+ if (type === "include" || type === "sort") {
49
+ return { ...accumulator, [type]: value.split(",") };
50
+ }
51
+ if (type === "page" && groups?.[0]) {
52
+ return {
53
+ ...accumulator,
54
+ page: { ...accumulator.page, [groups[0]]: value },
55
+ };
56
+ }
57
+ /* istanbul ignore next */
58
+ return accumulator;
59
+ }, {});
60
+ }
61
+ //# sourceMappingURL=toJsonApiQuery.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"toJsonApiQuery.js","sourceRoot":"","sources":["../../../../../packages/json-api/src/lib/toJsonApiQuery.ts"],"names":[],"mappings":";;AAgBA,wCAgDC;AA9DD,MAAM,KAAK,GAAG;IACZ,MAAM,EAAE,mBAAmB;IAC3B,MAAM,EAAE,uBAAuB;IAC/B,UAAU,EAAE,2BAA2B;IACvC,OAAO,EAAE,YAAY;IACrB,IAAI,EAAE,iBAAiB;IACvB,IAAI,EAAE,SAAS;CACP,CAAC;AAEX;;;;GAIG;AACH,SAAgB,cAAc,CAAC,YAA6B;IAC1D,OAAO,CAAC,GAAG,YAAY,CAAC,CAAC,MAAM,CAAqB,CAAC,WAAW,EAAE,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE;QAChF,MAAM,KAAK,GAAG,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;QACzE,IAAI,CAAC,KAAK,EAAE,CAAC;YACX,OAAO,WAAW,CAAC;QACrB,CAAC;QAED,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,GAAG,KAAqC,CAAC;QAC5D,MAAM,MAAM,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,CAAC,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE;aAClD,CAAC;QACJ,CAAC;QAED,0BAA0B;QAC1B,OAAO,WAAW,CAAC;IACrB,CAAC,EAAE,EAAE,CAAC,CAAC;AACT,CAAC"}
@@ -0,0 +1,7 @@
1
+ import { type ClientJsonApiQuery } from "./types";
2
+ /**
3
+ * Call this function from clients to convert from {@link ClientJsonApiQuery} to {@link URLSearchParams}.
4
+ *
5
+ * @see [Example](https://github.com/ClipboardHealth/core-utils/blob/main/packages/json-api/examples/toSearchParams.ts)
6
+ */
7
+ export declare function toSearchParams(query: ClientJsonApiQuery): URLSearchParams;
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.toSearchParams = toSearchParams;
4
+ function filterValueString(value) {
5
+ return value instanceof Date ? value.toISOString() : String(value);
6
+ }
7
+ function join(values) {
8
+ return values.join(",");
9
+ }
10
+ /**
11
+ * Call this function from clients to convert from {@link ClientJsonApiQuery} to {@link URLSearchParams}.
12
+ *
13
+ * @see [Example](https://github.com/ClipboardHealth/core-utils/blob/main/packages/json-api/examples/toSearchParams.ts)
14
+ */
15
+ function toSearchParams(query) {
16
+ const searchParams = new URLSearchParams();
17
+ if (query.fields) {
18
+ Object.entries(query.fields).forEach(([type, fields]) => {
19
+ searchParams.append(`fields[${type}]`, join(fields));
20
+ });
21
+ }
22
+ if (query.filter) {
23
+ Object.entries(query.filter).forEach(([field, values]) => {
24
+ const filterField = `filter[${field}]`;
25
+ if (Array.isArray(values)) {
26
+ searchParams.append(filterField, join(values.map((value) => filterValueString(value))));
27
+ }
28
+ else if (typeof values === "boolean") {
29
+ searchParams.append(filterField, String(values));
30
+ }
31
+ else if (typeof values === "object") {
32
+ Object.entries(values).forEach(([fieldType, value]) => {
33
+ searchParams.append(`${filterField}[${fieldType}]`, filterValueString(value));
34
+ });
35
+ }
36
+ });
37
+ }
38
+ if (query.include) {
39
+ searchParams.append("include", join(query.include));
40
+ }
41
+ if (query.page) {
42
+ Object.entries(query.page).forEach(([key, value]) => {
43
+ searchParams.append(`page[${key}]`, String(value));
44
+ });
45
+ }
46
+ if (query.sort) {
47
+ searchParams.append("sort", join(query.sort));
48
+ }
49
+ return searchParams;
50
+ }
51
+ //# sourceMappingURL=toSearchParams.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"toSearchParams.js","sourceRoot":"","sources":["../../../../../packages/json-api/src/lib/toSearchParams.ts"],"names":[],"mappings":";;AAeA,wCAuCC;AApDD,SAAS,iBAAiB,CAAC,KAAqC;IAC9D,OAAO,KAAK,YAAY,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AACrE,CAAC;AAED,SAAS,IAAI,CAAC,MAAgB;IAC5B,OAAO,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAC1B,CAAC;AAED;;;;GAIG;AACH,SAAgB,cAAc,CAAC,KAAyB;IACtD,MAAM,YAAY,GAAG,IAAI,eAAe,EAAE,CAAC;IAE3C,IAAI,KAAK,CAAC,MAAM,EAAE,CAAC;QACjB,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,EAAE,MAAM,CAAC,EAAE,EAAE;YACtD,YAAY,CAAC,MAAM,CAAC,UAAU,IAAI,GAAG,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC;QACvD,CAAC,CAAC,CAAC;IACL,CAAC;IAED,IAAI,KAAK,CAAC,MAAM,EAAE,CAAC;QACjB,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,EAAE,MAAM,CAAC,EAAE,EAAE;YACvD,MAAM,WAAW,GAAG,UAAU,KAAK,GAAG,CAAC;YACvC,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,C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OAAO,YAAY,CAAC;AACtB,CAAC"}
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Filter types to build complex filter queries.
3
+ * - gt: Greater than
4
+ * - gte: Greater than or equal to
5
+ * - lt: Less than
6
+ * - lte: Less than or equal to
7
+ * - not: Not equal to
8
+ */
9
+ type FilterType = "gt" | "gte" | "lt" | "lte" | "not";
10
+ type PageKey = "cursor" | "limit" | "number" | "offset" | "size";
11
+ interface JsonApiQueryTypes {
12
+ filterValue: unknown;
13
+ filterTypeValue: unknown;
14
+ pageValue: unknown;
15
+ }
16
+ export interface ClientTypes {
17
+ filterValue: Array<Date | number | string> | boolean;
18
+ filterTypeValue: Date | number | string;
19
+ pageValue: number | string;
20
+ }
21
+ interface ServerTypes {
22
+ filterValue: string[];
23
+ filterTypeValue: string;
24
+ pageValue: string;
25
+ }
26
+ /**
27
+ * A JSON:API URL query string.
28
+ */
29
+ interface JsonApiQuery<T extends JsonApiQueryTypes> {
30
+ /**
31
+ * Fields to include in the response.
32
+ *
33
+ * @see {@link https://jsonapi.org/format/#fetching-sparse-fieldsets Sparse fieldsets}
34
+ */
35
+ fields?: Record<string, string[]>;
36
+ /**
37
+ * Filters to apply to the query.
38
+ *
39
+ * @see {@link https://jsonapi.org/recommendations/#filtering Filtering}
40
+ * @see {@link https://discuss.jsonapi.org/t/share-propose-a-filtering-strategy/257 Filtering strategy}
41
+ */
42
+ filter?: Record<string, T["filterValue"] | {
43
+ [K in FilterType]?: T["filterTypeValue"];
44
+ }>;
45
+ /**
46
+ * Relationships to include in the response.
47
+ *
48
+ * @see {@link https://jsonapi.org/format/#fetching-includes Fetching includes}
49
+ */
50
+ include?: string[];
51
+ /**
52
+ * Pagination data.
53
+ *
54
+ * @see {@link https://jsonapi.org/format/#fetching-pagination Pagination}
55
+ * @see {@link https://jsonapi.org/examples/#pagination Pagination examples}
56
+ */
57
+ page?: {
58
+ [K in PageKey]?: T["pageValue"];
59
+ };
60
+ /**
61
+ * Sorting data. Include the "-" prefix for descending order.
62
+ *
63
+ * @see {@link https://jsonapi.org/format/#fetching-sorting Sorting}
64
+ */
65
+ sort?: string[];
66
+ }
67
+ export type ClientJsonApiQuery = JsonApiQuery<ClientTypes>;
68
+ export type ServerJsonApiQuery = JsonApiQuery<ServerTypes>;
69
+ export {};
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../packages/json-api/src/lib/types.ts"],"names":[],"mappings":""}