@aggiovato/yrest 0.1.1 → 0.2.1
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 +360 -33
- package/dist/cli/index.js +569 -59
- package/dist/cli/index.mjs +569 -59
- package/dist/index.d.mts +124 -3
- package/dist/index.d.ts +124 -3
- package/dist/index.js +494 -44
- package/dist/index.mjs +494 -44
- package/package.json +13 -4
package/dist/index.mjs
CHANGED
|
@@ -28,6 +28,17 @@ function createYamlStorage(filePath) {
|
|
|
28
28
|
const tmp = resolve(dirname(absPath), `.yrest-${randomUUID()}.tmp`);
|
|
29
29
|
writeFileSync(tmp, stringify(payload), "utf8");
|
|
30
30
|
renameSync(tmp, absPath);
|
|
31
|
+
},
|
|
32
|
+
reload() {
|
|
33
|
+
const fresh = parse(readFileSync(absPath, "utf8")) ?? {};
|
|
34
|
+
const freshRelations = fresh["_rel"] ?? {};
|
|
35
|
+
const freshData = Object.fromEntries(
|
|
36
|
+
Object.entries(fresh).filter(([key]) => key !== "_rel")
|
|
37
|
+
);
|
|
38
|
+
for (const key of Object.keys(data)) delete data[key];
|
|
39
|
+
Object.assign(data, freshData);
|
|
40
|
+
for (const key of Object.keys(relations)) delete relations[key];
|
|
41
|
+
Object.assign(relations, freshRelations);
|
|
31
42
|
}
|
|
32
43
|
};
|
|
33
44
|
}
|
|
@@ -77,17 +88,68 @@ function patchItem(storage, resource, id, body) {
|
|
|
77
88
|
storage.persist();
|
|
78
89
|
return updated;
|
|
79
90
|
}
|
|
91
|
+
function firstParam(value) {
|
|
92
|
+
if (value === void 0) return void 0;
|
|
93
|
+
return Array.isArray(value) ? value[0] : value;
|
|
94
|
+
}
|
|
80
95
|
function filterByQuery(items, query) {
|
|
81
96
|
const filters = Object.entries(query).filter(([key]) => !key.startsWith("_"));
|
|
82
97
|
if (filters.length === 0) return items;
|
|
83
98
|
return items.filter(
|
|
84
|
-
(item) => filters.every(([key, value]) =>
|
|
99
|
+
(item) => filters.every(([key, value]) => {
|
|
100
|
+
if (item[key] === void 0) return false;
|
|
101
|
+
const itemStr = String(item[key]);
|
|
102
|
+
return Array.isArray(value) ? value.includes(itemStr) : itemStr === value;
|
|
103
|
+
})
|
|
85
104
|
);
|
|
86
105
|
}
|
|
106
|
+
function sortBy(items, field, order) {
|
|
107
|
+
const direction = order === "desc" ? -1 : 1;
|
|
108
|
+
return [...items].sort((a, b) => {
|
|
109
|
+
const av = a[field];
|
|
110
|
+
const bv = b[field];
|
|
111
|
+
if (av === void 0) return 1;
|
|
112
|
+
if (bv === void 0) return -1;
|
|
113
|
+
if (typeof av === "number" && typeof bv === "number") return (av - bv) * direction;
|
|
114
|
+
return String(av).localeCompare(String(bv), void 0, { sensitivity: "base" }) * direction;
|
|
115
|
+
});
|
|
116
|
+
}
|
|
87
117
|
function paginate(items, page, limit) {
|
|
88
118
|
const start = (page - 1) * limit;
|
|
89
119
|
return items.slice(start, start + limit);
|
|
90
120
|
}
|
|
121
|
+
function expandItems(input, query, resource, storage) {
|
|
122
|
+
const isArray = Array.isArray(input);
|
|
123
|
+
const items = isArray ? input : [input];
|
|
124
|
+
const expandParam = query["_expand"];
|
|
125
|
+
if (!expandParam) return isArray ? items : input;
|
|
126
|
+
const keys = (Array.isArray(expandParam) ? expandParam : [expandParam]).flatMap((v) => v.split(",")).map((k) => k.trim()).filter(Boolean);
|
|
127
|
+
const resourceRelations = storage.getRelations()[resource] ?? {};
|
|
128
|
+
const expansions = /* @__PURE__ */ new Map();
|
|
129
|
+
for (const expandKey of keys) {
|
|
130
|
+
for (const [field, parentCollection] of Object.entries(resourceRelations)) {
|
|
131
|
+
const derivedKey = field.replace(/Id$/i, "");
|
|
132
|
+
if (derivedKey === expandKey || parentCollection === expandKey || parentCollection === `${expandKey}s`) {
|
|
133
|
+
expansions.set(expandKey, { field, parentCollection });
|
|
134
|
+
break;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
if (expansions.size === 0) return isArray ? items : input;
|
|
139
|
+
const expanded = items.map((item) => {
|
|
140
|
+
const result = { ...item };
|
|
141
|
+
for (const [expandKey, { field, parentCollection }] of expansions) {
|
|
142
|
+
const foreignKeyValue = item[field];
|
|
143
|
+
if (foreignKeyValue === void 0) continue;
|
|
144
|
+
const parent = (storage.getCollection(parentCollection) ?? []).find(
|
|
145
|
+
(p) => String(p["id"]) === String(foreignKeyValue)
|
|
146
|
+
);
|
|
147
|
+
if (parent !== void 0) result[expandKey] = parent;
|
|
148
|
+
}
|
|
149
|
+
return result;
|
|
150
|
+
});
|
|
151
|
+
return isArray ? expanded : expanded[0];
|
|
152
|
+
}
|
|
91
153
|
function deleteItem(storage, resource, id) {
|
|
92
154
|
const collection = storage.getCollection(resource) ?? [];
|
|
93
155
|
const idx = findIndexById(collection, id);
|
|
@@ -99,93 +161,481 @@ function deleteItem(storage, resource, id) {
|
|
|
99
161
|
}
|
|
100
162
|
|
|
101
163
|
// src/router/routes/collection.routes.ts
|
|
102
|
-
|
|
103
|
-
server.get(
|
|
164
|
+
var registerCollectionRoutes = (server, storage, resource, base, options) => {
|
|
165
|
+
server.get(base, (req, reply) => {
|
|
104
166
|
const collection = storage.getCollection(resource) ?? [];
|
|
105
167
|
const filtered = filterByQuery(collection, req.query);
|
|
106
|
-
const
|
|
107
|
-
const
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
168
|
+
const sortField = firstParam(req.query["_sort"]);
|
|
169
|
+
const sortOrder = firstParam(req.query["_order"]) === "desc" ? "desc" : "asc";
|
|
170
|
+
const sorted = sortField ? sortBy(filtered, sortField, sortOrder) : filtered;
|
|
171
|
+
if (options.pageable.enabled) {
|
|
172
|
+
const defaultLimit = options.pageable.limit;
|
|
173
|
+
const page = Math.max(1, parseInt(firstParam(req.query["_page"]) ?? "1", 10) || 1);
|
|
174
|
+
const limit = Math.max(
|
|
175
|
+
1,
|
|
176
|
+
parseInt(firstParam(req.query["_limit"]) ?? String(defaultLimit), 10) || defaultLimit
|
|
177
|
+
);
|
|
178
|
+
const totalItems = sorted.length;
|
|
179
|
+
const totalPages = Math.ceil(totalItems / limit) || 1;
|
|
180
|
+
const data = expandItems(paginate(sorted, page, limit), req.query, resource, storage);
|
|
181
|
+
const pagination = {
|
|
182
|
+
page,
|
|
183
|
+
limit,
|
|
184
|
+
totalItems,
|
|
185
|
+
totalPages,
|
|
186
|
+
isFirst: page === 1,
|
|
187
|
+
isLast: page >= totalPages,
|
|
188
|
+
hasNext: page < totalPages,
|
|
189
|
+
hasPrev: page > 1
|
|
190
|
+
};
|
|
191
|
+
return reply.send({ data, pagination });
|
|
192
|
+
}
|
|
193
|
+
const rawPage = firstParam(req.query["_page"]);
|
|
194
|
+
const rawLimit = firstParam(req.query["_limit"]);
|
|
195
|
+
let result;
|
|
196
|
+
if (!rawPage && !rawLimit) {
|
|
197
|
+
result = sorted;
|
|
198
|
+
} else {
|
|
199
|
+
const page = Math.max(1, parseInt(rawPage ?? "1", 10) || 1);
|
|
200
|
+
const limit = Math.max(1, parseInt(rawLimit ?? "10", 10) || 10);
|
|
201
|
+
reply.header("X-Total-Count", String(sorted.length));
|
|
202
|
+
result = paginate(sorted, page, limit);
|
|
203
|
+
}
|
|
204
|
+
return expandItems(result, req.query, resource, storage);
|
|
113
205
|
});
|
|
114
|
-
server.post(
|
|
206
|
+
server.post(base, (req, reply) => {
|
|
115
207
|
const item = createItem(storage, resource, req.body);
|
|
116
|
-
return reply.status(201).send(item);
|
|
208
|
+
return reply.status(201).send(expandItems(item, req.query, resource, storage));
|
|
117
209
|
});
|
|
118
|
-
}
|
|
210
|
+
};
|
|
119
211
|
|
|
120
212
|
// src/router/routes/item.routes.ts
|
|
121
|
-
|
|
122
|
-
server.get(`${
|
|
213
|
+
var registerItemRoutes = (server, storage, resource, base) => {
|
|
214
|
+
server.get(`${base}/:id`, (req, reply) => {
|
|
123
215
|
const item = findById(storage.getCollection(resource) ?? [], req.params.id);
|
|
124
216
|
if (!item) return reply.status(404).send({ error: "Not found" });
|
|
125
|
-
return item;
|
|
217
|
+
return expandItems(item, req.query, resource, storage);
|
|
126
218
|
});
|
|
127
|
-
server.put(`${
|
|
219
|
+
server.put(`${base}/:id`, (req, reply) => {
|
|
128
220
|
const item = replaceItem(storage, resource, req.params.id, req.body);
|
|
129
221
|
if (!item) return reply.status(404).send({ error: "Not found" });
|
|
130
|
-
return item;
|
|
222
|
+
return expandItems(item, req.query, resource, storage);
|
|
131
223
|
});
|
|
132
|
-
server.patch(`${
|
|
224
|
+
server.patch(`${base}/:id`, (req, reply) => {
|
|
133
225
|
const item = patchItem(storage, resource, req.params.id, req.body);
|
|
134
226
|
if (!item) return reply.status(404).send({ error: "Not found" });
|
|
135
|
-
return item;
|
|
227
|
+
return expandItems(item, req.query, resource, storage);
|
|
136
228
|
});
|
|
137
|
-
server.delete(`${
|
|
229
|
+
server.delete(`${base}/:id`, (req, reply) => {
|
|
138
230
|
const item = deleteItem(storage, resource, req.params.id);
|
|
139
231
|
if (!item) return reply.status(404).send({ error: "Not found" });
|
|
140
|
-
return item;
|
|
232
|
+
return expandItems(item, req.query, resource, storage);
|
|
141
233
|
});
|
|
142
|
-
}
|
|
234
|
+
};
|
|
143
235
|
|
|
144
236
|
// src/router/routes/nested.routes.ts
|
|
145
|
-
|
|
237
|
+
var registerNestedRoutes = (server, storage, relations, base) => {
|
|
146
238
|
for (const [child, fields] of Object.entries(relations)) {
|
|
147
239
|
for (const [field, parent] of Object.entries(fields)) {
|
|
148
|
-
server.get(
|
|
149
|
-
|
|
150
|
-
(
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
return children;
|
|
158
|
-
}
|
|
159
|
-
);
|
|
240
|
+
server.get(`${base}/${parent}/:id/${child}`, (req, reply) => {
|
|
241
|
+
const parentCollection = storage.getCollection(parent) ?? [];
|
|
242
|
+
const parentItem = findById(parentCollection, req.params.id);
|
|
243
|
+
if (!parentItem) return reply.status(404).send({ error: "Not found" });
|
|
244
|
+
const children = (storage.getCollection(child) ?? []).filter(
|
|
245
|
+
(item) => String(item[field]) === req.params.id
|
|
246
|
+
);
|
|
247
|
+
return children;
|
|
248
|
+
});
|
|
160
249
|
}
|
|
161
250
|
}
|
|
162
|
-
}
|
|
251
|
+
};
|
|
163
252
|
|
|
164
253
|
// src/router/resource.router.ts
|
|
165
|
-
function registerResourceRoutes(server, storage,
|
|
254
|
+
function registerResourceRoutes(server, storage, options) {
|
|
166
255
|
for (const resource of Object.keys(storage.getData())) {
|
|
167
|
-
const
|
|
168
|
-
registerCollectionRoutes(server, storage, resource,
|
|
169
|
-
registerItemRoutes(server, storage, resource,
|
|
256
|
+
const resourceBase = `${options.base}/${resource}`;
|
|
257
|
+
registerCollectionRoutes(server, storage, resource, resourceBase, options);
|
|
258
|
+
registerItemRoutes(server, storage, resource, resourceBase, options);
|
|
170
259
|
}
|
|
171
|
-
registerNestedRoutes(server, storage, storage.getRelations(), base);
|
|
260
|
+
registerNestedRoutes(server, storage, storage.getRelations(), options.base);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// src/router/templates/about.template.ts
|
|
264
|
+
var METHOD_COLOR = {
|
|
265
|
+
GET: "#3fb950",
|
|
266
|
+
POST: "#58a6ff",
|
|
267
|
+
PUT: "#d29922",
|
|
268
|
+
PATCH: "#a371f7",
|
|
269
|
+
DELETE: "#f85149"
|
|
270
|
+
};
|
|
271
|
+
function badge(label, color, bg) {
|
|
272
|
+
return `<span class="badge" style="background:${bg};color:${color};border:1px solid ${color}40">${label}</span>`;
|
|
273
|
+
}
|
|
274
|
+
function methodBadge(method) {
|
|
275
|
+
const color = METHOD_COLOR[method] ?? "#7d8590";
|
|
276
|
+
return badge(method, color, `${color}18`);
|
|
277
|
+
}
|
|
278
|
+
function endpointRow(method, path, desc) {
|
|
279
|
+
return `
|
|
280
|
+
<tr>
|
|
281
|
+
<td class="method-cell">${methodBadge(method)}</td>
|
|
282
|
+
<td class="path-cell"><code>${path}</code></td>
|
|
283
|
+
<td class="desc-cell">${desc}</td>
|
|
284
|
+
</tr>`;
|
|
285
|
+
}
|
|
286
|
+
function resourceAccordion(name, base, isOpen) {
|
|
287
|
+
const p = `${base}/${name}`;
|
|
288
|
+
const singular = name.endsWith("s") ? name.slice(0, -1) : name;
|
|
289
|
+
const rows = [
|
|
290
|
+
endpointRow(
|
|
291
|
+
"GET",
|
|
292
|
+
p,
|
|
293
|
+
`List all ${name}. Supports filters, sort, pagination and <code>?_expand</code>.`
|
|
294
|
+
),
|
|
295
|
+
endpointRow(
|
|
296
|
+
"POST",
|
|
297
|
+
p,
|
|
298
|
+
`Create a new ${singular}. Auto-assigns <code>id</code> if not provided.`
|
|
299
|
+
),
|
|
300
|
+
endpointRow("GET", `${p}/:id`, `Get a single ${singular} by id.`),
|
|
301
|
+
endpointRow(
|
|
302
|
+
"PUT",
|
|
303
|
+
`${p}/:id`,
|
|
304
|
+
`Fully replace a ${singular}. Original <code>id</code> is always preserved.`
|
|
305
|
+
),
|
|
306
|
+
endpointRow(
|
|
307
|
+
"PATCH",
|
|
308
|
+
`${p}/:id`,
|
|
309
|
+
`Partially update a ${singular} \u2014 only provided fields change.`
|
|
310
|
+
),
|
|
311
|
+
endpointRow("DELETE", `${p}/:id`, `Delete a ${singular} and return it as confirmation.`)
|
|
312
|
+
].join("");
|
|
313
|
+
return `
|
|
314
|
+
<details class="resource-card" ${isOpen ? "open" : ""}>
|
|
315
|
+
<summary>
|
|
316
|
+
<span class="resource-name">/${name}</span>
|
|
317
|
+
<span class="route-count">6 routes</span>
|
|
318
|
+
</summary>
|
|
319
|
+
<table>
|
|
320
|
+
<tbody>${rows}</tbody>
|
|
321
|
+
</table>
|
|
322
|
+
</details>`;
|
|
323
|
+
}
|
|
324
|
+
function examplesBlock(collections, relations, base, host, options) {
|
|
325
|
+
const examples = [];
|
|
326
|
+
const firstCol = collections[0];
|
|
327
|
+
if (firstCol) {
|
|
328
|
+
const p = `${host}${base}/${firstCol}`;
|
|
329
|
+
const singular = firstCol.endsWith("s") ? firstCol.slice(0, -1) : firstCol;
|
|
330
|
+
examples.push(
|
|
331
|
+
`# List all ${firstCol}
|
|
332
|
+
curl ${p}`,
|
|
333
|
+
`# Filter by field
|
|
334
|
+
curl "${p}?name=value"`,
|
|
335
|
+
`# Sort and paginate
|
|
336
|
+
curl "${p}?_sort=id&_order=desc&_page=1&_limit=5"`,
|
|
337
|
+
`# Get single ${singular}
|
|
338
|
+
curl ${p}/1`,
|
|
339
|
+
`# Create ${singular}
|
|
340
|
+
curl -X POST ${p} \\
|
|
341
|
+
-H "Content-Type: application/json" \\
|
|
342
|
+
-d '{"name":"example"}'`,
|
|
343
|
+
`# Partially update ${singular}
|
|
344
|
+
curl -X PATCH ${p}/1 \\
|
|
345
|
+
-H "Content-Type: application/json" \\
|
|
346
|
+
-d '{"name":"updated"}'`,
|
|
347
|
+
`# Delete ${singular}
|
|
348
|
+
curl -X DELETE ${p}/1`
|
|
349
|
+
);
|
|
350
|
+
}
|
|
351
|
+
const firstRel = Object.entries(relations)[0];
|
|
352
|
+
if (firstRel) {
|
|
353
|
+
const [child, fields] = firstRel;
|
|
354
|
+
const fk = Object.keys(fields)[0];
|
|
355
|
+
const expandKey = fk.replace(/Id$/i, "");
|
|
356
|
+
examples.push(
|
|
357
|
+
`# Embed parent with ?_expand
|
|
358
|
+
curl "${host}${base}/${child}/1?_expand=${expandKey}"`
|
|
359
|
+
);
|
|
360
|
+
}
|
|
361
|
+
for (const [child, fields] of Object.entries(relations)) {
|
|
362
|
+
for (const [, parent] of Object.entries(fields)) {
|
|
363
|
+
examples.push(`# Nested resource
|
|
364
|
+
curl ${host}${base}/${parent}/1/${child}`);
|
|
365
|
+
break;
|
|
366
|
+
}
|
|
367
|
+
break;
|
|
368
|
+
}
|
|
369
|
+
if (options.pageable.enabled && firstCol) {
|
|
370
|
+
examples.push(`# Pageable envelope
|
|
371
|
+
curl "${host}${base}/${firstCol}?_page=2"`);
|
|
372
|
+
}
|
|
373
|
+
const highlighted = examples.map((e) => e.replace(/^(#.+)$/gm, '<span class="cm">$1</span>')).join("\n\n");
|
|
374
|
+
return `<pre>${highlighted}</pre>`;
|
|
375
|
+
}
|
|
376
|
+
function generateAboutHtml(storage, options) {
|
|
377
|
+
const collections = Object.keys(storage.getData());
|
|
378
|
+
const relations = storage.getRelations();
|
|
379
|
+
const base = options.base;
|
|
380
|
+
const host = `http://${options.host}:${options.port}`;
|
|
381
|
+
const modes = [];
|
|
382
|
+
if (options.watch) modes.push(badge("watch", "#38bdf8", "#38bdf818"));
|
|
383
|
+
if (options.readonly) modes.push(badge("readonly", "#94a3b8", "#94a3b818"));
|
|
384
|
+
if (options.delay > 0) modes.push(badge(`delay \xB7 ${options.delay}ms`, "#fb923c", "#fb923c18"));
|
|
385
|
+
if (options.pageable.enabled)
|
|
386
|
+
modes.push(badge(`pageable \xB7 limit ${options.pageable.limit}`, "#34d399", "#34d39918"));
|
|
387
|
+
const accordions = collections.map((col, i) => resourceAccordion(col, base, i === 0)).join("");
|
|
388
|
+
const nestedRows = [];
|
|
389
|
+
for (const [child, fields] of Object.entries(relations)) {
|
|
390
|
+
for (const [, parent] of Object.entries(fields)) {
|
|
391
|
+
const nestedPath = `${base}/${parent}/:id/${child}`;
|
|
392
|
+
const parentSingular = parent.endsWith("s") ? parent.slice(0, -1) : parent;
|
|
393
|
+
nestedRows.push(
|
|
394
|
+
endpointRow("GET", nestedPath, `List ${child} belonging to a ${parentSingular}.`)
|
|
395
|
+
);
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
const nestedAccordion = nestedRows.length ? `
|
|
399
|
+
<details class="resource-card nested-card">
|
|
400
|
+
<summary>
|
|
401
|
+
<span class="resource-name">Nested routes</span>
|
|
402
|
+
<span class="route-count">${nestedRows.length} route${nestedRows.length !== 1 ? "s" : ""}</span>
|
|
403
|
+
</summary>
|
|
404
|
+
<table><tbody>${nestedRows.join("")}</tbody></table>
|
|
405
|
+
</details>` : "";
|
|
406
|
+
const paginationDesc = options.pageable.enabled ? `Pageable mode active \u2014 default limit <code>${options.pageable.limit}</code>. Response wrapped in <code>{ data, pagination }</code>.` : `Returns the requested slice. <code>X-Total-Count</code> header reflects the total before pagination.`;
|
|
407
|
+
return `<!DOCTYPE html>
|
|
408
|
+
<html lang="en">
|
|
409
|
+
<head>
|
|
410
|
+
<meta charset="UTF-8">
|
|
411
|
+
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
412
|
+
<title>yrest \u2014 API Overview</title>
|
|
413
|
+
<style>
|
|
414
|
+
:root {
|
|
415
|
+
--bg: #0d1117;
|
|
416
|
+
--bg-card: #161b22;
|
|
417
|
+
--bg-hover: #1c2128;
|
|
418
|
+
--bg-inset: #0d1117;
|
|
419
|
+
--border: #30363d;
|
|
420
|
+
--border-hi: #3d444d;
|
|
421
|
+
--text: #e6edf3;
|
|
422
|
+
--text-muted:#7d8590;
|
|
423
|
+
--accent: #58a6ff;
|
|
424
|
+
--radius: 8px;
|
|
425
|
+
}
|
|
426
|
+
* { box-sizing: border-box; margin: 0; padding: 0; }
|
|
427
|
+
body { background: var(--bg); color: var(--text); font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; font-size: 14px; line-height: 1.6; }
|
|
428
|
+
|
|
429
|
+
/* \u2500\u2500 Banner \u2500\u2500 */
|
|
430
|
+
.banner {
|
|
431
|
+
width: 100%;
|
|
432
|
+
background: linear-gradient(135deg, #0d1117 0%, #161b22 40%, #1a2332 100%);
|
|
433
|
+
border-bottom: 1px solid var(--border);
|
|
434
|
+
padding: 48px 32px 40px;
|
|
435
|
+
}
|
|
436
|
+
.banner-inner { max-width: 1100px; margin: 0 auto; }
|
|
437
|
+
.banner h1 { font-size: clamp(36px, 6vw, 60px); font-weight: 800; letter-spacing: -2px; line-height: 1; }
|
|
438
|
+
.banner h1 .y { color: var(--text); }
|
|
439
|
+
.banner h1 .rest { color: var(--accent); }
|
|
440
|
+
.banner p { color: var(--text-muted); margin-top: 10px; font-size: 15px; }
|
|
441
|
+
.banner-meta { display: flex; gap: 24px; margin-top: 20px; flex-wrap: wrap; }
|
|
442
|
+
.banner-meta span { color: var(--text-muted); font-size: 13px; }
|
|
443
|
+
.banner-meta span strong { color: var(--text); font-family: monospace; }
|
|
444
|
+
|
|
445
|
+
/* \u2500\u2500 Layout \u2500\u2500 */
|
|
446
|
+
.wrap { max-width: 1100px; margin: 0 auto; padding: 32px 24px 48px; }
|
|
447
|
+
h2 { font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: .08em; color: var(--text-muted); margin: 32px 0 12px; }
|
|
448
|
+
|
|
449
|
+
/* \u2500\u2500 Cards \u2500\u2500 */
|
|
450
|
+
.card { background: var(--bg-card); border: 1px solid var(--border); border-radius: var(--radius); padding: 20px 24px; }
|
|
451
|
+
.two-col { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
|
|
452
|
+
@media (max-width: 600px) { .two-col { grid-template-columns: 1fr; } }
|
|
453
|
+
|
|
454
|
+
/* \u2500\u2500 Server info grid \u2500\u2500 */
|
|
455
|
+
.info-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 16px; }
|
|
456
|
+
.stat label { font-size: 10px; text-transform: uppercase; letter-spacing: .07em; color: var(--text-muted); display: block; margin-bottom: 3px; }
|
|
457
|
+
.stat value { font-size: 15px; font-weight: 600; font-family: monospace; color: var(--text); }
|
|
458
|
+
|
|
459
|
+
/* \u2500\u2500 Mode badges \u2500\u2500 */
|
|
460
|
+
.modes { display: flex; gap: 8px; flex-wrap: wrap; min-height: 28px; align-items: center; }
|
|
461
|
+
.badge { display: inline-block; padding: 3px 10px; border-radius: 20px; font-size: 12px; font-weight: 600; white-space: nowrap; }
|
|
462
|
+
|
|
463
|
+
/* \u2500\u2500 Endpoints grid (2 cols on wide, 1 col on narrow) \u2500\u2500 */
|
|
464
|
+
.endpoints-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px; }
|
|
465
|
+
@media (max-width: 860px) { .endpoints-grid { grid-template-columns: 1fr; } }
|
|
466
|
+
.nested-card { grid-column: 1 / -1; }
|
|
467
|
+
|
|
468
|
+
/* \u2500\u2500 Accordion (details/summary) \u2500\u2500 */
|
|
469
|
+
.resource-card {
|
|
470
|
+
background: var(--bg-card);
|
|
471
|
+
border: 1px solid var(--border);
|
|
472
|
+
border-radius: var(--radius);
|
|
473
|
+
overflow: hidden;
|
|
474
|
+
transition: border-color .15s;
|
|
475
|
+
}
|
|
476
|
+
.resource-card[open] { border-color: var(--border-hi); }
|
|
477
|
+
.resource-card summary {
|
|
478
|
+
display: flex;
|
|
479
|
+
align-items: center;
|
|
480
|
+
justify-content: space-between;
|
|
481
|
+
padding: 13px 18px;
|
|
482
|
+
cursor: pointer;
|
|
483
|
+
user-select: none;
|
|
484
|
+
list-style: none;
|
|
485
|
+
gap: 8px;
|
|
486
|
+
}
|
|
487
|
+
.resource-card summary::-webkit-details-marker { display: none; }
|
|
488
|
+
.resource-card summary::before {
|
|
489
|
+
content: "\u203A";
|
|
490
|
+
color: var(--text-muted);
|
|
491
|
+
font-size: 18px;
|
|
492
|
+
line-height: 1;
|
|
493
|
+
transition: transform .2s;
|
|
494
|
+
margin-right: 4px;
|
|
495
|
+
flex-shrink: 0;
|
|
496
|
+
}
|
|
497
|
+
.resource-card[open] summary::before { transform: rotate(90deg); }
|
|
498
|
+
.resource-card summary:hover { background: var(--bg-hover); }
|
|
499
|
+
.resource-name { font-family: monospace; font-size: 14px; font-weight: 600; color: var(--accent); flex: 1; }
|
|
500
|
+
.route-count { font-size: 11px; color: var(--text-muted); background: var(--bg-inset); border: 1px solid var(--border); padding: 2px 8px; border-radius: 12px; white-space: nowrap; }
|
|
501
|
+
|
|
502
|
+
/* \u2500\u2500 Tables \u2500\u2500 */
|
|
503
|
+
table { width: 100%; border-collapse: collapse; }
|
|
504
|
+
td { padding: 8px 12px; border-top: 1px solid var(--border); vertical-align: top; font-size: 13px; }
|
|
505
|
+
.method-cell { width: 78px; white-space: nowrap; }
|
|
506
|
+
.path-cell { width: 44%; white-space: nowrap; }
|
|
507
|
+
.desc-cell { color: var(--text-muted); }
|
|
508
|
+
code { font-family: "SF Mono", "Fira Code", monospace; font-size: 12px; background: #58a6ff15; color: var(--accent); padding: 1px 5px; border-radius: 3px; }
|
|
509
|
+
|
|
510
|
+
/* \u2500\u2500 Query params table \u2500\u2500 */
|
|
511
|
+
.param-table th { text-align: left; padding: 8px 12px; font-size: 10px; text-transform: uppercase; letter-spacing: .06em; color: var(--text-muted); border-bottom: 1px solid var(--border); }
|
|
512
|
+
.param-table td:first-child { white-space: nowrap; width: 160px; }
|
|
513
|
+
.param-table td:nth-child(2) { white-space: nowrap; width: 200px; }
|
|
514
|
+
|
|
515
|
+
/* \u2500\u2500 Code block \u2500\u2500 */
|
|
516
|
+
pre { background: #010409; border: 1px solid var(--border); color: #e6edf3; padding: 20px 24px; border-radius: var(--radius); font-size: 12.5px; line-height: 1.8; overflow-x: auto; font-family: "SF Mono", "Fira Code", monospace; }
|
|
517
|
+
.cm { color: #3d444d; }
|
|
518
|
+
|
|
519
|
+
/* \u2500\u2500 Warning \u2500\u2500 */
|
|
520
|
+
.warn { background: #2d1f0e; border-left: 3px solid #d29922; padding: 10px 14px; border-radius: 0 6px 6px 0; font-size: 13px; color: #d29922; margin-top: 12px; }
|
|
521
|
+
|
|
522
|
+
/* \u2500\u2500 Footer \u2500\u2500 */
|
|
523
|
+
footer { margin-top: 48px; text-align: center; font-size: 11px; color: var(--text-muted); padding-bottom: 16px; }
|
|
524
|
+
footer a { color: var(--accent); text-decoration: none; }
|
|
525
|
+
</style>
|
|
526
|
+
</head>
|
|
527
|
+
<body>
|
|
528
|
+
|
|
529
|
+
<div class="banner">
|
|
530
|
+
<div class="banner-inner">
|
|
531
|
+
<h1><span class="y">y</span><span class="rest">rest</span></h1>
|
|
532
|
+
<p>Zero-config REST API mock server</p>
|
|
533
|
+
<div class="banner-meta">
|
|
534
|
+
<span>URL <strong>${host}</strong></span>
|
|
535
|
+
<span>Base <strong>${base || "/"}</strong></span>
|
|
536
|
+
<span>File <strong>${options.file}</strong></span>
|
|
537
|
+
<span>Collections <strong>${collections.length}</strong></span>
|
|
538
|
+
</div>
|
|
539
|
+
</div>
|
|
540
|
+
</div>
|
|
541
|
+
|
|
542
|
+
<div class="wrap">
|
|
543
|
+
|
|
544
|
+
<h2>Active Modes</h2>
|
|
545
|
+
<div class="card">
|
|
546
|
+
<div class="modes">${modes.length ? modes.join(" ") : `<span style="color:var(--text-muted);font-size:13px">none</span>`}</div>
|
|
547
|
+
${options.watch ? `<div class="warn">\u26A0 <strong>Watch mode:</strong> data changes in existing collections reload automatically. Adding or removing entire collections requires a server restart.</div>` : ""}
|
|
548
|
+
</div>
|
|
549
|
+
|
|
550
|
+
<h2>Endpoints</h2>
|
|
551
|
+
<div class="endpoints-grid">
|
|
552
|
+
${accordions}
|
|
553
|
+
${nestedAccordion}
|
|
554
|
+
</div>
|
|
555
|
+
|
|
556
|
+
<h2>Query Parameters</h2>
|
|
557
|
+
<div class="card">
|
|
558
|
+
<table class="param-table">
|
|
559
|
+
<thead><tr><th>Param</th><th>Example</th><th>Description</th></tr></thead>
|
|
560
|
+
<tbody>
|
|
561
|
+
<tr><td><code>?field=value</code></td><td><code>?name=Ana&role=admin</code></td><td>Filter by any field. Multiple params are ANDed.</td></tr>
|
|
562
|
+
<tr><td><code>?_sort & ?_order</code></td><td><code>?_sort=name&_order=desc</code></td><td>Sort by field. <code>_order</code>: <code>asc</code> (default) or <code>desc</code>.</td></tr>
|
|
563
|
+
<tr><td><code>?_page & ?_limit</code></td><td><code>?_page=2&_limit=10</code></td><td>${paginationDesc}</td></tr>
|
|
564
|
+
<tr><td><code>?_expand</code></td><td><code>?_expand=user</code></td><td>Embed a related parent object inline. Requires <code>_rel</code> in the YAML file.</td></tr>
|
|
565
|
+
</tbody>
|
|
566
|
+
</table>
|
|
567
|
+
</div>
|
|
568
|
+
|
|
569
|
+
${collections.length ? `<h2>Examples</h2><div class="card">${examplesBlock(collections, relations, base, host, options)}</div>` : ""}
|
|
570
|
+
|
|
571
|
+
<footer>
|
|
572
|
+
Powered by <a href="https://github.com/aggiovato/yaml-rest" target="_blank">@aggiovato/yrest</a> \xB7 <a href="/_about">/_about</a>
|
|
573
|
+
</footer>
|
|
574
|
+
|
|
575
|
+
</div>
|
|
576
|
+
</body>
|
|
577
|
+
</html>`;
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
// src/router/routes/about.routes.ts
|
|
581
|
+
function registerAboutRoute(server, storage, options) {
|
|
582
|
+
server.get("/_about", (_req, reply) => {
|
|
583
|
+
reply.header("Content-Type", "text/html; charset=utf-8");
|
|
584
|
+
return reply.send(generateAboutHtml(storage, options));
|
|
585
|
+
});
|
|
172
586
|
}
|
|
173
587
|
|
|
174
588
|
// src/server/createServer.ts
|
|
589
|
+
var MUTATING_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
|
|
175
590
|
async function createServer(storage, options) {
|
|
176
591
|
const server = Fastify();
|
|
177
592
|
await server.register(cors);
|
|
178
|
-
|
|
593
|
+
if (options.readonly) {
|
|
594
|
+
server.addHook("onRequest", (_req, reply, done) => {
|
|
595
|
+
if (MUTATING_METHODS.has(_req.method)) {
|
|
596
|
+
reply.status(405).header("Allow", "GET, HEAD, OPTIONS").send({ error: "Server is running in readonly mode" });
|
|
597
|
+
}
|
|
598
|
+
done();
|
|
599
|
+
});
|
|
600
|
+
}
|
|
601
|
+
if (options.delay > 0) {
|
|
602
|
+
server.addHook("onSend", (_req, _reply, payload, done) => {
|
|
603
|
+
setTimeout(() => done(null, payload), options.delay);
|
|
604
|
+
});
|
|
605
|
+
}
|
|
606
|
+
registerAboutRoute(server, storage, options);
|
|
607
|
+
registerResourceRoutes(server, storage, options);
|
|
179
608
|
return server;
|
|
180
609
|
}
|
|
181
610
|
|
|
182
611
|
// src/config/loadOptions.ts
|
|
183
612
|
import { z } from "zod";
|
|
184
613
|
var serverOptionsSchema = z.object({
|
|
614
|
+
/** Path to the YAML database file. Must be a non-empty string. */
|
|
185
615
|
file: z.string().min(1),
|
|
616
|
+
/** TCP port the server listens on. Accepts string input and coerces to number. */
|
|
186
617
|
port: z.coerce.number().int().positive().default(3070),
|
|
618
|
+
/** Hostname or IP address to bind. */
|
|
187
619
|
host: z.string().default("localhost"),
|
|
188
|
-
|
|
620
|
+
/**
|
|
621
|
+
* URL prefix prepended to every route (e.g. `/api`).
|
|
622
|
+
* A leading slash is added automatically if omitted.
|
|
623
|
+
*/
|
|
624
|
+
base: z.string().default("").transform((v) => v && !v.startsWith("/") ? `/${v}` : v),
|
|
625
|
+
/** When `true`, the server reloads the YAML file automatically on disk changes. */
|
|
626
|
+
watch: z.boolean().default(false),
|
|
627
|
+
/** When `true`, all mutating requests (POST, PUT, PATCH, DELETE) are rejected with 405. */
|
|
628
|
+
readonly: z.boolean().default(false),
|
|
629
|
+
/** Milliseconds to delay every response, simulating network latency. `0` = disabled. */
|
|
630
|
+
delay: z.coerce.number().int().min(0).default(0),
|
|
631
|
+
/**
|
|
632
|
+
* Wraps GET collection responses in a `{ data, pagination }` envelope.
|
|
633
|
+
* Accepts `true` (default limit 10), `false` (disabled), or a positive integer (custom limit).
|
|
634
|
+
*/
|
|
635
|
+
pageable: z.union([z.boolean(), z.coerce.number().int().positive()]).default(false).transform((v) => ({
|
|
636
|
+
enabled: v !== false,
|
|
637
|
+
limit: v === false || v === true ? 10 : v
|
|
638
|
+
}))
|
|
189
639
|
});
|
|
190
640
|
export {
|
|
191
641
|
createServer,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aggiovato/yrest",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.1",
|
|
4
4
|
"description": "Zero-config REST API mock server powered by a YAML file",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"yaml",
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
"author": "Aggiovato",
|
|
15
15
|
"repository": {
|
|
16
16
|
"type": "git",
|
|
17
|
-
"url": "https://github.com/aggiovato/yaml-rest.git"
|
|
17
|
+
"url": "git+https://github.com/aggiovato/yaml-rest.git"
|
|
18
18
|
},
|
|
19
19
|
"main": "./dist/index.js",
|
|
20
20
|
"module": "./dist/index.mjs",
|
|
@@ -38,7 +38,11 @@
|
|
|
38
38
|
"test": "vitest",
|
|
39
39
|
"test:run": "vitest run",
|
|
40
40
|
"typecheck": "tsc --noEmit",
|
|
41
|
-
"
|
|
41
|
+
"lint": "eslint src tests",
|
|
42
|
+
"lint:fix": "eslint src tests --fix",
|
|
43
|
+
"format": "prettier --write .",
|
|
44
|
+
"format:check": "prettier --check .",
|
|
45
|
+
"prepublishOnly": "npm run test:run && npm run build"
|
|
42
46
|
},
|
|
43
47
|
"dependencies": {
|
|
44
48
|
"@fastify/cors": "^10.0.0",
|
|
@@ -48,9 +52,14 @@
|
|
|
48
52
|
"zod": "^3.23.8"
|
|
49
53
|
},
|
|
50
54
|
"devDependencies": {
|
|
51
|
-
"@
|
|
55
|
+
"@eslint/js": "^10.0.1",
|
|
56
|
+
"@types/node": "^22.19.20",
|
|
57
|
+
"eslint": "^10.4.1",
|
|
58
|
+
"eslint-config-prettier": "^10.1.8",
|
|
59
|
+
"prettier": "^3.8.3",
|
|
52
60
|
"tsup": "^8.1.0",
|
|
53
61
|
"typescript": "^5.5.0",
|
|
62
|
+
"typescript-eslint": "^8.60.1",
|
|
54
63
|
"vitest": "^4.1.8"
|
|
55
64
|
},
|
|
56
65
|
"engines": {
|