@bjornharrtell/json-api 0.1.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.
Files changed (40) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +68 -0
  3. package/dist/docs/.nojekyll +1 -0
  4. package/dist/docs/assets/hierarchy.js +1 -0
  5. package/dist/docs/assets/highlight.css +85 -0
  6. package/dist/docs/assets/icons.js +18 -0
  7. package/dist/docs/assets/icons.svg +1 -0
  8. package/dist/docs/assets/main.js +60 -0
  9. package/dist/docs/assets/navigation.js +1 -0
  10. package/dist/docs/assets/search.js +1 -0
  11. package/dist/docs/assets/style.css +1640 -0
  12. package/dist/docs/classes/Model.html +4 -0
  13. package/dist/docs/enums/RelationshipType.html +3 -0
  14. package/dist/docs/functions/camel.html +2 -0
  15. package/dist/docs/functions/createJsonApiStore.html +1 -0
  16. package/dist/docs/hierarchy.html +1 -0
  17. package/dist/docs/index.html +11 -0
  18. package/dist/docs/interfaces/FetchOptions.html +5 -0
  19. package/dist/docs/interfaces/FetchParams.html +1 -0
  20. package/dist/docs/interfaces/JsonApiDocument.html +6 -0
  21. package/dist/docs/interfaces/JsonApiError.html +7 -0
  22. package/dist/docs/interfaces/JsonApiFetcher.html +7 -0
  23. package/dist/docs/interfaces/JsonApiLinkObject.html +8 -0
  24. package/dist/docs/interfaces/JsonApiLinks.html +8 -0
  25. package/dist/docs/interfaces/JsonApiMeta.html +8 -0
  26. package/dist/docs/interfaces/JsonApiRelationship.html +2 -0
  27. package/dist/docs/interfaces/JsonApiResource.html +5 -0
  28. package/dist/docs/interfaces/JsonApiResourceIdentifier.html +3 -0
  29. package/dist/docs/interfaces/JsonApiStore.html +14 -0
  30. package/dist/docs/interfaces/JsonApiStoreConfig.html +7 -0
  31. package/dist/docs/interfaces/ModelDefinition.html +7 -0
  32. package/dist/docs/interfaces/PageOption.html +3 -0
  33. package/dist/docs/interfaces/Relationship.html +4 -0
  34. package/dist/docs/modules.html +1 -0
  35. package/dist/docs/types/JsonApiLink.html +1 -0
  36. package/dist/docs/types/JsonApiStoreUseFunction.html +1 -0
  37. package/dist/lib.d.ts +193 -0
  38. package/dist/lib.js +155 -0
  39. package/dist/lib.js.map +1 -0
  40. package/package.json +44 -0
