@bjornharrtell/json-api 5.0.2 → 5.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.
- package/dist/docs/assets/icons.js +1 -1
- package/dist/docs/assets/icons.svg +1 -1
- package/dist/docs/assets/search.js +1 -1
- package/dist/docs/assets/style.css +3 -3
- package/dist/docs/enums/RelationshipType.html +2 -2
- package/dist/docs/functions/camel.html +1 -1
- package/dist/docs/functions/useJsonApi.html +1 -1
- package/dist/docs/index.html +4 -2
- package/dist/docs/interfaces/AtomicOperation.html +2 -2
- package/dist/docs/interfaces/BaseEntity.html +2 -2
- package/dist/docs/interfaces/FetchOptions.html +2 -2
- package/dist/docs/interfaces/FetchParams.html +1 -1
- package/dist/docs/interfaces/JsonApiAtomicDocument.html +2 -2
- package/dist/docs/interfaces/JsonApiAtomicOperation.html +3 -2
- package/dist/docs/interfaces/JsonApiAtomicResult.html +2 -2
- package/dist/docs/interfaces/JsonApiConfig.html +4 -4
- package/dist/docs/interfaces/JsonApiDocument.html +2 -2
- package/dist/docs/interfaces/JsonApiError.html +2 -2
- package/dist/docs/interfaces/JsonApiLinkObject.html +2 -2
- package/dist/docs/interfaces/JsonApiLinks.html +2 -2
- package/dist/docs/interfaces/JsonApiMeta.html +2 -2
- package/dist/docs/interfaces/JsonApiRelationship.html +2 -2
- package/dist/docs/interfaces/JsonApiResource.html +2 -2
- package/dist/docs/interfaces/JsonApiResourceIdentifier.html +2 -2
- package/dist/docs/interfaces/ModelDefinition.html +3 -3
- package/dist/docs/interfaces/PageOption.html +2 -2
- package/dist/docs/interfaces/Relationship.html +3 -3
- package/dist/docs/types/JsonApi.html +1 -1
- package/dist/docs/types/JsonApiFetcher.html +1 -1
- package/dist/docs/types/JsonApiLink.html +1 -1
- package/dist/lib.d.ts +8 -3
- package/dist/lib.js +187 -182
- package/dist/lib.js.map +1 -1
- package/package.json +6 -6
package/dist/lib.js
CHANGED
|
@@ -1,220 +1,225 @@
|
|
|
1
|
-
function
|
|
2
|
-
return new URL(
|
|
1
|
+
function O(...i) {
|
|
2
|
+
return new URL(i.join("/")).href;
|
|
3
3
|
}
|
|
4
|
-
async function
|
|
5
|
-
const { headers:
|
|
6
|
-
method:
|
|
7
|
-
headers:
|
|
8
|
-
signal:
|
|
9
|
-
body:
|
|
4
|
+
async function T(i, t) {
|
|
5
|
+
const { headers: n, searchParams: p, method: s, signal: f, body: d } = t, w = p ? `?${p}` : "", g = i.replace(/(?:\?.*?)?(?=#|$)/, w), b = await fetch(g, {
|
|
6
|
+
method: s,
|
|
7
|
+
headers: n,
|
|
8
|
+
signal: f,
|
|
9
|
+
body: d
|
|
10
10
|
});
|
|
11
|
-
if (!
|
|
12
|
-
return await
|
|
11
|
+
if (!b.ok) throw new Error(`HTTP error! status: ${b.status} ${b.statusText}`);
|
|
12
|
+
return await b.json();
|
|
13
13
|
}
|
|
14
|
-
async function
|
|
15
|
-
const { signal:
|
|
16
|
-
|
|
17
|
-
const
|
|
18
|
-
method:
|
|
19
|
-
headers:
|
|
20
|
-
signal:
|
|
21
|
-
body:
|
|
14
|
+
async function S(i, t) {
|
|
15
|
+
const { signal: n, body: p } = t, s = "POST", f = new Headers(t.headers ?? {});
|
|
16
|
+
f.append("Accept", 'application/vnd.api+json; ext="https://jsonapi.org/ext/atomic"'), f.append("Content-Type", 'application/vnd.api+json; ext="https://jsonapi.org/ext/atomic"');
|
|
17
|
+
const d = await fetch(i, {
|
|
18
|
+
method: s,
|
|
19
|
+
headers: f,
|
|
20
|
+
signal: n,
|
|
21
|
+
body: p
|
|
22
22
|
});
|
|
23
|
-
if (!
|
|
24
|
-
return
|
|
23
|
+
if (!d.ok) throw new Error(`HTTP error! status: ${d.status} ${d.statusText}`);
|
|
24
|
+
return d.status === 204 ? void 0 : await d.json();
|
|
25
25
|
}
|
|
26
|
-
class
|
|
27
|
-
constructor(
|
|
28
|
-
this.endpoint =
|
|
29
|
-
}
|
|
30
|
-
createOptions(
|
|
31
|
-
const
|
|
32
|
-
|
|
33
|
-
const
|
|
34
|
-
if (
|
|
35
|
-
for (const [
|
|
36
|
-
|
|
37
|
-
for (const [
|
|
38
|
-
return
|
|
39
|
-
}
|
|
40
|
-
async fetchDocument(
|
|
41
|
-
const
|
|
42
|
-
|
|
43
|
-
const
|
|
44
|
-
return await
|
|
45
|
-
}
|
|
46
|
-
async fetchAll(
|
|
47
|
-
const
|
|
48
|
-
return (await
|
|
49
|
-
}
|
|
50
|
-
async fetchOne(
|
|
51
|
-
const
|
|
52
|
-
return (await
|
|
53
|
-
}
|
|
54
|
-
async fetchHasMany(
|
|
55
|
-
const
|
|
56
|
-
return await
|
|
57
|
-
}
|
|
58
|
-
async fetchBelongsTo(
|
|
59
|
-
const
|
|
60
|
-
return await
|
|
61
|
-
}
|
|
62
|
-
async post(
|
|
63
|
-
const
|
|
64
|
-
data:
|
|
65
|
-
}),
|
|
66
|
-
return
|
|
67
|
-
}
|
|
68
|
-
async postAtomic(
|
|
69
|
-
const
|
|
70
|
-
return
|
|
26
|
+
class B {
|
|
27
|
+
constructor(t) {
|
|
28
|
+
this.endpoint = t;
|
|
29
|
+
}
|
|
30
|
+
createOptions(t = {}, n = {}, p) {
|
|
31
|
+
const s = new URLSearchParams(), f = new Headers(t.headers ?? {});
|
|
32
|
+
f.append("Accept", "application/vnd.api+json");
|
|
33
|
+
const d = { searchParams: s, headers: f, body: p };
|
|
34
|
+
if (t.fields)
|
|
35
|
+
for (const [w, g] of Object.entries(t.fields)) s.append(`fields[${w}]`, g.join(","));
|
|
36
|
+
t.page?.size && s.append("page[size]", t.page.size.toString()), t.page?.number && s.append("page[number]", t.page.number.toString()), t.include && s.append("include", t.include.join(",")), t.filter && s.append("filter", t.filter);
|
|
37
|
+
for (const [w, g] of Object.entries(n)) s.append(w, g);
|
|
38
|
+
return d;
|
|
39
|
+
}
|
|
40
|
+
async fetchDocument(t, n, p, s) {
|
|
41
|
+
const f = [this.endpoint, t];
|
|
42
|
+
n && f.push(n);
|
|
43
|
+
const d = O(...f);
|
|
44
|
+
return await T(d, this.createOptions(p, s));
|
|
45
|
+
}
|
|
46
|
+
async fetchAll(t, n, p) {
|
|
47
|
+
const s = O(this.endpoint, t);
|
|
48
|
+
return (await T(s, this.createOptions(n, p))).data;
|
|
49
|
+
}
|
|
50
|
+
async fetchOne(t, n, p, s) {
|
|
51
|
+
const f = O(this.endpoint, t, n);
|
|
52
|
+
return (await T(f, this.createOptions(p, s))).data;
|
|
53
|
+
}
|
|
54
|
+
async fetchHasMany(t, n, p, s, f) {
|
|
55
|
+
const d = O(this.endpoint, t, n, p);
|
|
56
|
+
return await T(d, this.createOptions(s, f));
|
|
57
|
+
}
|
|
58
|
+
async fetchBelongsTo(t, n, p, s, f) {
|
|
59
|
+
const d = O(this.endpoint, t, n, p);
|
|
60
|
+
return await T(d, this.createOptions(s, f));
|
|
61
|
+
}
|
|
62
|
+
async post(t, n) {
|
|
63
|
+
const p = O(this.endpoint, t.type), f = JSON.stringify({
|
|
64
|
+
data: t
|
|
65
|
+
}), d = this.createOptions(n, {}, f);
|
|
66
|
+
return d.method = "POST", d.headers.set("Content-Type", "application/vnd.api+json"), await T(p, d);
|
|
67
|
+
}
|
|
68
|
+
async postAtomic(t, n = {}) {
|
|
69
|
+
const p = new URL([this.endpoint, "operations"].join("/")).href;
|
|
70
|
+
return n.body = JSON.stringify(t), await S(p, n);
|
|
71
71
|
}
|
|
72
72
|
}
|
|
73
|
-
function
|
|
74
|
-
return
|
|
73
|
+
function C(i) {
|
|
74
|
+
return i.replace(/[-][a-z\u00E0-\u00F6\u00F8-\u00FE]/g, (t) => t.slice(1).toUpperCase());
|
|
75
|
+
}
|
|
76
|
+
var F = /* @__PURE__ */ ((i) => (i[i.HasMany = 0] = "HasMany", i[i.BelongsTo = 1] = "BelongsTo", i))(F || {});
|
|
77
|
+
function E(i, t, n) {
|
|
78
|
+
i[t] = n;
|
|
75
79
|
}
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
80
|
+
function A(i) {
|
|
81
|
+
const t = { type: i.type };
|
|
82
|
+
return i.lid ? t.lid = i.lid : i.id && (t.id = i.id), t;
|
|
79
83
|
}
|
|
80
|
-
function
|
|
81
|
-
const
|
|
82
|
-
for (const e of
|
|
83
|
-
|
|
84
|
-
function
|
|
85
|
-
return
|
|
86
|
-
}
|
|
87
|
-
function
|
|
88
|
-
const o =
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
if (l.relationshipType === 0) {
|
|
99
|
-
const t = c;
|
|
100
|
-
f.relationships[a] = {
|
|
101
|
-
data: t.map(i)
|
|
84
|
+
function L(i, t) {
|
|
85
|
+
const n = t ?? new B(i.endpoint), p = /* @__PURE__ */ new Map(), s = /* @__PURE__ */ new Map();
|
|
86
|
+
for (const e of i.modelDefinitions)
|
|
87
|
+
p.set(e.type, e), e.relationships && s.set(e.type, e.relationships);
|
|
88
|
+
function f(e) {
|
|
89
|
+
return i.kebabCase ? C(e) : e;
|
|
90
|
+
}
|
|
91
|
+
function d(e) {
|
|
92
|
+
const o = s.get(e.type), l = A(e);
|
|
93
|
+
l.attributes = {}, o && (l.relationships = {});
|
|
94
|
+
for (const [r, c] of Object.entries(e))
|
|
95
|
+
if (!(r === "id" || r === "lid" || r === "type" || c === void 0))
|
|
96
|
+
if (o && r in o && l.relationships) {
|
|
97
|
+
const y = o[r];
|
|
98
|
+
if (y.relationshipType === 0) {
|
|
99
|
+
const u = c;
|
|
100
|
+
l.relationships[r] = {
|
|
101
|
+
data: u.map(A)
|
|
102
102
|
};
|
|
103
|
-
} else if (
|
|
104
|
-
const
|
|
105
|
-
|
|
106
|
-
data:
|
|
103
|
+
} else if (y.relationshipType === 1) {
|
|
104
|
+
const u = c;
|
|
105
|
+
l.relationships[r] = {
|
|
106
|
+
data: A(u)
|
|
107
107
|
};
|
|
108
108
|
} else
|
|
109
|
-
throw new Error(`Unknown relationship type for ${
|
|
109
|
+
throw new Error(`Unknown relationship type for ${r}`);
|
|
110
110
|
} else
|
|
111
|
-
|
|
112
|
-
return
|
|
111
|
+
l.attributes[r] = c;
|
|
112
|
+
return l;
|
|
113
113
|
}
|
|
114
114
|
function w(e, o) {
|
|
115
|
-
if (!
|
|
116
|
-
const
|
|
117
|
-
if (
|
|
118
|
-
const
|
|
119
|
-
for (const [
|
|
120
|
-
|
|
121
|
-
return
|
|
115
|
+
if (!p.get(e)) throw new Error(`Model type ${e} not defined`);
|
|
116
|
+
const r = o.id ?? crypto.randomUUID(), c = { id: r, type: e, ...o };
|
|
117
|
+
if (i.kebabCase) {
|
|
118
|
+
const y = { id: r, type: e };
|
|
119
|
+
for (const [u, m] of Object.entries(o))
|
|
120
|
+
u !== "id" && m !== void 0 && (y[f(u)] = m);
|
|
121
|
+
return y;
|
|
122
122
|
}
|
|
123
123
|
return c;
|
|
124
124
|
}
|
|
125
|
-
function
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
(
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
)
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
if (!
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
125
|
+
function g(e, o) {
|
|
126
|
+
function l(a) {
|
|
127
|
+
return w(a.type, {
|
|
128
|
+
id: a.id,
|
|
129
|
+
...a.attributes
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
function r(a, h) {
|
|
133
|
+
a.has(h.type) || a.set(h.type, /* @__PURE__ */ new Map()), a.get(h.type)?.set(h.id, h);
|
|
134
|
+
}
|
|
135
|
+
function c(a, h) {
|
|
136
|
+
if (h.id === void 0) throw new Error("Resource identifier must have an id");
|
|
137
|
+
return a.has(h.type) || a.set(h.type, /* @__PURE__ */ new Map()), a.get(h.type)?.get(h.id);
|
|
138
|
+
}
|
|
139
|
+
const y = /* @__PURE__ */ new Map();
|
|
140
|
+
if (o) for (const a of o) r(y, l(a));
|
|
141
|
+
const u = e.map(l), m = /* @__PURE__ */ new Map();
|
|
142
|
+
for (const a of u) r(m, a);
|
|
143
|
+
function M(a) {
|
|
144
|
+
const h = c(m, a) ?? c(y, a);
|
|
145
|
+
if (!h) throw new Error("Unexpected not found record");
|
|
146
|
+
if (!a.relationships) return;
|
|
147
|
+
const R = s.get(a.type);
|
|
148
|
+
if (R)
|
|
149
|
+
for (const [D, $] of Object.entries(a.relationships)) {
|
|
150
|
+
const x = f(D), v = R[x];
|
|
151
|
+
if (!v || !$.data) continue;
|
|
152
|
+
const z = (v.relationshipType === 0 ? $.data : [$.data]).filter((j) => j && j.type === v.type).map((j) => c(y, j) || c(m, j)).filter(Boolean);
|
|
153
|
+
E(
|
|
154
|
+
h,
|
|
155
|
+
x,
|
|
156
|
+
v.relationshipType === 0 ? z : z[0]
|
|
156
157
|
);
|
|
157
158
|
}
|
|
158
159
|
}
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
return
|
|
164
|
-
}
|
|
165
|
-
async function
|
|
166
|
-
const
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
160
|
+
if (o) {
|
|
161
|
+
for (const a of e) M(a);
|
|
162
|
+
for (const a of o) M(a);
|
|
163
|
+
}
|
|
164
|
+
return u;
|
|
165
|
+
}
|
|
166
|
+
async function b(e, o, l) {
|
|
167
|
+
const r = await n.fetchDocument(e, void 0, o, l), c = r.data, y = g(c, r.included);
|
|
168
|
+
return { doc: r, records: y };
|
|
169
|
+
}
|
|
170
|
+
async function k(e, o, l, r) {
|
|
171
|
+
const c = await n.fetchDocument(e, o, l, r), y = c.data, m = g([y], c.included)[0];
|
|
172
|
+
if (!m) throw new Error(`Record with id ${o} not found`);
|
|
173
|
+
return m;
|
|
174
|
+
}
|
|
175
|
+
async function P(e, o, l, r) {
|
|
176
|
+
const c = e.type, y = s.get(c);
|
|
177
|
+
if (!y) throw new Error(`Model ${c} has no relationships`);
|
|
178
|
+
const u = y[o];
|
|
179
|
+
if (!u) throw new Error(`Relationship ${o} not defined`);
|
|
180
|
+
if (u.relationshipType === 1) {
|
|
181
|
+
const h = await n.fetchBelongsTo(c, e.id, o, l, r), R = h.data, D = w(u.type, {
|
|
182
|
+
id: R.id,
|
|
183
|
+
...R.attributes
|
|
179
184
|
});
|
|
180
|
-
return
|
|
185
|
+
return E(e, o, D), h;
|
|
181
186
|
}
|
|
182
|
-
const
|
|
183
|
-
(
|
|
184
|
-
id:
|
|
185
|
-
...
|
|
187
|
+
const m = await n.fetchHasMany(c, e.id, o, l, r), a = (u.relationshipType === 0 ? m.data : [m.data]).map(
|
|
188
|
+
(h) => w(u.type, {
|
|
189
|
+
id: h.id,
|
|
190
|
+
...h.attributes
|
|
186
191
|
})
|
|
187
192
|
);
|
|
188
|
-
return
|
|
193
|
+
return E(
|
|
189
194
|
e,
|
|
190
195
|
o,
|
|
191
|
-
|
|
192
|
-
),
|
|
196
|
+
u.relationshipType === 0 ? a : a[0]
|
|
197
|
+
), m;
|
|
193
198
|
}
|
|
194
|
-
async function
|
|
195
|
-
const
|
|
196
|
-
return
|
|
199
|
+
async function U(e, o) {
|
|
200
|
+
const l = d(e), r = await n.post(l, o);
|
|
201
|
+
return g([r.data])[0];
|
|
197
202
|
}
|
|
198
|
-
async function
|
|
199
|
-
const
|
|
200
|
-
"atomic:operations": e.map((
|
|
201
|
-
}, c = await
|
|
203
|
+
async function H(e, o) {
|
|
204
|
+
const r = {
|
|
205
|
+
"atomic:operations": e.map((u) => ({ op: u.op, data: d(u.data) }))
|
|
206
|
+
}, c = await n.postAtomic(r, o);
|
|
202
207
|
if (!c) return;
|
|
203
|
-
const
|
|
204
|
-
return { doc: c, records:
|
|
208
|
+
const y = c["atomic:results"] ? g(c["atomic:results"].map((u) => u.data)) : [];
|
|
209
|
+
return { doc: c, records: y };
|
|
205
210
|
}
|
|
206
211
|
return {
|
|
207
|
-
findAll:
|
|
208
|
-
findRecord:
|
|
209
|
-
findRelated:
|
|
212
|
+
findAll: b,
|
|
213
|
+
findRecord: k,
|
|
214
|
+
findRelated: P,
|
|
210
215
|
createRecord: w,
|
|
211
|
-
saveRecord:
|
|
212
|
-
saveAtomic:
|
|
216
|
+
saveRecord: U,
|
|
217
|
+
saveAtomic: H
|
|
213
218
|
};
|
|
214
219
|
}
|
|
215
220
|
export {
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
221
|
+
F as RelationshipType,
|
|
222
|
+
C as camel,
|
|
223
|
+
L as useJsonApi
|
|
219
224
|
};
|
|
220
225
|
//# sourceMappingURL=lib.js.map
|
package/dist/lib.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lib.js","sources":["../src/json-api-fetcher.ts","../src/util.ts","../src/json-api.ts"],"sourcesContent":["import type { JsonApiAtomicDocument, JsonApiDocument, JsonApiResource } from './json-api.ts'\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 headers?: HeadersInit\n body?: BodyInit\n signal?: AbortSignal\n}\n\nexport interface FetchParams {\n [key: string]: string\n}\n\nexport interface Options {\n searchParams?: URLSearchParams\n headers: Headers\n method?: string\n body?: BodyInit\n signal?: AbortSignal\n}\n\nasync function req(url: string, options: Options) {\n const { headers, searchParams, method, signal, body } = options\n const textSearchParams = searchParams ? `?${searchParams}` : ''\n const finalUrl = url.replace(/(?:\\?.*?)?(?=#|$)/, textSearchParams)\n const response = await fetch(finalUrl, {\n method,\n headers,\n signal,\n body,\n })\n if (!response.ok) throw new Error(`HTTP error! status: ${response.status} ${response.statusText}`)\n const data = (await response.json()) as JsonApiDocument\n return data\n}\n\nasync function postAtomic(url: string, options: FetchOptions) {\n const { signal, body } = options\n const method = 'POST'\n const headers = new Headers(options.headers ?? {})\n headers.append('Accept', 'application/vnd.api+json; ext=\"https://jsonapi.org/ext/atomic\"')\n headers.append('Content-Type', 'application/vnd.api+json; ext=\"https://jsonapi.org/ext/atomic\"')\n const response = await fetch(url, {\n method,\n headers,\n signal,\n body,\n })\n if (!response.ok) throw new Error(`HTTP error! status: ${response.status} ${response.statusText}`)\n if (response.status === 204) return\n const data = (await response.json()) as JsonApiAtomicDocument\n return data\n}\n\nexport type JsonApiFetcher = InstanceType<typeof JsonApiFetcherImpl>\n\nexport class JsonApiFetcherImpl implements JsonApiFetcher {\n constructor(public endpoint: string) {}\n createOptions(options: FetchOptions = {}, params: FetchParams = {}, body?: BodyInit): Options {\n const searchParams = new URLSearchParams()\n const headers = new Headers(options.headers ?? {})\n headers.append('Accept', 'application/vnd.api+json')\n const requestOptions = { searchParams, headers, body }\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 req(url, this.createOptions(options, params))\n return doc\n }\n async fetchAll(type: string, options?: FetchOptions, params?: FetchParams) {\n const url = resolvePath(this.endpoint, type)\n const doc = await req(url, this.createOptions(options, params))\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 req(url, this.createOptions(options, params))\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 req(url, this.createOptions(options, params))\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 req(url, this.createOptions(options, params))\n return doc\n }\n async post(resource: JsonApiResource, options?: FetchOptions) {\n const url = resolvePath(this.endpoint, resource.type)\n const postDoc: JsonApiDocument = {\n data: resource,\n }\n const body = JSON.stringify(postDoc)\n const newOptions = this.createOptions(options, {}, body)\n newOptions.method = 'POST'\n newOptions.headers.set('Content-Type', 'application/vnd.api+json')\n const doc = (await req(url, newOptions)) as JsonApiDocument\n return doc\n }\n async postAtomic(doc: JsonApiAtomicDocument, options?: FetchOptions) {\n const url = new URL([this.endpoint, 'operations'].join('/')).href\n options = options || {}\n options.body = JSON.stringify(doc)\n const results = await postAtomic(url, options)\n return results\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 FetchOptions, type FetchParams, type JsonApiFetcher, JsonApiFetcherImpl } from './json-api-fetcher.ts'\nimport { camel } from './util.ts'\n\nexport interface JsonApiResourceIdentifier {\n id?: string\n lid?: string\n type: string\n}\n\nexport interface JsonApiRelationship {\n data: null | [] | JsonApiResourceIdentifier | JsonApiResourceIdentifier[]\n}\n\nexport interface JsonApiResource {\n id?: string\n lid?: string\n type: string\n attributes: Record<string, unknown>\n relationships?: Record<string, JsonApiRelationship>\n}\n\nexport interface JsonApiMeta {\n // Pagination\n totalPages?: number\n totalItems?: number\n currentPage?: number\n itemsPerPage?: number\n\n // Common metadata\n timestamp?: string | number\n version?: string\n copyright?: string\n\n // Allow additional custom properties\n [key: string]: unknown\n}\n\nexport interface JsonApiLinkObject {\n href: string\n rel?: string\n describedby?: JsonApiLink\n title?: string\n type?: string\n hreflang?: string | string[]\n meta?: JsonApiMeta\n}\n\nexport type JsonApiLink = null | string | JsonApiLinkObject\n\nexport interface JsonApiLinks {\n self?: JsonApiLink\n related?: JsonApiLink\n describedby?: JsonApiLink\n first?: JsonApiLink\n last?: JsonApiLink\n prev?: JsonApiLink\n next?: JsonApiLink\n}\n\nexport interface JsonApiDocument {\n links?: JsonApiLinks\n data?: JsonApiResource | JsonApiResource[]\n errors?: JsonApiError[]\n included?: JsonApiResource[]\n meta?: JsonApiMeta\n}\n\nexport interface JsonApiError {\n id: string\n status: string\n code?: string\n title: string\n detail?: string\n meta?: JsonApiMeta\n}\n\nexport interface JsonApiAtomicOperation {\n op: 'add' | 'update' | 'remove'\n data: JsonApiResource\n}\n\nexport interface JsonApiAtomicResult {\n data: JsonApiResource\n meta?: JsonApiMeta\n}\n\nexport interface JsonApiAtomicDocument {\n ['atomic:operations']?: JsonApiAtomicOperation[]\n ['atomic:results']?: JsonApiAtomicResult[]\n errors?: JsonApiError[]\n}\n\nexport interface AtomicOperation {\n op: 'add' | 'update' | 'remove'\n data: BaseEntity\n}\n\nexport interface BaseEntity {\n id: string\n lid?: string\n type: string\n}\n\n/**\n * Model definition\n */\nexport interface ModelDefinition {\n /**\n * The JSON:API type for the model\n */\n type: string\n /**\n * Optional relationships for the model\n */\n relationships?: Record<string, Relationship>\n}\n\nexport interface JsonApiConfig {\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 /** The JSON:API type name of the related model */\n type: string\n /** The relationship type */\n relationshipType: RelationshipType\n}\n\nfunction setRelationship(record: BaseEntity, name: string, value: unknown): void {\n ;(record as unknown as Record<string, unknown>)[name] = value\n}\n\nexport type JsonApi = ReturnType<typeof useJsonApi>\n\nexport function useJsonApi(config: JsonApiConfig, fetcher?: JsonApiFetcher) {\n const _fetcher = fetcher ?? new JsonApiFetcherImpl(config.endpoint)\n\n // Map type names to their definitions\n const modelDefinitions = new Map<string, ModelDefinition>()\n const relationshipDefinitions = new Map<string, Record<string, Relationship>>()\n\n for (const modelDef of config.modelDefinitions) {\n modelDefinitions.set(modelDef.type, modelDef)\n if (modelDef.relationships) relationshipDefinitions.set(modelDef.type, modelDef.relationships)\n }\n\n function normalize(str: string) {\n return config.kebabCase ? camel(str) : str\n }\n\n function serializeRid(entity: BaseEntity): JsonApiResourceIdentifier {\n const rid: JsonApiResourceIdentifier = { type: entity.type }\n if (entity.lid) rid.lid = entity.lid\n else if (entity.id) rid.id = entity.id\n return rid\n }\n\n function serialize(record: BaseEntity): JsonApiResource {\n const relationships = relationshipDefinitions.get(record.type)\n const resource: JsonApiResource = serializeRid(record) as JsonApiResource\n resource.attributes = {}\n if (relationships) resource.relationships = {}\n for (const [key, value] of Object.entries(record)) {\n if (key === 'id' || key === 'lid' || key === 'type' || value === undefined) continue\n if (relationships && key in relationships) {\n const rel = relationships[key]\n if (rel.relationshipType === RelationshipType.HasMany) {\n const entities = value as unknown as BaseEntity[]\n resource.relationships![key] = {\n data: entities.map(serializeRid),\n }\n } else if (rel.relationshipType === RelationshipType.BelongsTo) {\n const entity = value as unknown as BaseEntity\n resource.relationships![key] = {\n data: serializeRid(entity),\n }\n } else {\n throw new Error(`Unknown relationship type for ${key}`)\n }\n } else {\n resource.attributes[key] = value\n }\n }\n return resource\n }\n\n function createRecord<T extends BaseEntity>(type: string, properties: Partial<T> & { id?: string }): T {\n const modelDef = modelDefinitions.get(type)\n if (!modelDef) throw new Error(`Model type ${type} not defined`)\n\n const id = properties.id ?? crypto.randomUUID()\n\n const record = { id, type, ...properties } as T\n\n // Normalize property keys if needed\n if (config.kebabCase) {\n const normalizedRecord = { id, type } as BaseEntity & Record<string, unknown>\n for (const [key, value] of Object.entries(properties))\n if (key !== 'id' && value !== undefined) normalizedRecord[normalize(key)] = value\n return normalizedRecord as T\n }\n\n return record as T\n }\n\n function resourcesToRecords<T extends BaseEntity>(resources: JsonApiResource[], included?: JsonApiResource[]): T[] {\n // Create records for included resources - use type -> id map structure to avoid collisions\n const includedMap = new Map<string, Map<string, BaseEntity>>()\n if (included) {\n for (const resource of included) {\n const record = createRecord<BaseEntity>(resource.type, {\n id: resource.id,\n ...resource.attributes,\n })\n if (!includedMap.has(resource.type)) includedMap.set(resource.type, new Map())\n includedMap.get(resource.type)!.set(resource.id!, record)\n }\n }\n\n // Create records for main resources\n const records = resources.map((resource) =>\n createRecord<T>(resource.type, {\n id: resource.id,\n ...(resource.attributes as Partial<T>),\n }),\n )\n\n const recordsMap = new Map<string, BaseEntity>()\n for (const record of records) recordsMap.set(record.id!, record)\n\n // Populate relationships\n function populateRelationships(resource: JsonApiResource) {\n const record = recordsMap.get(resource.id!) ?? includedMap.get(resource.type)?.get(resource.id!)\n if (!record) throw new Error('Unexpected not found record')\n\n if (!resource.relationships) return\n\n const rels = relationshipDefinitions.get(resource.type)\n if (!rels) return\n\n for (const [name, reldoc] of Object.entries(resource.relationships)) {\n const normalizedName = normalize(name)\n const rel = rels[normalizedName]\n if (!rel) continue // Ignore undefined relationships\n\n const rids =\n rel.relationshipType === RelationshipType.HasMany\n ? (reldoc.data as JsonApiResourceIdentifier[])\n : [reldoc.data as JsonApiResourceIdentifier]\n\n const relatedRecords = rids\n .filter((d) => d && d.type === rel.type)\n .map((d) => includedMap.get(d.type)?.get(d.id!) || recordsMap.get(d.id!))\n .filter(Boolean)\n\n setRelationship(\n record,\n normalizedName,\n rel.relationshipType === RelationshipType.HasMany ? relatedRecords : relatedRecords[0],\n )\n }\n }\n\n if (included) {\n resources.forEach(populateRelationships)\n included.forEach(populateRelationships)\n }\n\n return records\n }\n\n async function findAll<T extends BaseEntity>(\n type: string,\n options?: FetchOptions,\n params?: FetchParams,\n ): Promise<{ doc: JsonApiDocument; records: T[] }> {\n const doc = await _fetcher.fetchDocument(type, undefined, options, params)\n const resources = doc.data as JsonApiResource[]\n const records = resourcesToRecords<T>(resources, doc.included)\n return { doc, records }\n }\n\n async function findRecord<T extends BaseEntity>(\n type: string,\n id: string,\n options?: FetchOptions,\n params?: FetchParams,\n ): Promise<T> {\n const doc = await _fetcher.fetchDocument(type, id, options, params)\n const resource = doc.data as JsonApiResource\n const records = resourcesToRecords<T>([resource], doc.included)\n const record = records[0]\n if (!record) throw new Error(`Record with id ${id} not found`)\n return record\n }\n\n async function findRelated(\n record: BaseEntity,\n relationshipName: string,\n options?: FetchOptions,\n params?: FetchParams,\n ): Promise<JsonApiDocument> {\n const type = record.type\n const rels = relationshipDefinitions.get(type)\n if (!rels) throw new Error(`Model ${type} has no relationships`)\n\n const rel = rels[relationshipName]\n if (!rel) throw new Error(`Relationship ${relationshipName} not defined`)\n\n if (rel.relationshipType === RelationshipType.BelongsTo) {\n const doc = await _fetcher.fetchBelongsTo(type, record.id!, relationshipName, options, params)\n const related = doc.data as JsonApiResource\n const relatedRecord = createRecord(rel.type, {\n id: related.id,\n ...related.attributes,\n })\n setRelationship(record, relationshipName, relatedRecord)\n return doc\n }\n\n const doc = await _fetcher.fetchHasMany(type, record.id!, relationshipName, options, params)\n const related =\n rel.relationshipType === RelationshipType.HasMany\n ? (doc.data as JsonApiResource[])\n : [doc.data as JsonApiResource]\n\n const relatedRecords = related.map((r) =>\n createRecord(rel.type, {\n id: r.id,\n ...r.attributes,\n }),\n )\n\n setRelationship(\n record,\n relationshipName,\n rel.relationshipType === RelationshipType.HasMany ? relatedRecords : relatedRecords[0],\n )\n\n return doc\n }\n\n async function saveRecord<T extends BaseEntity>(record: BaseEntity, options?: FetchOptions): Promise<T> {\n const resource = serialize(record)\n const doc = await _fetcher.post(resource, options)\n const records = resourcesToRecords<T>([doc.data] as JsonApiResource[])\n return records[0] as T\n }\n\n async function saveAtomic(\n operations: AtomicOperation[],\n options?: FetchOptions,\n ): Promise<{ doc: JsonApiAtomicDocument; records: BaseEntity[] } | undefined> {\n const atomicOperations = operations.map((op) => ({ op: op.op, data: serialize(op.data) }) as JsonApiAtomicOperation)\n const atomicDoc: JsonApiAtomicDocument = {\n ['atomic:operations']: atomicOperations,\n }\n const doc = await _fetcher.postAtomic(atomicDoc, options)\n if (!doc) return\n const records = resourcesToRecords(doc['atomic:results']!.map((r) => r.data))\n return { doc, records }\n }\n\n return {\n findAll,\n findRecord,\n findRelated,\n createRecord,\n saveRecord,\n saveAtomic,\n }\n}\n"],"names":["resolvePath","segments","req","url","options","headers","searchParams","method","signal","body","textSearchParams","finalUrl","response","postAtomic","JsonApiFetcherImpl","endpoint","params","requestOptions","key","value","type","id","name","resource","newOptions","doc","camel","str","match","RelationshipType","setRelationship","record","useJsonApi","config","fetcher","_fetcher","modelDefinitions","relationshipDefinitions","modelDef","normalize","serializeRid","entity","rid","serialize","relationships","rel","entities","createRecord","properties","normalizedRecord","resourcesToRecords","resources","included","includedMap","records","recordsMap","populateRelationships","rels","reldoc","normalizedName","relatedRecords","d","findAll","findRecord","findRelated","relationshipName","related","relatedRecord","r","saveRecord","saveAtomic","operations","atomicDoc","op"],"mappings":"AAEA,SAASA,KAAeC,GAA4B;AAClD,SAAO,IAAI,IAAIA,EAAS,KAAK,GAAG,CAAC,EAAE;AACrC;AA6BA,eAAeC,EAAIC,GAAaC,GAAkB;AAChD,QAAM,EAAE,SAAAC,GAAS,cAAAC,GAAc,QAAAC,GAAQ,QAAAC,GAAQ,MAAAC,MAASL,GAClDM,IAAmBJ,IAAe,IAAIA,CAAY,KAAK,IACvDK,IAAWR,EAAI,QA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GAGhFnC;AAAA,EACT;AAEA,iBAAe4C,EAAiCtC,GAAoB3B,GAAoC;AACtG,UAAMmB,IAAWoB,EAAUZ,CAAM,GAC3BN,IAAM,MAAMU,EAAS,KAAKZ,GAAUnB,CAAO;AAEjD,WADgB8C,EAAsB,CAACzB,EAAI,IAAI,CAAsB,EACtD,CAAC;AAAA,EAClB;AAEA,iBAAe6C,EACbC,GACAnE,GAC4E;AAE5E,UAAMoE,IAAmC;AAAA,MACtC,qBAFsBD,EAAW,IAAI,CAACE,OAAQ,EAAE,IAAIA,EAAG,IAAI,MAAM9B,EAAU8B,EAAG,IAAI,IAA8B;AAAA,IAE1F,GAEnBhD,IAAM,MAAMU,EAAS,WAAWqC,GAAWpE,CAAO;AACxD,QAAI,CAACqB,EAAK;AACV,UAAM6B,IAAUJ,EAAmBzB,EAAI,gBAAgB,EAAG,IAAI,CAAC2C,MAAMA,EAAE,IAAI,CAAC;AAC5E,WAAO,EAAE,KAAA3C,GAAK,SAAA6B,EAAA;AAAA,EAChB;AAEA,SAAO;AAAA,IACL,SAAAQ;AAAA,IACA,YAAAC;AAAA,IACA,aAAAC;AAAA,IACA,cAAAjB;AAAA,IACA,YAAAsB;AAAA,IACA,YAAAC;AAAA,EAAA;AAEJ;"}
|
|
1
|
+
{"version":3,"file":"lib.js","sources":["../src/json-api-fetcher.ts","../src/util.ts","../src/json-api.ts"],"sourcesContent":["import type { JsonApiAtomicDocument, JsonApiDocument, JsonApiResource } from './json-api.ts'\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 headers?: HeadersInit\n body?: BodyInit\n signal?: AbortSignal\n}\n\nexport interface FetchParams {\n [key: string]: string\n}\n\nexport interface Options {\n searchParams?: URLSearchParams\n headers: Headers\n method?: string\n body?: BodyInit\n signal?: AbortSignal\n}\n\nasync function req(url: string, options: Options) {\n const { headers, searchParams, method, signal, body } = options\n const textSearchParams = searchParams ? `?${searchParams}` : ''\n const finalUrl = url.replace(/(?:\\?.*?)?(?=#|$)/, textSearchParams)\n const response = await fetch(finalUrl, {\n method,\n headers,\n signal,\n body,\n })\n if (!response.ok) throw new Error(`HTTP error! status: ${response.status} ${response.statusText}`)\n const data = (await response.json()) as JsonApiDocument\n return data\n}\n\nasync function postAtomic(url: string, options: FetchOptions) {\n const { signal, body } = options\n const method = 'POST'\n const headers = new Headers(options.headers ?? {})\n headers.append('Accept', 'application/vnd.api+json; ext=\"https://jsonapi.org/ext/atomic\"')\n headers.append('Content-Type', 'application/vnd.api+json; ext=\"https://jsonapi.org/ext/atomic\"')\n const response = await fetch(url, {\n method,\n headers,\n signal,\n body,\n })\n if (!response.ok) throw new Error(`HTTP error! status: ${response.status} ${response.statusText}`)\n if (response.status === 204) return\n const data = (await response.json()) as JsonApiAtomicDocument\n return data\n}\n\nexport type JsonApiFetcher = InstanceType<typeof JsonApiFetcherImpl>\n\nexport class JsonApiFetcherImpl implements JsonApiFetcher {\n constructor(public endpoint: string) {}\n createOptions(options: FetchOptions = {}, params: FetchParams = {}, body?: BodyInit): Options {\n const searchParams = new URLSearchParams()\n const headers = new Headers(options.headers ?? {})\n headers.append('Accept', 'application/vnd.api+json')\n const requestOptions = { searchParams, headers, body }\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 req(url, this.createOptions(options, params))\n return doc\n }\n async fetchAll(type: string, options?: FetchOptions, params?: FetchParams) {\n const url = resolvePath(this.endpoint, type)\n const doc = await req(url, this.createOptions(options, params))\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 req(url, this.createOptions(options, params))\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 req(url, this.createOptions(options, params))\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 req(url, this.createOptions(options, params))\n return doc\n }\n async post(resource: JsonApiResource, options?: FetchOptions) {\n const url = resolvePath(this.endpoint, resource.type)\n const postDoc: JsonApiDocument = {\n data: resource,\n }\n const body = JSON.stringify(postDoc)\n const newOptions = this.createOptions(options, {}, body)\n newOptions.method = 'POST'\n newOptions.headers.set('Content-Type', 'application/vnd.api+json')\n const doc = (await req(url, newOptions)) as JsonApiDocument\n return doc\n }\n async postAtomic(doc: JsonApiAtomicDocument, options: FetchOptions = {}) {\n const url = new URL([this.endpoint, 'operations'].join('/')).href\n options.body = JSON.stringify(doc)\n const results = await postAtomic(url, options)\n return results\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 FetchOptions, type FetchParams, type JsonApiFetcher, JsonApiFetcherImpl } from './json-api-fetcher.ts'\nimport { camel } from './util.ts'\n\nexport interface JsonApiResourceIdentifier {\n id?: string\n lid?: string\n type: string\n}\n\nexport interface JsonApiRelationship {\n data: null | [] | JsonApiResourceIdentifier | JsonApiResourceIdentifier[]\n}\n\nexport interface JsonApiResource {\n id?: string\n lid?: string\n type: string\n attributes: Record<string, unknown>\n relationships?: Record<string, JsonApiRelationship>\n}\n\nexport interface JsonApiMeta {\n // Pagination\n totalPages?: number\n totalItems?: number\n currentPage?: number\n itemsPerPage?: number\n\n // Common metadata\n timestamp?: string | number\n version?: string\n copyright?: string\n\n // Allow additional custom properties\n [key: string]: unknown\n}\n\nexport interface JsonApiLinkObject {\n href: string\n rel?: string\n describedby?: JsonApiLink\n title?: string\n type?: string\n hreflang?: string | string[]\n meta?: JsonApiMeta\n}\n\nexport type JsonApiLink = null | string | JsonApiLinkObject\n\nexport interface JsonApiLinks {\n self?: JsonApiLink\n related?: JsonApiLink\n describedby?: JsonApiLink\n first?: JsonApiLink\n last?: JsonApiLink\n prev?: JsonApiLink\n next?: JsonApiLink\n}\n\nexport interface JsonApiDocument {\n links?: JsonApiLinks\n data?: JsonApiResource | JsonApiResource[]\n errors?: JsonApiError[]\n included?: JsonApiResource[]\n meta?: JsonApiMeta\n}\n\nexport interface JsonApiReference extends JsonApiResourceIdentifier {\n relationship?: string\n}\n\nexport interface JsonApiError {\n id: string\n status: string\n code?: string\n title: string\n detail?: string\n meta?: JsonApiMeta\n}\n\nexport interface JsonApiAtomicOperation {\n op: 'add' | 'update' | 'remove'\n data?: JsonApiResource\n ref?: JsonApiReference\n}\n\nexport interface JsonApiAtomicResult {\n data: JsonApiResource\n meta?: JsonApiMeta\n}\n\nexport interface JsonApiAtomicDocument {\n 'atomic:operations'?: JsonApiAtomicOperation[]\n 'atomic:results'?: JsonApiAtomicResult[]\n errors?: JsonApiError[]\n}\n\nexport interface AtomicOperation {\n op: 'add' | 'update' | 'remove'\n data: BaseEntity\n}\n\nexport interface BaseEntity {\n id: string\n lid?: string\n type: string\n}\n\n/**\n * Model definition\n */\nexport interface ModelDefinition {\n /**\n * The JSON:API type for the model\n */\n type: string\n /**\n * Optional relationships for the model\n */\n relationships?: Record<string, Relationship>\n}\n\nexport interface JsonApiConfig {\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 /** The JSON:API type name of the related model */\n type: string\n /** The relationship type */\n relationshipType: RelationshipType\n}\n\nfunction setRelationship(record: BaseEntity, name: string, value: unknown): void {\n ;(record as unknown as Record<string, unknown>)[name] = value\n}\n\nexport type JsonApi = ReturnType<typeof useJsonApi>\n\nfunction serializeRid(entity: BaseEntity): JsonApiResourceIdentifier {\n const rid: JsonApiResourceIdentifier = { type: entity.type }\n if (entity.lid) rid.lid = entity.lid\n else if (entity.id) rid.id = entity.id\n return rid\n}\n\nexport function useJsonApi(config: JsonApiConfig, fetcher?: JsonApiFetcher) {\n const _fetcher = fetcher ?? new JsonApiFetcherImpl(config.endpoint)\n\n // Map type names to their definitions\n const modelDefinitions = new Map<string, ModelDefinition>()\n const relationshipDefinitions = new Map<string, Record<string, Relationship>>()\n\n for (const modelDef of config.modelDefinitions) {\n modelDefinitions.set(modelDef.type, modelDef)\n if (modelDef.relationships) relationshipDefinitions.set(modelDef.type, modelDef.relationships)\n }\n\n function normalize(str: string) {\n return config.kebabCase ? camel(str) : str\n }\n\n function serialize(record: BaseEntity): JsonApiResource {\n const relationships = relationshipDefinitions.get(record.type)\n const resource: JsonApiResource = serializeRid(record) as JsonApiResource\n resource.attributes = {}\n if (relationships) resource.relationships = {}\n for (const [key, value] of Object.entries(record)) {\n if (key === 'id' || key === 'lid' || key === 'type' || value === undefined) continue\n if (relationships && key in relationships && resource.relationships) {\n const rel = relationships[key]\n if (rel.relationshipType === RelationshipType.HasMany) {\n const entities = value as unknown as BaseEntity[]\n resource.relationships[key] = {\n data: entities.map(serializeRid),\n }\n } else if (rel.relationshipType === RelationshipType.BelongsTo) {\n const entity = value as unknown as BaseEntity\n resource.relationships[key] = {\n data: serializeRid(entity),\n }\n } else {\n throw new Error(`Unknown relationship type for ${key}`)\n }\n } else {\n resource.attributes[key] = value\n }\n }\n return resource\n }\n\n function createRecord<T extends BaseEntity>(type: string, properties: Partial<T> & { id?: string }): T {\n const modelDef = modelDefinitions.get(type)\n if (!modelDef) throw new Error(`Model type ${type} not defined`)\n\n const id = properties.id ?? crypto.randomUUID()\n\n const record = { id, type, ...properties } as T\n\n // Normalize property keys if needed\n if (config.kebabCase) {\n const normalizedRecord = { id, type } as BaseEntity & Record<string, unknown>\n for (const [key, value] of Object.entries(properties))\n if (key !== 'id' && value !== undefined) normalizedRecord[normalize(key)] = value\n return normalizedRecord as T\n }\n\n return record\n }\n\n function resourcesToRecords(resources: JsonApiResource[], included?: JsonApiResource[]): BaseEntity[] {\n function resourceToRecord(resource: JsonApiResource): BaseEntity {\n return createRecord(resource.type, {\n id: resource.id,\n ...resource.attributes,\n })\n }\n\n function setRecord(map: Map<string, Map<string, BaseEntity>>, record: BaseEntity) {\n if (!map.has(record.type)) map.set(record.type, new Map())\n map.get(record.type)?.set(record.id, record)\n }\n\n function getRecord(map: Map<string, Map<string, BaseEntity>>, rid: JsonApiResourceIdentifier) {\n if (rid.id === undefined) throw new Error('Resource identifier must have an id')\n if (!map.has(rid.type)) map.set(rid.type, new Map())\n return map.get(rid.type)?.get(rid.id)\n }\n\n const includedMap = new Map<string, Map<string, BaseEntity>>()\n if (included) for (const resource of included) setRecord(includedMap, resourceToRecord(resource))\n\n const records = resources.map(resourceToRecord)\n const recordsMap = new Map<string, Map<string, BaseEntity>>()\n for (const record of records) setRecord(recordsMap, record)\n\n function populateRelationships(resource: JsonApiResource) {\n const record = getRecord(recordsMap, resource) ?? getRecord(includedMap, resource)\n if (!record) throw new Error('Unexpected not found record')\n\n if (!resource.relationships) return\n\n const rels = relationshipDefinitions.get(resource.type)\n if (!rels) return\n\n for (const [name, reldoc] of Object.entries(resource.relationships)) {\n const normalizedName = normalize(name)\n const rel = rels[normalizedName]\n if (!rel) continue\n if (!reldoc.data) continue\n const rids =\n rel.relationshipType === RelationshipType.HasMany\n ? (reldoc.data as JsonApiResourceIdentifier[])\n : [reldoc.data as JsonApiResourceIdentifier]\n const relatedRecords = rids\n .filter((d) => d && d.type === rel.type)\n .map((d) => getRecord(includedMap, d) || getRecord(recordsMap, d))\n .filter(Boolean)\n setRelationship(\n record,\n normalizedName,\n rel.relationshipType === RelationshipType.HasMany ? relatedRecords : relatedRecords[0],\n )\n }\n }\n\n if (included) {\n for (const r of resources) populateRelationships(r)\n for (const r of included) populateRelationships(r)\n }\n\n return records\n }\n\n async function findAll<T extends BaseEntity>(\n type: string,\n options?: FetchOptions,\n params?: FetchParams,\n ): Promise<{ doc: JsonApiDocument; records: T[] }> {\n const doc = await _fetcher.fetchDocument(type, undefined, options, params)\n const resources = doc.data as JsonApiResource[]\n const records = resourcesToRecords(resources, doc.included) as T[]\n return { doc, records }\n }\n\n async function findRecord<T extends BaseEntity>(\n type: string,\n id: string,\n options?: FetchOptions,\n params?: FetchParams,\n ): Promise<T> {\n const doc = await _fetcher.fetchDocument(type, id, options, params)\n const resource = doc.data as JsonApiResource\n const records = resourcesToRecords([resource], doc.included) as T[]\n const record = records[0]\n if (!record) throw new Error(`Record with id ${id} not found`)\n return record\n }\n\n async function findRelated(\n record: BaseEntity,\n relationshipName: string,\n options?: FetchOptions,\n params?: FetchParams,\n ): Promise<JsonApiDocument> {\n const type = record.type\n const rels = relationshipDefinitions.get(type)\n if (!rels) throw new Error(`Model ${type} has no relationships`)\n\n const rel = rels[relationshipName]\n if (!rel) throw new Error(`Relationship ${relationshipName} not defined`)\n\n if (rel.relationshipType === RelationshipType.BelongsTo) {\n const doc = await _fetcher.fetchBelongsTo(type, record.id, relationshipName, options, params)\n const related = doc.data as JsonApiResource\n const relatedRecord = createRecord(rel.type, {\n id: related.id,\n ...related.attributes,\n })\n setRelationship(record, relationshipName, relatedRecord)\n return doc\n }\n\n const doc = await _fetcher.fetchHasMany(type, record.id, relationshipName, options, params)\n const related =\n rel.relationshipType === RelationshipType.HasMany\n ? (doc.data as JsonApiResource[])\n : [doc.data as JsonApiResource]\n\n const relatedRecords = related.map((r) =>\n createRecord(rel.type, {\n id: r.id,\n ...r.attributes,\n }),\n )\n\n setRelationship(\n record,\n relationshipName,\n rel.relationshipType === RelationshipType.HasMany ? relatedRecords : relatedRecords[0],\n )\n\n return doc\n }\n\n async function saveRecord<T extends BaseEntity>(record: BaseEntity, options?: FetchOptions): Promise<T> {\n const resource = serialize(record)\n const doc = await _fetcher.post(resource, options)\n const records = resourcesToRecords([doc.data] as JsonApiResource[])\n return records[0] as T\n }\n\n async function saveAtomic(\n operations: AtomicOperation[],\n options?: FetchOptions,\n ): Promise<{ doc: JsonApiAtomicDocument; records: BaseEntity[] } | undefined> {\n const atomicOperations = operations.map((op) => ({ op: op.op, data: serialize(op.data) }) as JsonApiAtomicOperation)\n const atomicDoc: JsonApiAtomicDocument = {\n 'atomic:operations': atomicOperations,\n }\n const doc = await _fetcher.postAtomic(atomicDoc, options)\n if (!doc) return\n const records = doc['atomic:results'] ? resourcesToRecords(doc['atomic:results'].map((r) => r.data)) : []\n return { doc, records }\n }\n\n return {\n findAll,\n findRecord,\n findRelated,\n createRecord,\n saveRecord,\n saveAtomic,\n }\n}\n"],"names":["resolvePath","segments","req","url","options","headers","searchParams","method","signal","body","textSearchParams","finalUrl","response","postAtomic","JsonApiFetcherImpl","endpoint","params","requestOptions","key","value","type","id","name","resource","newOptions","doc","camel","str","match","RelationshipType","setRelationship","record","serializeRid","entity","rid","useJsonApi","config","fetcher","_fetcher","modelDefinitions","relationshipDefinitions","modelDef","normalize","serialize","relationships","rel","entities","createRecord","properties","normalizedRecord","resourcesToRecords","resources","included","resourceToRecord","setRecord","map","getRecord","includedMap","records","recordsMap","populateRelationships","rels","reldoc","normalizedName","relatedRecords","d","r","findAll","findRecord","findRelated","relationshipName","related","relatedRecord","saveRecord","saveAtomic","operations","atomicDoc","op"],"mappings":"AAEA,SAASA,KAA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AAAA,IACA,cAAAtB;AAAA,IACA,YAAA0B;AAAA,IACA,YAAAC;AAAA,EAAA;AAEJ;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bjornharrtell/json-api",
|
|
3
|
-
"version": "5.0
|
|
3
|
+
"version": "5.1.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "./dist/lib.js",
|
|
6
6
|
"module": "./dist/lib.js",
|
|
@@ -18,13 +18,13 @@
|
|
|
18
18
|
"url": "git+https://github.com/bjornharrtell/json-api.git"
|
|
19
19
|
},
|
|
20
20
|
"devDependencies": {
|
|
21
|
-
"@biomejs/biome": "2.
|
|
22
|
-
"@types/node": "^
|
|
23
|
-
"typedoc": "^0.28.
|
|
21
|
+
"@biomejs/biome": "2.3.11",
|
|
22
|
+
"@types/node": "^25.0.9",
|
|
23
|
+
"typedoc": "^0.28.16",
|
|
24
24
|
"typescript": "~5.9.3",
|
|
25
|
-
"vite": "^7.1
|
|
25
|
+
"vite": "^7.3.1",
|
|
26
26
|
"vite-plugin-dts": "^4.5.4",
|
|
27
|
-
"vitest": "^
|
|
27
|
+
"vitest": "^4.0.17"
|
|
28
28
|
},
|
|
29
29
|
"scripts": {
|
|
30
30
|
"dev": "vite",
|