package/dist/lib.d.ts ADDED
@@ -0,0 +1,193 @@
1
+ /**
2
+ * Convert str from kebab-case to camelCase
3
+ */
4
+ export declare function camel(str: string): string;
5
+
6
+ export declare function createJsonApiStore(name: string, config: JsonApiStoreConfig, fetcher?: JsonApiFetcher): {
7
+ modelRegistry: Map<typeof Model, string>;
8
+ relsRegistry: Map<typeof Model, Record<string, Relationship>>;
9
+ findAll: <T extends typeof Model>(ctor: T, options?: FetchOptions, params?: FetchParams) => Promise<{
10
+ doc: JsonApiDocument;
11
+ records: InstanceType<T>[];
12
+ }>;
13
+ findRecord: <T extends typeof Model>(ctor: T, id: string, options?: FetchOptions, params?: FetchParams) => Promise<InstanceType<T>>;
14
+ findRelated: (record: Model, name: string, options?: FetchOptions, params?: FetchParams) => Promise<JsonApiDocument>;
15
+ saveRecord: (record: Model) => Promise<void>;
16
+ };
17
+
18
+ export declare interface FetchOptions {
19
+ fields?: Record<string, string[]>;
20
+ page?: PageOption;
21
+ include?: string[];
22
+ filter?: string;
23
+ }
24
+
25
+ export declare interface FetchParams {
26
+ [key: string]: string;
27
+ }
28
+
29
+ export declare interface JsonApiDocument {
30
+ links?: JsonApiLinks;
31
+ data?: JsonApiResource | JsonApiResource[];
32
+ errors?: JsonApiError[];
33
+ included?: JsonApiResource[];
34
+ meta?: JsonApiMeta;
35
+ }
36
+
37
+ export declare interface JsonApiError {
38
+ id: string;
39
+ status: string;
40
+ code?: string;
41
+ title: string;
42
+ detail?: string;
43
+ meta?: JsonApiMeta;
44
+ }
45
+
46
+ export declare interface JsonApiFetcher {
47
+ fetchDocument(type: string, id?: string, options?: FetchOptions, params?: FetchParams): Promise<JsonApiDocument>;
48
+ fetchOne(type: string, id: string, options?: FetchOptions, params?: FetchParams): Promise<JsonApiResource>;
49
+ fetchAll(type: string, options?: FetchOptions, params?: FetchParams): Promise<JsonApiResource[]>;
50
+ fetchHasMany(type: string, id: string, name: string, options?: FetchOptions, params?: FetchParams): Promise<JsonApiDocument>;
51
+ fetchBelongsTo(type: string, id: string, name: string, options?: FetchOptions, params?: FetchParams): Promise<JsonApiDocument>;
52
+ post(data: JsonApiResource): Promise<JsonApiDocument>;
53
+ }
54
+
55
+ export declare type JsonApiLink = null | string | JsonApiLinkObject;
56
+
57
+ export declare interface JsonApiLinkObject {
58
+ href: string;
59
+ rel?: string;
60
+ describedby?: JsonApiLink;
61
+ title?: string;
62
+ type?: string;
63
+ hreflang?: string | string[];
64
+ meta?: JsonApiMeta;
65
+ }
66
+
67
+ export declare interface JsonApiLinks {
68
+ self?: JsonApiLink;
69
+ related?: JsonApiLink;
70
+ describedby?: JsonApiLink;
71
+ first?: JsonApiLink;
72
+ last?: JsonApiLink;
73
+ prev?: JsonApiLink;
74
+ next?: JsonApiLink;
75
+ }
76
+
77
+ export declare interface JsonApiMeta {
78
+ totalPages?: number;
79
+ totalItems?: number;
80
+ currentPage?: number;
81
+ itemsPerPage?: number;
82
+ timestamp?: string | number;
83
+ version?: string;
84
+ copyright?: string;
85
+ [key: string]: unknown;
86
+ }
87
+
88
+ export declare interface JsonApiRelationship {
89
+ data: null | [] | JsonApiResourceIdentifier | JsonApiResourceIdentifier[];
90
+ }
91
+
92
+ export declare interface JsonApiResource {
93
+ id: string;
94
+ type: string;
95
+ attributes: Record<string, unknown>;
96
+ relationships?: Record<string, JsonApiRelationship>;
97
+ }
98
+
99
+ export declare interface JsonApiResourceIdentifier {
100
+ id: string;
101
+ type: string;
102
+ }
103
+
104
+ export declare interface JsonApiStore {
105
+ /**
106
+ * Models registered with this store
107
+ */
108
+ modelRegistry: Map<typeof Model, string>;
109
+ /**
110
+ * Relationships registered with this store
111
+ */
112
+ relRegistry: Map<typeof Model, Record<string, Relationship>>;
113
+ /* Excluded from this release type: createRecord */
114
+ /**
115
+ * Find all records of a given type
116
+ * @returns the JSON API document that was fetched and the records that were found
117
+ */
118
+ findAll<T extends typeof Model>(ctor: T, options?: FetchOptions, params?: FetchParams): Promise<{
119
+ doc: JsonApiDocument;
120
+ records: InstanceType<T>[];
121
+ }>;
122
+ /**
123
+ * Find a single record by id
124
+ * @returns the record that was found
125
+ */
126
+ findRecord<T extends typeof Model>(ctor: T, id: string, options?: FetchOptions, params?: FetchParams): Promise<InstanceType<T>>;
127
+ /**
128
+ * Find related records for a given record and relationship name
129
+ * @returns the JSON API document that was fetched
130
+ */
131
+ findRelated(record: Model, name: string, options?: FetchOptions, params?: FetchParams): Promise<JsonApiDocument>;
132
+ }
133
+
134
+ export declare interface JsonApiStoreConfig {
135
+ /**
136
+ * The URL for the JSON:API endpoint
137
+ */
138
+ endpoint: string;
139
+ /**
140
+ * Model definitions for the store
141
+ */
142
+ modelDefinitions: ModelDefinition[];
143
+ /**
144
+ * Whether to convert kebab-case names from JSON:API (older convention) to camelCase
145
+ */
146
+ kebabCase?: boolean;
147
+ }
148
+
149
+ export declare type JsonApiStoreUseFunction = () => JsonApiStore;
150
+
151
+ /**
152
+ * Base class for models
153
+ */
154
+ export declare class Model {
155
+ id: string;
156
+ constructor(id: string);
157
+ [key: string]: unknown;
158
+ }
159
+
160
+ export declare interface ModelDefinition {
161
+ /**
162
+ * The JSON:API type for the model
163
+ */
164
+ type: string;
165
+ /**
166
+ * The model constructor
167
+ */
168
+ ctor: typeof Model;
169
+ /**
170
+ * Relationships for the model
171
+ */
172
+ rels?: Record<string, Relationship>;
173
+ }
174
+
175
+ export declare interface PageOption {
176
+ size?: number;
177
+ number?: number;
178
+ }
179
+
180
+ /**
181
+ * Relationship definition
182
+ */
183
+ export declare interface Relationship {
184
+ ctor: typeof Model;
185
+ type: RelationshipType;
186
+ }
187
+
188
+ export declare enum RelationshipType {
189
+ HasMany = 0,
190
+ BelongsTo = 1
191
+ }
192
+
193
+ export { }
package/dist/lib.js ADDED
@@ -0,0 +1,155 @@
1
+ import b from "ky";
2
+ function O(...u) {
3
+ return new URL(u.join("/")).href;
4
+ }
5
+ class q {
6
+ constructor(e) {
7
+ this.endpoint = e;
8
+ }
9
+ createOptions(e = {}, a = {}, r = !1) {
10
+ const s = new URLSearchParams(), c = new Headers();
11
+ c.append("Accept", "application/vnd.api+json"), r && c.append("Content-Type", "application/vnd.api+json");
12
+ const p = { searchParams: s, headers: c };
13
+ if (e.fields)
14
+ for (const [w, m] of Object.entries(e.fields)) s.append(`fields[${w}]`, m.join(","));
15
+ e.page?.size && s.append("page[size]", e.page.size.toString()), e.page?.number && s.append("page[number]", e.page.number.toString()), e.include && s.append("include", e.include.join(",")), e.filter && s.append("filter", e.filter);
16
+ for (const [w, m] of Object.entries(a)) s.append(w, m);
17
+ return p;
18
+ }
19
+ async fetchDocument(e, a, r, s) {
20
+ const c = [this.endpoint, e];
21
+ a && c.push(a);
22
+ const p = O(...c);
23
+ return await b.get(p, this.createOptions(r, s)).json();
24
+ }
25
+ async fetchAll(e, a, r) {
26
+ const s = O(this.endpoint, e);
27
+ return (await b.get(s, this.createOptions(a, r)).json()).data;
28
+ }
29
+ async fetchOne(e, a, r, s) {
30
+ const c = O(this.endpoint, e, a);
31
+ return (await b.get(c, this.createOptions(r, s)).json()).data;
32
+ }
33
+ async fetchHasMany(e, a, r, s, c) {
34
+ const p = O(this.endpoint, e, a, r);
35
+ return await b.get(p, this.createOptions(s, c)).json();
36
+ }
37
+ async fetchBelongsTo(e, a, r, s, c) {
38
+ const p = O(this.endpoint, e, a, r);
39
+ return await b.get(p, this.createOptions(s, c)).json();
40
+ }
41
+ async post(e) {
42
+ const a = O(this.endpoint, e.type), r = this.createOptions({}, {}, !0), s = {
43
+ data: e
44
+ };
45
+ return r.json = s, await b.post(a, r).json();
46
+ }
47
+ }
48
+ function x(u) {
49
+ return u.replace(/[-][a-z\u00E0-\u00F6\u00F8-\u00FE]/g, (e) => e.slice(1).toUpperCase());
50
+ }
51
+ class L {
52
+ constructor(e) {
53
+ this.id = e, this.id = e;
54
+ }
55
+ }
56
+ var I = /* @__PURE__ */ ((u) => (u[u.HasMany = 0] = "HasMany", u[u.BelongsTo = 1] = "BelongsTo", u))(I || {});
57
+ function N(u, e, a) {
58
+ const r = a ?? new q(e.endpoint), s = /* @__PURE__ */ new Map(), c = /* @__PURE__ */ new Map(), p = /* @__PURE__ */ new Map();
59
+ for (const t of e.modelDefinitions) {
60
+ const n = t.ctor;
61
+ s.set(n, t.type), c.set(t.type, n), t.rels && p.set(n, t.rels);
62
+ }
63
+ function w(t) {
64
+ return e.kebabCase ? x(t) : t;
65
+ }
66
+ function m(t, n, i) {
67
+ j(t);
68
+ const l = new t(n);
69
+ if (i)
70
+ for (const [d, f] of Object.entries(i)) f !== void 0 && (l[w(d)] = f);
71
+ return l;
72
+ }
73
+ function j(t) {
74
+ const n = s.get(t);
75
+ if (!n) throw new Error(`Model ${t.name} not defined`);
76
+ return n;
77
+ }
78
+ function k(t) {
79
+ const n = c.get(t);
80
+ if (!n) throw new Error(`Model with name ${t} not defined`);
81
+ return n;
82
+ }
83
+ function A(t, n, i) {
84
+ function l(o) {
85
+ return m(
86
+ k(o.type),
87
+ o.id,
88
+ o.attributes
89
+ );
90
+ }
91
+ const d = /* @__PURE__ */ new Map();
92
+ if (i) for (const o of i) d.set(o.id, l(o));
93
+ const f = n.map((o) => m(t, o.id, o.attributes)), h = /* @__PURE__ */ new Map();
94
+ for (const o of f) h.set(o.id, o);
95
+ function g(o) {
96
+ const z = h.get(o.id) ?? d.get(o.id);
97
+ if (!z) throw new Error("Unexpected not found record");
98
+ const v = k(o.type);
99
+ if (o.relationships)
100
+ for (const [M, R] of Object.entries(o.relationships)) {
101
+ const E = p.get(v);
102
+ if (!E) continue;
103
+ const H = w(M), $ = E[H];
104
+ if (!$) throw new Error(`Relationship ${H} not defined`);
105
+ const B = j($.ctor), C = $.type === 0 ? R.data : [R.data], P = C.filter((y) => y && d.has(y.id) && y.type === B).map((y) => d.get(y.id)), T = C.filter((y) => y && h.has(y.id) && y.type === B).map((y) => h.get(y.id));
106
+ T.push(...P), z[H] = $.type === 0 ? T : T[0];
107
+ }
108
+ }
109
+ return i && (n.map(g), i.map(g)), f;
110
+ }
111
+ async function D(t, n, i) {
112
+ const l = j(t), d = await r.fetchDocument(l, void 0, n, i), f = d.data, h = A(t, f, d.included);
113
+ return { doc: d, records: h };
114
+ }
115
+ async function F(t, n, i, l) {
116
+ const d = j(t), f = await r.fetchDocument(d, n, i, l), h = f.data, o = A(t, [h], f.included)[0];
117
+ if (!o) throw new Error(`Record with id ${n} not found`);
118
+ return o;
119
+ }
120
+ async function S(t, n, i, l) {
121
+ const d = t.constructor, f = j(d), h = p.get(d);
122
+ if (!h) throw new Error(`Model ${d.name} has no relationships`);
123
+ const g = h[n];
124
+ if (!g) throw new Error(`Has many relationship ${n} not defined`);
125
+ if (g.type === 1) {
126
+ const M = await r.fetchBelongsTo(f, t.id, n, i, l), R = M.data, E = m(g.ctor, R.id, R.attributes);
127
+ return t[n] = E, M;
128
+ }
129
+ const o = await r.fetchHasMany(f, t.id, n, i, l), v = (g.type === 0 ? o.data : [o.data]).map((M) => m(g.ctor, M.id, M.attributes));
130
+ return t[n] = g.type === 0 ? v : v[0], o;
131
+ }
132
+ async function U(t) {
133
+ const n = j(t.constructor), i = {
134
+ id: t.id,
135
+ type: n,
136
+ attributes: t
137
+ };
138
+ await r.post(i);
139
+ }
140
+ return {
141
+ modelRegistry: s,
142
+ relsRegistry: p,
143
+ findAll: D,
144
+ findRecord: F,
145
+ findRelated: S,
146
+ saveRecord: U
147
+ };
148
+ }
149
+ export {
150
+ L as Model,
151
+ I as RelationshipType,
152
+ x as camel,
153
+ N as createJsonApiStore
154
+ };
155
+ //# sourceMappingURL=lib.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lib.js","sources":["../src/json-api-fetcher.ts","../src/util.ts","../src/json-api-store.ts"],"sourcesContent":["import ky, { type Options } from 'ky'\nimport type { JsonApiDocument, JsonApiResource } from './json-api'\n\nfunction resolvePath(...segments: string[]): string {\n return new URL(segments.join('/')).href\n}\n\nexport interface PageOption {\n size?: number\n number?: number\n}\n\nexport interface FetchOptions {\n fields?: Record<string, string[]>\n page?: PageOption\n include?: string[]\n filter?: string\n}\n\nexport interface FetchParams {\n [key: string]: string\n}\n\nexport interface JsonApiFetcher {\n fetchDocument(type: string, id?: string, options?: FetchOptions, params?: FetchParams): Promise<JsonApiDocument>\n fetchOne(type: string, id: string, options?: FetchOptions, params?: FetchParams): Promise<JsonApiResource>\n fetchAll(type: string, options?: FetchOptions, params?: FetchParams): Promise<JsonApiResource[]>\n fetchHasMany(\n type: string,\n id: string,\n name: string,\n options?: FetchOptions,\n params?: FetchParams\n ): Promise<JsonApiDocument>\n fetchBelongsTo(\n type: string,\n id: string,\n name: string,\n options?: FetchOptions,\n params?: FetchParams\n ): Promise<JsonApiDocument>\n post(data: JsonApiResource): Promise<JsonApiDocument>\n}\n\nexport class JsonApiFetcherImpl implements JsonApiFetcher {\n constructor(private endpoint: string) {}\n createOptions(options: FetchOptions = {}, params: FetchParams = {}, post = false): Options {\n const searchParams = new URLSearchParams()\n const headers = new Headers()\n headers.append('Accept', 'application/vnd.api+json')\n if (post) headers.append('Content-Type', 'application/vnd.api+json')\n //if (this.state) headers.append('Authorization', `Bearer ${this.state.value.token}`)\n const requestOptions = { searchParams, headers }\n if (options.fields)\n for (const [key, value] of Object.entries(options.fields)) searchParams.append(`fields[${key}]`, value.join(','))\n if (options.page?.size) searchParams.append('page[size]', options.page.size.toString())\n if (options.page?.number) searchParams.append('page[number]', options.page.number.toString())\n if (options.include) searchParams.append('include', options.include.join(','))\n if (options.filter) searchParams.append('filter', options.filter)\n for (const [key, value] of Object.entries(params)) searchParams.append(key, value)\n return requestOptions\n }\n async fetchDocument(type: string, id?: string, options?: FetchOptions, params?: FetchParams) {\n const segments = [this.endpoint, type]\n if (id) segments.push(id)\n const url = resolvePath(...segments)\n const doc = await ky.get(url, this.createOptions(options, params)).json<JsonApiDocument>()\n return doc\n }\n async fetchAll(type: string, options?: FetchOptions, params?: FetchParams) {\n const url = resolvePath(this.endpoint, type)\n const doc = await ky.get(url, this.createOptions(options, params)).json<JsonApiDocument>()\n const resources = doc.data as JsonApiResource[]\n return resources\n }\n async fetchOne(type: string, id: string, options?: FetchOptions, params?: FetchParams) {\n const url = resolvePath(this.endpoint, type, id)\n const doc = await ky.get(url, this.createOptions(options, params)).json<JsonApiDocument>()\n const resource = doc.data as JsonApiResource\n return resource\n }\n async fetchHasMany(type: string, id: string, name: string, options?: FetchOptions, params?: FetchParams) {\n const url = resolvePath(this.endpoint, type, id, name)\n const doc = await ky.get(url, this.createOptions(options, params)).json<JsonApiDocument>()\n return doc\n }\n async fetchBelongsTo(type: string, id: string, name: string, options?: FetchOptions, params?: FetchParams) {\n const url = resolvePath(this.endpoint, type, id, name)\n const doc = await ky.get(url, this.createOptions(options, params)).json<JsonApiDocument>()\n return doc\n }\n async post(resource: JsonApiResource) {\n const url = resolvePath(this.endpoint, resource.type)\n const requestOptions = this.createOptions({}, {}, true)\n const body: JsonApiDocument = {\n data: resource,\n }\n requestOptions.json = body\n const doc = await ky.post(url, requestOptions).json<JsonApiDocument>()\n return doc\n }\n}\n","/**\n * Convert str from kebab-case to camelCase\n */\nexport function camel(str: string) {\n return str.replace(/[-][a-z\\u00E0-\\u00F6\\u00F8-\\u00FE]/g, (match) => match.slice(1).toUpperCase())\n}\n","import type { JsonApiDocument, JsonApiResource, JsonApiResourceIdentifier } from './json-api'\nimport { type FetchOptions, type FetchParams, type JsonApiFetcher, JsonApiFetcherImpl } from './json-api-fetcher'\nimport { camel } from './util'\n\n/**\n * Base class for models\n */\nexport class Model {\n constructor(public id: string) {\n this.id = id\n }\n [key: string]: unknown\n}\n\nexport interface ModelDefinition {\n /**\n * The JSON:API type for the model\n */\n type: string\n /**\n * The model constructor\n */\n ctor: typeof Model\n /**\n * Relationships for the model\n */\n rels?: Record<string, Relationship>\n}\n\nexport interface JsonApiStoreConfig {\n /**\n * The URL for the JSON:API endpoint\n */\n endpoint: string\n /**\n * Model definitions for the store\n */\n modelDefinitions: ModelDefinition[]\n /**\n * Whether to convert kebab-case names from JSON:API (older convention) to camelCase\n */\n kebabCase?: boolean\n}\n\nexport enum RelationshipType {\n HasMany = 0,\n BelongsTo = 1,\n}\n\n/**\n * Relationship definition\n */\nexport interface Relationship {\n ctor: typeof Model\n type: RelationshipType\n}\n\nexport interface JsonApiStore {\n /**\n * Models registered with this store\n */\n modelRegistry: Map<typeof Model, string>\n /**\n * Relationships registered with this store\n */\n relRegistry: Map<typeof Model, Record<string, Relationship>>\n /**\n * @internal\n */\n createRecord<T extends typeof Model>(ctor: T, properties: Partial<InstanceType<T>> & { id?: string }): InstanceType<T>\n /**\n * Find all records of a given type\n * @returns the JSON API document that was fetched and the records that were found\n */\n findAll<T extends typeof Model>(\n ctor: T,\n options?: FetchOptions,\n params?: FetchParams\n ): Promise<{ doc: JsonApiDocument; records: InstanceType<T>[] }>\n /**\n * Find a single record by id\n * @returns the record that was found\n */\n findRecord<T extends typeof Model>(\n ctor: T,\n id: string,\n options?: FetchOptions,\n params?: FetchParams\n ): Promise<InstanceType<T>>\n /**\n * Find related records for a given record and relationship name\n * @returns the JSON API document that was fetched\n */\n findRelated(record: Model, name: string, options?: FetchOptions, params?: FetchParams): Promise<JsonApiDocument>\n}\n\nexport type JsonApiStoreUseFunction = () => JsonApiStore\n\nexport function createJsonApiStore(name: string, config: JsonApiStoreConfig, fetcher?: JsonApiFetcher) {\n const _fetcher = fetcher ?? new JsonApiFetcherImpl(config.endpoint)\n\n const modelRegistry = new Map<typeof Model, string>()\n const modelsByType = new Map<string, typeof Model>()\n const relsRegistry = new Map<typeof Model, Record<string, Relationship>>()\n\n for (const modelDef of config.modelDefinitions) {\n const ctor = modelDef.ctor\n modelRegistry.set(ctor, modelDef.type)\n modelsByType.set(modelDef.type, ctor)\n if (modelDef.rels) relsRegistry.set(ctor, modelDef.rels)\n }\n\n function normalize(str: string) {\n return config.kebabCase ? camel(str) : str\n }\n\n function internalCreateRecord<T extends typeof Model>(ctor: T, id: string, properties?: Partial<InstanceType<T>>) {\n const type = getModelType(ctor)\n const record = new ctor(id)\n if (properties)\n for (const [key, value] of Object.entries(properties)) if (value !== undefined) record[normalize(key)] = value\n return record as InstanceType<T>\n }\n\n function getModelType(ctor: typeof Model) {\n const type = modelRegistry.get(ctor)\n if (!type) throw new Error(`Model ${ctor.name} not defined`)\n return type\n }\n\n function getModel(type: string) {\n const ctor = modelsByType.get(type)\n if (!ctor) throw new Error(`Model with name ${type} not defined`)\n return ctor\n }\n\n function resourcesToRecords<T extends typeof Model>(\n ctor: T,\n resources: JsonApiResource[],\n included?: JsonApiResource[]\n ) {\n function createRecord<T extends typeof Model>(resource: JsonApiResource) {\n return internalCreateRecord<T>(\n getModel(resource.type) as T,\n resource.id,\n resource.attributes as Partial<InstanceType<T>>\n )\n }\n // create records for included resources\n const includedMap = new Map<string, InstanceType<typeof Model>>()\n if (included) for (const resource of included) includedMap.set(resource.id, createRecord(resource))\n // create records for main resources\n const records = resources.map((r) => internalCreateRecord<T>(ctor, r.id, r.attributes as Partial<InstanceType<T>>))\n const recordsMap = new Map<string, InstanceType<typeof Model>>()\n for (const r of records) recordsMap.set(r.id, r)\n // populate relationships\n function populateRelationships(resource: JsonApiResource) {\n const record = recordsMap.get(resource.id) ?? includedMap.get(resource.id)\n if (!record) throw new Error('Unexpected not found record')\n const recordCtor = getModel(resource.type)\n if (!resource.relationships) return\n for (const [name, reldoc] of Object.entries(resource.relationships)) {\n const rels = relsRegistry.get(recordCtor)\n // NOTE: if relationship is not defined but exists in data, it is ignored\n if (!rels) continue\n const normalizedName = normalize(name)\n const rel = rels[normalizedName]\n if (!rel) throw new Error(`Relationship ${normalizedName} not defined`)\n const relType = getModelType(rel.ctor)\n const rids =\n rel.type === RelationshipType.HasMany\n ? (reldoc.data as JsonApiResourceIdentifier[])\n : [reldoc.data as JsonApiResourceIdentifier]\n const relIncludedRecords = rids\n .filter((d) => d && includedMap.has(d.id) && d.type === relType)\n .map((d) => includedMap.get(d.id))\n const relRecords = rids\n .filter((d) => d && recordsMap.has(d.id) && d.type === relType)\n .map((d) => recordsMap.get(d.id))\n relRecords.push(...relIncludedRecords)\n record[normalizedName] = rel.type === RelationshipType.HasMany ? relRecords : relRecords[0]\n }\n }\n if (included) {\n resources.map(populateRelationships)\n included.map(populateRelationships)\n }\n return records as InstanceType<T>[]\n }\n\n async function findAll<T extends typeof Model>(ctor: T, options?: FetchOptions, params?: FetchParams) {\n const type = getModelType(ctor)\n const doc = await _fetcher.fetchDocument(type, undefined, options, params)\n const resources = doc.data as JsonApiResource[]\n const records = resourcesToRecords(ctor, resources, doc.included)\n return { doc, records }\n }\n\n async function findRecord<T extends typeof Model>(ctor: T, id: string, options?: FetchOptions, params?: FetchParams) {\n const type = getModelType(ctor)\n const doc = await _fetcher.fetchDocument(type, id, options, params)\n const resource = doc.data as JsonApiResource\n const records = resourcesToRecords(ctor, [resource], doc.included)\n const record = records[0]\n if (!record) throw new Error(`Record with id ${id} not found`)\n return record as InstanceType<T>\n }\n\n async function findRelated(record: Model, name: string, options?: FetchOptions, params?: FetchParams) {\n const ctor = record.constructor as typeof Model\n const type = getModelType(ctor)\n const rels = relsRegistry.get(ctor)\n if (!rels) throw new Error(`Model ${ctor.name} has no relationships`)\n const rel = rels[name]\n if (!rel) throw new Error(`Has many relationship ${name} not defined`)\n if (rel.type === RelationshipType.BelongsTo) {\n const doc = await _fetcher.fetchBelongsTo(type, record.id, name, options, params)\n const related = doc.data as JsonApiResource\n const relatedRecord = internalCreateRecord(rel.ctor, related.id, related.attributes)\n record[name] = relatedRecord\n return doc\n }\n const doc = await _fetcher.fetchHasMany(type, record.id, name, options, params)\n const related =\n rel.type === RelationshipType.HasMany ? (doc.data as JsonApiResource[]) : [doc.data as JsonApiResource]\n const relatedRecords = related.map((r) => internalCreateRecord(rel.ctor, r.id, r.attributes))\n record[name] = rel.type === RelationshipType.HasMany ? relatedRecords : relatedRecords[0]\n return doc\n }\n\n async function saveRecord(record: Model) {\n const type = getModelType(record.constructor as typeof Model)\n const resource: JsonApiResource = {\n id: record.id,\n type,\n attributes: record,\n }\n await _fetcher.post(resource)\n }\n\n return {\n modelRegistry,\n relsRegistry,\n findAll,\n findRecord,\n findRelated,\n saveRecord,\n }\n}\n"],"names":["resolvePath","segments","JsonApiFetcherImpl","endpoint","options","params","post","searchParams","headers","requestOptions","key","value","type","id","url","ky","name","resource","body","camel","str","match","Model","RelationshipType","createJsonApiStore","config","fetcher","_fetcher","modelRegistry","modelsByType","relsRegistry","modelDef","ctor","normalize","internalCreateRecord","properties","getModelType","record","getModel","resourcesToRecords","resources","included","createRecord","includedMap","records","r","recordsMap","populateRelationships","recordCtor","reldoc","rels","normalizedName","rel","relType","rids","relIncludedRecords","d","relRecords","findAll","doc","findRecord","findRelated","related","relatedRecord","relatedRecords","saveRecord"],"mappings":";AAGA,SAASA,KAAeC,GAA4B;AAClD,SAAO,IAAI,IAAIA,EAAS,KAAK,GAAG,CAAC,EAAE;AACrC;AAuCO,MAAMC,EAA6C;AAAA,EACxD,YAAoBC,GAAkB;AAAlB,SAAA,WAAAA;AAAA,EAAA;AAAA,EACpB,cAAcC,IAAwB,CAAC,GAAGC,IAAsB,CAAC,GAAGC,IAAO,IAAgB;AACnF,UAAAC,IAAe,IAAI,gBAAgB,GACnCC,IAAU,IAAI,QAAQ;AACpB,IAAAA,EAAA,OAAO,UAAU,0BAA0B,GAC/CF,KAAME,EAAQ,OAAO,gBAAgB,0BAA0B;AAE7D,UAAAC,IAAiB,EAAE,cAAAF,GAAc,SAAAC,EAAQ;AAC/C,QAAIJ,EAAQ;AACV,iBAAW,CAACM,GAAKC,CAAK,KAAK,OAAO,QAAQP,EAAQ,MAAM,EAAG,CAAAG,EAAa,OAAO,UAAUG,CAAG,KAAKC,EAAM,KAAK,GAAG,CAAC;AAC9G,IAAAP,EAAQ,MAAM,QAA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BO,EAAI,OAA6B,CAACA,EAAI,IAAuB,GACzE,IAAI,CAACd,MAAMX,EAAqBkB,EAAI,MAAMP,EAAE,IAAIA,EAAE,UAAU,CAAC;AAC5F,WAAAR,EAAOrB,CAAI,IAAIoC,EAAI,SAAS,IAA2BY,IAAiBA,EAAe,CAAC,GACjFL;AAAA,EAAA;AAGT,iBAAeM,EAAW5B,GAAe;AACjC,UAAAzB,IAAOwB,EAAaC,EAAO,WAA2B,GACtDpB,IAA4B;AAAA,MAChC,IAAIoB,EAAO;AAAA,MACX,MAAAzB;AAAA,MACA,YAAYyB;AAAA,IACd;AACM,UAAAV,EAAS,KAAKV,CAAQ;AAAA,EAAA;AAGvB,SAAA;AAAA,IACL,eAAAW;AAAA,IACA,cAAAE;AAAA,IACA,SAAA4B;AAAA,IACA,YAAAE;AAAA,IACA,aAAAC;AAAA,IACA,YAAAI;AAAA,EACF;AACF;"}
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@bjornharrtell/json-api",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "main": "./dist/lib.js",
6
+ "module": "./dist/lib.js",
7
+ "types": "./dist/lib.d.ts",
8
+ "exports": {
9
+ ".": "./dist/lib.js",
10
+ "./*": "./src/*"
11
+ },
12
+ "files": [
13
+ "README.md",
14
+ "dist"
15
+ ],
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/bjornharrtell/json-api.git"
19
+ },
20
+ "scripts": {
21
+ "dev": "vite",
22
+ "test": "vitest",
23
+ "build": "vite build",
24
+ "preview": "vite preview",
25
+ "type-check": "vue-tsc --build",
26
+ "typedoc": "typedoc"
27
+ },
28
+ "dependencies": {
29
+ "ky": "^1.7.5"
30
+ },
31
+ "devDependencies": {
32
+ "@biomejs/biome": "1.9.4",
33
+ "@tsconfig/node22": "^22.0.1",
34
+ "@types/jsdom": "^21.1.7",
35
+ "@types/node": "^22.13.13",
36
+ "@vue/test-utils": "^2.4.6",
37
+ "@vue/tsconfig": "^0.7.0",
38
+ "typedoc": "^0.28.1",
39
+ "typescript": "~5.8.2",
40
+ "vite": "^6.2.3",
41
+ "vite-plugin-dts": "^4.5.3",
42
+ "vitest": "^3.0.9"
43
+ }
44
+ }