@atscript/moost-db 0.1.32
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/LICENSE +21 -0
- package/dist/index.cjs +427 -0
- package/dist/index.d.ts +137 -0
- package/dist/index.mjs +394 -0
- package/package.json +58 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Atscript
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,427 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
//#region rolldown:runtime
|
|
3
|
+
var __create = Object.create;
|
|
4
|
+
var __defProp = Object.defineProperty;
|
|
5
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
6
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
7
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
8
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
9
|
+
var __copyProps = (to, from, except, desc) => {
|
|
10
|
+
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
|
|
11
|
+
key = keys[i];
|
|
12
|
+
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
|
|
13
|
+
get: ((k) => from[k]).bind(null, key),
|
|
14
|
+
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
return to;
|
|
18
|
+
};
|
|
19
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
|
|
20
|
+
value: mod,
|
|
21
|
+
enumerable: true
|
|
22
|
+
}) : target, mod));
|
|
23
|
+
|
|
24
|
+
//#endregion
|
|
25
|
+
const __atscript_typescript_utils = __toESM(require("@atscript/typescript/utils"));
|
|
26
|
+
const __moostjs_event_http = __toESM(require("@moostjs/event-http"));
|
|
27
|
+
const moost = __toESM(require("moost"));
|
|
28
|
+
const __uniqu_url = __toESM(require("@uniqu/url"));
|
|
29
|
+
|
|
30
|
+
//#region packages/moost-db/src/decorators.ts
|
|
31
|
+
const TABLE_DEF = "__atscript_db_table_def";
|
|
32
|
+
const TableController = (table, prefix) => (0, moost.ApplyDecorators)((0, moost.Provide)(TABLE_DEF, () => table), (0, moost.Controller)(prefix || table.tableName), (0, moost.Inherit)());
|
|
33
|
+
|
|
34
|
+
//#endregion
|
|
35
|
+
//#region packages/moost-db/src/validation-interceptor.ts
|
|
36
|
+
function transformValidationError(error, reply) {
|
|
37
|
+
if (error instanceof __atscript_typescript_utils.ValidatorError) reply(new __moostjs_event_http.HttpError(400, {
|
|
38
|
+
message: error.message,
|
|
39
|
+
statusCode: 400,
|
|
40
|
+
errors: error.errors
|
|
41
|
+
}));
|
|
42
|
+
}
|
|
43
|
+
const validationErrorTransform = () => (0, moost.defineInterceptor)({ error: transformValidationError }, moost.TInterceptorPriority.CATCH_ERROR);
|
|
44
|
+
const UseValidationErrorTransform = () => (0, moost.Intercept)(validationErrorTransform());
|
|
45
|
+
|
|
46
|
+
//#endregion
|
|
47
|
+
//#region packages/moost-db/src/dto/controls.dto.as.js
|
|
48
|
+
function _define_property$1(obj, key, value) {
|
|
49
|
+
if (key in obj) Object.defineProperty(obj, key, {
|
|
50
|
+
value,
|
|
51
|
+
enumerable: true,
|
|
52
|
+
configurable: true,
|
|
53
|
+
writable: true
|
|
54
|
+
});
|
|
55
|
+
else obj[key] = value;
|
|
56
|
+
return obj;
|
|
57
|
+
}
|
|
58
|
+
var QueryControlsDto = class {
|
|
59
|
+
static toJsonSchema() {
|
|
60
|
+
(0, __atscript_typescript_utils.throwFeatureDisabled)("JSON Schema", "jsonSchema", "emit.jsonSchema");
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
_define_property$1(QueryControlsDto, "__is_atscript_annotated_type", true);
|
|
64
|
+
_define_property$1(QueryControlsDto, "type", {});
|
|
65
|
+
_define_property$1(QueryControlsDto, "metadata", new Map());
|
|
66
|
+
_define_property$1(QueryControlsDto, "id", "QueryControlsDto");
|
|
67
|
+
var PagesControlsDto = class {
|
|
68
|
+
static toJsonSchema() {
|
|
69
|
+
(0, __atscript_typescript_utils.throwFeatureDisabled)("JSON Schema", "jsonSchema", "emit.jsonSchema");
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
_define_property$1(PagesControlsDto, "__is_atscript_annotated_type", true);
|
|
73
|
+
_define_property$1(PagesControlsDto, "type", {});
|
|
74
|
+
_define_property$1(PagesControlsDto, "metadata", new Map());
|
|
75
|
+
_define_property$1(PagesControlsDto, "id", "PagesControlsDto");
|
|
76
|
+
var GetOneControlsDto = class {
|
|
77
|
+
static toJsonSchema() {
|
|
78
|
+
(0, __atscript_typescript_utils.throwFeatureDisabled)("JSON Schema", "jsonSchema", "emit.jsonSchema");
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
_define_property$1(GetOneControlsDto, "__is_atscript_annotated_type", true);
|
|
82
|
+
_define_property$1(GetOneControlsDto, "type", {});
|
|
83
|
+
_define_property$1(GetOneControlsDto, "metadata", new Map());
|
|
84
|
+
_define_property$1(GetOneControlsDto, "id", "GetOneControlsDto");
|
|
85
|
+
let SortControlDto = class SortControlDto$1 {
|
|
86
|
+
static toJsonSchema() {
|
|
87
|
+
(0, __atscript_typescript_utils.throwFeatureDisabled)("JSON Schema", "jsonSchema", "emit.jsonSchema");
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
_define_property$1(SortControlDto, "__is_atscript_annotated_type", true);
|
|
91
|
+
_define_property$1(SortControlDto, "type", {});
|
|
92
|
+
_define_property$1(SortControlDto, "metadata", new Map());
|
|
93
|
+
_define_property$1(SortControlDto, "id", "SortControlDto");
|
|
94
|
+
let SelectControlDto = class SelectControlDto$1 {
|
|
95
|
+
static toJsonSchema() {
|
|
96
|
+
(0, __atscript_typescript_utils.throwFeatureDisabled)("JSON Schema", "jsonSchema", "emit.jsonSchema");
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
_define_property$1(SelectControlDto, "__is_atscript_annotated_type", true);
|
|
100
|
+
_define_property$1(SelectControlDto, "type", {});
|
|
101
|
+
_define_property$1(SelectControlDto, "metadata", new Map());
|
|
102
|
+
_define_property$1(SelectControlDto, "id", "SelectControlDto");
|
|
103
|
+
(0, __atscript_typescript_utils.defineAnnotatedType)("object", QueryControlsDto).prop("$skip", (0, __atscript_typescript_utils.defineAnnotatedType)().designType("number").tags("positive", "int", "number").annotate("expect.int", true).annotate("expect.min", { minValue: 0 }).optional().$type).prop("$limit", (0, __atscript_typescript_utils.defineAnnotatedType)().designType("number").tags("positive", "int", "number").annotate("expect.int", true).annotate("expect.min", { minValue: 0 }).optional().$type).prop("$count", (0, __atscript_typescript_utils.defineAnnotatedType)().designType("boolean").tags("boolean").optional().$type).prop("$sort", (0, __atscript_typescript_utils.defineAnnotatedType)().refTo(SortControlDto).optional().$type).prop("$select", (0, __atscript_typescript_utils.defineAnnotatedType)("union").item((0, __atscript_typescript_utils.defineAnnotatedType)().refTo(SelectControlDto).$type).item((0, __atscript_typescript_utils.defineAnnotatedType)("array").of((0, __atscript_typescript_utils.defineAnnotatedType)().designType("string").tags("string").$type).$type).optional().$type).prop("$search", (0, __atscript_typescript_utils.defineAnnotatedType)().designType("string").tags("string").optional().$type).prop("$index", (0, __atscript_typescript_utils.defineAnnotatedType)().designType("string").tags("string").optional().$type);
|
|
104
|
+
(0, __atscript_typescript_utils.defineAnnotatedType)("object", PagesControlsDto).prop("$page", (0, __atscript_typescript_utils.defineAnnotatedType)().designType("string").tags("string").annotate("expect.pattern", {
|
|
105
|
+
pattern: "^\\d+$",
|
|
106
|
+
flags: "u",
|
|
107
|
+
message: "Expected positive number"
|
|
108
|
+
}, true).optional().$type).prop("$size", (0, __atscript_typescript_utils.defineAnnotatedType)().designType("string").tags("string").annotate("expect.pattern", {
|
|
109
|
+
pattern: "^\\d+$",
|
|
110
|
+
flags: "u",
|
|
111
|
+
message: "Expected positive number"
|
|
112
|
+
}, true).optional().$type).prop("$sort", (0, __atscript_typescript_utils.defineAnnotatedType)().refTo(SortControlDto).optional().$type).prop("$select", (0, __atscript_typescript_utils.defineAnnotatedType)("union").item((0, __atscript_typescript_utils.defineAnnotatedType)().refTo(SelectControlDto).$type).item((0, __atscript_typescript_utils.defineAnnotatedType)("array").of((0, __atscript_typescript_utils.defineAnnotatedType)().designType("string").tags("string").$type).$type).optional().$type).prop("$search", (0, __atscript_typescript_utils.defineAnnotatedType)().designType("string").tags("string").optional().$type).prop("$index", (0, __atscript_typescript_utils.defineAnnotatedType)().designType("string").tags("string").optional().$type);
|
|
113
|
+
(0, __atscript_typescript_utils.defineAnnotatedType)("object", GetOneControlsDto).prop("$select", (0, __atscript_typescript_utils.defineAnnotatedType)("union").item((0, __atscript_typescript_utils.defineAnnotatedType)().refTo(SelectControlDto).$type).item((0, __atscript_typescript_utils.defineAnnotatedType)("array").of((0, __atscript_typescript_utils.defineAnnotatedType)().designType("string").tags("string").$type).$type).optional().$type);
|
|
114
|
+
(0, __atscript_typescript_utils.defineAnnotatedType)("object", SortControlDto).propPattern(/./, (0, __atscript_typescript_utils.defineAnnotatedType)("union").item((0, __atscript_typescript_utils.defineAnnotatedType)().designType("number").value(1).$type).item((0, __atscript_typescript_utils.defineAnnotatedType)().designType("number").value(-1).$type).$type);
|
|
115
|
+
(0, __atscript_typescript_utils.defineAnnotatedType)("object", SelectControlDto).propPattern(/./, (0, __atscript_typescript_utils.defineAnnotatedType)("union").item((0, __atscript_typescript_utils.defineAnnotatedType)().designType("number").value(1).$type).item((0, __atscript_typescript_utils.defineAnnotatedType)().designType("number").value(0).$type).$type);
|
|
116
|
+
|
|
117
|
+
//#endregion
|
|
118
|
+
//#region packages/moost-db/src/as-db.controller.ts
|
|
119
|
+
function _define_property(obj, key, value) {
|
|
120
|
+
if (key in obj) Object.defineProperty(obj, key, {
|
|
121
|
+
value,
|
|
122
|
+
enumerable: true,
|
|
123
|
+
configurable: true,
|
|
124
|
+
writable: true
|
|
125
|
+
});
|
|
126
|
+
else obj[key] = value;
|
|
127
|
+
return obj;
|
|
128
|
+
}
|
|
129
|
+
function _ts_decorate(decorators, target, key, desc) {
|
|
130
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
131
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
132
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
133
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
134
|
+
}
|
|
135
|
+
function _ts_metadata(k, v) {
|
|
136
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
137
|
+
}
|
|
138
|
+
function _ts_param(paramIndex, decorator) {
|
|
139
|
+
return function(target, key) {
|
|
140
|
+
decorator(target, key, paramIndex);
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
var AsDbController = class {
|
|
144
|
+
/**
|
|
145
|
+
* One-time initialization hook. Override to seed data, register watchers, etc.
|
|
146
|
+
*/ init() {}
|
|
147
|
+
get queryControlsValidator() {
|
|
148
|
+
if (!this._queryControlsValidator) this._queryControlsValidator = QueryControlsDto.validator();
|
|
149
|
+
return this._queryControlsValidator;
|
|
150
|
+
}
|
|
151
|
+
get pagesControlsValidator() {
|
|
152
|
+
if (!this._pagesControlsValidator) this._pagesControlsValidator = PagesControlsDto.validator();
|
|
153
|
+
return this._pagesControlsValidator;
|
|
154
|
+
}
|
|
155
|
+
get getOneControlsValidator() {
|
|
156
|
+
if (!this._getOneControlsValidator) this._getOneControlsValidator = GetOneControlsDto.validator();
|
|
157
|
+
return this._getOneControlsValidator;
|
|
158
|
+
}
|
|
159
|
+
validateControls(controls, type) {
|
|
160
|
+
const v = type === "query" ? this.queryControlsValidator : type === "pages" ? this.pagesControlsValidator : this.getOneControlsValidator;
|
|
161
|
+
if (!v.validate(controls, true)) return v.errors[0]?.message || "Invalid controls";
|
|
162
|
+
return undefined;
|
|
163
|
+
}
|
|
164
|
+
validateInsights(insights) {
|
|
165
|
+
for (const key of insights.keys()) if (!this.table.flatMap.has(key)) return `Unknown field "${key}"`;
|
|
166
|
+
return undefined;
|
|
167
|
+
}
|
|
168
|
+
validateParsed(parsed, type) {
|
|
169
|
+
const controlsError = this.validateControls(parsed.controls, type);
|
|
170
|
+
if (controlsError) return new __moostjs_event_http.HttpError(400, controlsError);
|
|
171
|
+
if (parsed.insights) {
|
|
172
|
+
const insightsError = this.validateInsights(parsed.insights);
|
|
173
|
+
if (insightsError) return new __moostjs_event_http.HttpError(400, insightsError);
|
|
174
|
+
}
|
|
175
|
+
return undefined;
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* Transform filter before querying. Override to add tenant filtering, etc.
|
|
179
|
+
*/ transformFilter(filter) {
|
|
180
|
+
return filter;
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Transform projection before querying.
|
|
184
|
+
*/ transformProjection(projection) {
|
|
185
|
+
return projection;
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* Intercepts write operations. Return `undefined` to abort.
|
|
189
|
+
*/ onWrite(action, data) {
|
|
190
|
+
return data;
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Intercepts delete operations. Return `undefined` to abort.
|
|
194
|
+
*/ onRemove(id) {
|
|
195
|
+
return id;
|
|
196
|
+
}
|
|
197
|
+
parseQueryString(url) {
|
|
198
|
+
const idx = url.indexOf("?");
|
|
199
|
+
return (0, __uniqu_url.parseUrl)(idx >= 0 ? url.slice(idx + 1) : "");
|
|
200
|
+
}
|
|
201
|
+
async returnOne(result) {
|
|
202
|
+
const item = await result;
|
|
203
|
+
if (!item) return new __moostjs_event_http.HttpError(404);
|
|
204
|
+
return item;
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* **GET /query** — returns an array of records or a count.
|
|
208
|
+
*/ async query(url) {
|
|
209
|
+
const parsed = this.parseQueryString(url);
|
|
210
|
+
const error = this.validateParsed(parsed, "query");
|
|
211
|
+
if (error) return error;
|
|
212
|
+
const controls = parsed.controls;
|
|
213
|
+
const filter = this.transformFilter(parsed.filter);
|
|
214
|
+
const select = this.transformProjection(controls.$select);
|
|
215
|
+
if (controls.$count) return this.table.count({
|
|
216
|
+
filter,
|
|
217
|
+
controls: {
|
|
218
|
+
...controls,
|
|
219
|
+
$select: select
|
|
220
|
+
}
|
|
221
|
+
});
|
|
222
|
+
const searchTerm = controls.$search;
|
|
223
|
+
const indexName = controls.$index;
|
|
224
|
+
if (searchTerm && this.table.isSearchable()) return this.table.search(searchTerm, {
|
|
225
|
+
filter,
|
|
226
|
+
controls: {
|
|
227
|
+
...controls,
|
|
228
|
+
$select: select,
|
|
229
|
+
$limit: controls.$limit || 1e3
|
|
230
|
+
}
|
|
231
|
+
}, indexName);
|
|
232
|
+
return this.table.findMany({
|
|
233
|
+
filter,
|
|
234
|
+
controls: {
|
|
235
|
+
...controls,
|
|
236
|
+
$select: select,
|
|
237
|
+
$limit: controls.$limit || 1e3
|
|
238
|
+
}
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* **GET /pages** — returns paginated records with metadata.
|
|
243
|
+
*/ async pages(url) {
|
|
244
|
+
const parsed = this.parseQueryString(url);
|
|
245
|
+
const error = this.validateParsed(parsed, "pages");
|
|
246
|
+
if (error) return error;
|
|
247
|
+
const controls = parsed.controls;
|
|
248
|
+
const page = Math.max(Number(controls.$page || 1), 1);
|
|
249
|
+
const size = Math.max(Number(controls.$size || 10), 1);
|
|
250
|
+
const skip = (page - 1) * size;
|
|
251
|
+
const filter = this.transformFilter(parsed.filter);
|
|
252
|
+
const select = this.transformProjection(controls.$select);
|
|
253
|
+
const searchTerm = controls.$search;
|
|
254
|
+
const indexName = controls.$index;
|
|
255
|
+
const query = {
|
|
256
|
+
filter,
|
|
257
|
+
controls: {
|
|
258
|
+
...controls,
|
|
259
|
+
$select: select,
|
|
260
|
+
$skip: skip,
|
|
261
|
+
$limit: size
|
|
262
|
+
}
|
|
263
|
+
};
|
|
264
|
+
let result;
|
|
265
|
+
if (searchTerm && this.table.isSearchable()) result = await this.table.searchWithCount(searchTerm, query, indexName);
|
|
266
|
+
else result = await this.table.findManyWithCount(query);
|
|
267
|
+
return {
|
|
268
|
+
data: result.data,
|
|
269
|
+
page,
|
|
270
|
+
itemsPerPage: size,
|
|
271
|
+
pages: Math.ceil(result.count / size),
|
|
272
|
+
count: result.count
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
/**
|
|
276
|
+
* **GET /one/:id** — retrieves a single record by ID or unique property.
|
|
277
|
+
*/ async getOne(id, url) {
|
|
278
|
+
const parsed = this.parseQueryString(url);
|
|
279
|
+
if (Object.keys(parsed.filter).length > 0) return new __moostjs_event_http.HttpError(400, "Filtering is not allowed for \"one\" endpoint");
|
|
280
|
+
const error = this.validateParsed(parsed, "getOne");
|
|
281
|
+
if (error) return error;
|
|
282
|
+
const select = this.transformProjection(parsed.controls.$select);
|
|
283
|
+
return this.returnOne(this.table.findById(id, { $select: select }));
|
|
284
|
+
}
|
|
285
|
+
/**
|
|
286
|
+
* **POST /** — inserts one or many records.
|
|
287
|
+
*/ async insert(payload) {
|
|
288
|
+
const arr = Array.isArray(payload) ? payload : [payload];
|
|
289
|
+
if (arr.length === 1) {
|
|
290
|
+
const data$1 = await this.onWrite("insert", arr[0]);
|
|
291
|
+
if (data$1 === undefined) return new __moostjs_event_http.HttpError(500, "Not saved");
|
|
292
|
+
return await this.table.insertOne(data$1);
|
|
293
|
+
}
|
|
294
|
+
const data = await this.onWrite("insertMany", arr);
|
|
295
|
+
if (data === undefined) return new __moostjs_event_http.HttpError(500, "Not saved");
|
|
296
|
+
return await this.table.insertMany(data);
|
|
297
|
+
}
|
|
298
|
+
/**
|
|
299
|
+
* **PUT /** — fully replaces a record matched by primary key.
|
|
300
|
+
*/ async replace(payload) {
|
|
301
|
+
const data = await this.onWrite("replace", payload);
|
|
302
|
+
if (data === undefined) return new __moostjs_event_http.HttpError(500, "Not saved");
|
|
303
|
+
return await this.table.replaceOne(data);
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* **PATCH /** — partially updates a record matched by primary key.
|
|
307
|
+
*/ async update(payload) {
|
|
308
|
+
const data = await this.onWrite("update", payload);
|
|
309
|
+
if (data === undefined) return new __moostjs_event_http.HttpError(500, "Not saved");
|
|
310
|
+
return await this.table.updateOne(data);
|
|
311
|
+
}
|
|
312
|
+
/**
|
|
313
|
+
* **DELETE /:id** — removes a single record by primary key.
|
|
314
|
+
*/ async remove(id) {
|
|
315
|
+
const resolvedId = await this.onRemove(id);
|
|
316
|
+
if (resolvedId === undefined) return new __moostjs_event_http.HttpError(500, "Not deleted");
|
|
317
|
+
const result = await this.table.deleteOne(resolvedId);
|
|
318
|
+
if (result.deletedCount < 1) return new __moostjs_event_http.HttpError(404);
|
|
319
|
+
return result;
|
|
320
|
+
}
|
|
321
|
+
/**
|
|
322
|
+
* **GET /meta** — returns table metadata for UI.
|
|
323
|
+
*/ meta() {
|
|
324
|
+
return {
|
|
325
|
+
searchable: this.table.isSearchable(),
|
|
326
|
+
searchIndexes: this._searchIndexes,
|
|
327
|
+
type: this._serializedType
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
constructor(table, app) {
|
|
331
|
+
/** Reference to the underlying table. */ _define_property(this, "table", void 0);
|
|
332
|
+
/** Application-scoped logger. */ _define_property(this, "logger", void 0);
|
|
333
|
+
/** Cached serialized type definition (static, computed once). */ _define_property(this, "_serializedType", void 0);
|
|
334
|
+
/** Cached search index list (static, computed once). */ _define_property(this, "_searchIndexes", void 0);
|
|
335
|
+
_define_property(this, "_queryControlsValidator", void 0);
|
|
336
|
+
_define_property(this, "_pagesControlsValidator", void 0);
|
|
337
|
+
_define_property(this, "_getOneControlsValidator", void 0);
|
|
338
|
+
this.table = table;
|
|
339
|
+
this._serializedType = (0, __atscript_typescript_utils.serializeAnnotatedType)(table.type);
|
|
340
|
+
this._searchIndexes = table.getSearchIndexes();
|
|
341
|
+
this.logger = app.getLogger(`db [${table.tableName}]`);
|
|
342
|
+
this.logger.info("Initializing table controller");
|
|
343
|
+
try {
|
|
344
|
+
const p = this.init();
|
|
345
|
+
if (p instanceof Promise) p.catch((error) => {
|
|
346
|
+
this.logger.error(error);
|
|
347
|
+
});
|
|
348
|
+
} catch (error) {
|
|
349
|
+
this.logger.error(error);
|
|
350
|
+
throw error;
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
};
|
|
354
|
+
_ts_decorate([
|
|
355
|
+
(0, __moostjs_event_http.Get)("query"),
|
|
356
|
+
_ts_param(0, (0, __moostjs_event_http.Url)()),
|
|
357
|
+
_ts_metadata("design:type", Function),
|
|
358
|
+
_ts_metadata("design:paramtypes", [String]),
|
|
359
|
+
_ts_metadata("design:returntype", Promise)
|
|
360
|
+
], AsDbController.prototype, "query", null);
|
|
361
|
+
_ts_decorate([
|
|
362
|
+
(0, __moostjs_event_http.Get)("pages"),
|
|
363
|
+
_ts_param(0, (0, __moostjs_event_http.Url)()),
|
|
364
|
+
_ts_metadata("design:type", Function),
|
|
365
|
+
_ts_metadata("design:paramtypes", [String]),
|
|
366
|
+
_ts_metadata("design:returntype", Promise)
|
|
367
|
+
], AsDbController.prototype, "pages", null);
|
|
368
|
+
_ts_decorate([
|
|
369
|
+
(0, __moostjs_event_http.Get)("one/:id"),
|
|
370
|
+
_ts_param(0, (0, moost.Param)("id")),
|
|
371
|
+
_ts_param(1, (0, __moostjs_event_http.Url)()),
|
|
372
|
+
_ts_metadata("design:type", Function),
|
|
373
|
+
_ts_metadata("design:paramtypes", [String, String]),
|
|
374
|
+
_ts_metadata("design:returntype", Promise)
|
|
375
|
+
], AsDbController.prototype, "getOne", null);
|
|
376
|
+
_ts_decorate([
|
|
377
|
+
(0, __moostjs_event_http.Post)(""),
|
|
378
|
+
_ts_param(0, (0, __moostjs_event_http.Body)()),
|
|
379
|
+
_ts_metadata("design:type", Function),
|
|
380
|
+
_ts_metadata("design:paramtypes", [Object]),
|
|
381
|
+
_ts_metadata("design:returntype", Promise)
|
|
382
|
+
], AsDbController.prototype, "insert", null);
|
|
383
|
+
_ts_decorate([
|
|
384
|
+
(0, __moostjs_event_http.Put)(""),
|
|
385
|
+
_ts_param(0, (0, __moostjs_event_http.Body)()),
|
|
386
|
+
_ts_metadata("design:type", Function),
|
|
387
|
+
_ts_metadata("design:paramtypes", [Object]),
|
|
388
|
+
_ts_metadata("design:returntype", Promise)
|
|
389
|
+
], AsDbController.prototype, "replace", null);
|
|
390
|
+
_ts_decorate([
|
|
391
|
+
(0, __moostjs_event_http.Patch)(""),
|
|
392
|
+
_ts_param(0, (0, __moostjs_event_http.Body)()),
|
|
393
|
+
_ts_metadata("design:type", Function),
|
|
394
|
+
_ts_metadata("design:paramtypes", [Object]),
|
|
395
|
+
_ts_metadata("design:returntype", Promise)
|
|
396
|
+
], AsDbController.prototype, "update", null);
|
|
397
|
+
_ts_decorate([
|
|
398
|
+
(0, __moostjs_event_http.Delete)(":id"),
|
|
399
|
+
_ts_param(0, (0, moost.Param)("id")),
|
|
400
|
+
_ts_metadata("design:type", Function),
|
|
401
|
+
_ts_metadata("design:paramtypes", [String]),
|
|
402
|
+
_ts_metadata("design:returntype", Promise)
|
|
403
|
+
], AsDbController.prototype, "remove", null);
|
|
404
|
+
_ts_decorate([
|
|
405
|
+
(0, __moostjs_event_http.Get)("meta"),
|
|
406
|
+
_ts_metadata("design:type", Function),
|
|
407
|
+
_ts_metadata("design:paramtypes", []),
|
|
408
|
+
_ts_metadata("design:returntype", void 0)
|
|
409
|
+
], AsDbController.prototype, "meta", null);
|
|
410
|
+
AsDbController = _ts_decorate([
|
|
411
|
+
UseValidationErrorTransform(),
|
|
412
|
+
_ts_param(0, (0, moost.Inject)(TABLE_DEF)),
|
|
413
|
+
_ts_metadata("design:type", Function),
|
|
414
|
+
_ts_metadata("design:paramtypes", [typeof AtscriptDbTable === "undefined" ? Object : AtscriptDbTable, typeof moost.Moost === "undefined" ? Object : moost.Moost])
|
|
415
|
+
], AsDbController);
|
|
416
|
+
|
|
417
|
+
//#endregion
|
|
418
|
+
Object.defineProperty(exports, 'AsDbController', {
|
|
419
|
+
enumerable: true,
|
|
420
|
+
get: function () {
|
|
421
|
+
return AsDbController;
|
|
422
|
+
}
|
|
423
|
+
});
|
|
424
|
+
exports.TABLE_DEF = TABLE_DEF
|
|
425
|
+
exports.TableController = TableController
|
|
426
|
+
exports.UseValidationErrorTransform = UseValidationErrorTransform
|
|
427
|
+
exports.validationErrorTransform = validationErrorTransform
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import * as _atscript_typescript_serialize from '@atscript/typescript/serialize';
|
|
2
|
+
import * as _atscript_utils_db from '@atscript/utils-db';
|
|
3
|
+
import { AtscriptDbTable, Uniquery, FilterExpr, UniqueryControls } from '@atscript/utils-db';
|
|
4
|
+
import * as _uniqu_url from '@uniqu/url';
|
|
5
|
+
import { TAtscriptAnnotatedType, TAtscriptDataType, Validator } from '@atscript/typescript/utils';
|
|
6
|
+
import { HttpError } from '@moostjs/event-http';
|
|
7
|
+
import * as moost from 'moost';
|
|
8
|
+
import { TConsoleBase, Moost } from 'moost';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Generic database controller for Moost that works with any `AtscriptDbTable` +
|
|
12
|
+
* `BaseDbAdapter`. All CRUD routes through the generic table layer — no
|
|
13
|
+
* adapter-specific imports.
|
|
14
|
+
*
|
|
15
|
+
* Subclass and provide the table via DI:
|
|
16
|
+
* ```ts
|
|
17
|
+
* @Provide(TABLE_DEF, () => driver.getTable(MyType))
|
|
18
|
+
* @TableController(MyType)
|
|
19
|
+
* export class MyController extends AsDbController<typeof MyType> {}
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
declare class AsDbController<T extends TAtscriptAnnotatedType = TAtscriptAnnotatedType, DataType = TAtscriptDataType<T>> {
|
|
23
|
+
/** Reference to the underlying table. */
|
|
24
|
+
protected table: AtscriptDbTable<T>;
|
|
25
|
+
/** Application-scoped logger. */
|
|
26
|
+
protected logger: TConsoleBase;
|
|
27
|
+
/** Cached serialized type definition (static, computed once). */
|
|
28
|
+
private _serializedType;
|
|
29
|
+
/** Cached search index list (static, computed once). */
|
|
30
|
+
private _searchIndexes;
|
|
31
|
+
constructor(table: AtscriptDbTable<T>, app: Moost);
|
|
32
|
+
/**
|
|
33
|
+
* One-time initialization hook. Override to seed data, register watchers, etc.
|
|
34
|
+
*/
|
|
35
|
+
protected init(): void | Promise<void>;
|
|
36
|
+
private _queryControlsValidator?;
|
|
37
|
+
private _pagesControlsValidator?;
|
|
38
|
+
private _getOneControlsValidator?;
|
|
39
|
+
protected get queryControlsValidator(): Validator<any, unknown>;
|
|
40
|
+
protected get pagesControlsValidator(): Validator<any, unknown>;
|
|
41
|
+
protected get getOneControlsValidator(): Validator<any, unknown>;
|
|
42
|
+
protected validateControls(controls: Record<string, unknown>, type: 'query' | 'pages' | 'getOne'): string | undefined;
|
|
43
|
+
protected validateInsights(insights: Map<string, unknown>): string | undefined;
|
|
44
|
+
protected validateParsed(parsed: Uniquery, type: 'query' | 'pages' | 'getOne'): HttpError | undefined;
|
|
45
|
+
/**
|
|
46
|
+
* Transform filter before querying. Override to add tenant filtering, etc.
|
|
47
|
+
*/
|
|
48
|
+
protected transformFilter(filter: FilterExpr): FilterExpr;
|
|
49
|
+
/**
|
|
50
|
+
* Transform projection before querying.
|
|
51
|
+
*/
|
|
52
|
+
protected transformProjection(projection?: UniqueryControls['$select']): UniqueryControls['$select'] | undefined;
|
|
53
|
+
/**
|
|
54
|
+
* Intercepts write operations. Return `undefined` to abort.
|
|
55
|
+
*/
|
|
56
|
+
protected onWrite(action: 'insert' | 'insertMany' | 'replace' | 'update', data: unknown): unknown | Promise<unknown | undefined>;
|
|
57
|
+
/**
|
|
58
|
+
* Intercepts delete operations. Return `undefined` to abort.
|
|
59
|
+
*/
|
|
60
|
+
protected onRemove(id: unknown): unknown | Promise<unknown | undefined>;
|
|
61
|
+
protected parseQueryString(url: string): _uniqu_url.UrlQuery;
|
|
62
|
+
protected returnOne(result: Promise<DataType | null>): Promise<DataType | HttpError>;
|
|
63
|
+
/**
|
|
64
|
+
* **GET /query** — returns an array of records or a count.
|
|
65
|
+
*/
|
|
66
|
+
query(url: string): Promise<DataType[] | number | HttpError>;
|
|
67
|
+
/**
|
|
68
|
+
* **GET /pages** — returns paginated records with metadata.
|
|
69
|
+
*/
|
|
70
|
+
pages(url: string): Promise<{
|
|
71
|
+
data: DataType[];
|
|
72
|
+
page: number;
|
|
73
|
+
itemsPerPage: number;
|
|
74
|
+
pages: number;
|
|
75
|
+
count: number;
|
|
76
|
+
} | HttpError>;
|
|
77
|
+
/**
|
|
78
|
+
* **GET /one/:id** — retrieves a single record by ID or unique property.
|
|
79
|
+
*/
|
|
80
|
+
getOne(id: string, url: string): Promise<DataType | HttpError>;
|
|
81
|
+
/**
|
|
82
|
+
* **POST /** — inserts one or many records.
|
|
83
|
+
*/
|
|
84
|
+
insert(payload: unknown): Promise<HttpError | unknown>;
|
|
85
|
+
/**
|
|
86
|
+
* **PUT /** — fully replaces a record matched by primary key.
|
|
87
|
+
*/
|
|
88
|
+
replace(payload: unknown): Promise<HttpError | unknown>;
|
|
89
|
+
/**
|
|
90
|
+
* **PATCH /** — partially updates a record matched by primary key.
|
|
91
|
+
*/
|
|
92
|
+
update(payload: unknown): Promise<HttpError | unknown>;
|
|
93
|
+
/**
|
|
94
|
+
* **DELETE /:id** — removes a single record by primary key.
|
|
95
|
+
*/
|
|
96
|
+
remove(id: string): Promise<HttpError | unknown>;
|
|
97
|
+
/**
|
|
98
|
+
* **GET /meta** — returns table metadata for UI.
|
|
99
|
+
*/
|
|
100
|
+
meta(): {
|
|
101
|
+
searchable: boolean;
|
|
102
|
+
searchIndexes: _atscript_utils_db.TSearchIndexInfo[];
|
|
103
|
+
type: _atscript_typescript_serialize.TSerializedAnnotatedType;
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* DI token under which the {@link AtscriptDbTable} instance
|
|
109
|
+
* is exposed to the controller's constructor via `@Inject`.
|
|
110
|
+
*/
|
|
111
|
+
declare const TABLE_DEF = "__atscript_db_table_def";
|
|
112
|
+
/**
|
|
113
|
+
* Combines the boilerplate needed to turn an {@link AsDbController}
|
|
114
|
+
* subclass into a fully wired HTTP controller for a given `@db.table` model.
|
|
115
|
+
*
|
|
116
|
+
* Internally applies three decorators:
|
|
117
|
+
* 1. **Provide** — registers the table instance under {@link TABLE_DEF}.
|
|
118
|
+
* 2. **Controller** — registers the class as a Moost HTTP controller
|
|
119
|
+
* with an optional route prefix. Defaults to `table.tableName`.
|
|
120
|
+
* 3. **Inherit** — copies metadata (routes, guards, etc.) from the
|
|
121
|
+
* parent class so they stay active in the derived controller.
|
|
122
|
+
*
|
|
123
|
+
* @param table The {@link AtscriptDbTable} instance for this controller.
|
|
124
|
+
* @param prefix Optional route prefix. Defaults to `table.tableName`.
|
|
125
|
+
*
|
|
126
|
+
* @example
|
|
127
|
+
* ```ts
|
|
128
|
+
* @TableController(usersTable)
|
|
129
|
+
* export class UsersController extends AsDbController<typeof UserModel> {}
|
|
130
|
+
* ```
|
|
131
|
+
*/
|
|
132
|
+
declare const TableController: (table: AtscriptDbTable, prefix?: string) => MethodDecorator & ClassDecorator & ParameterDecorator & PropertyDecorator;
|
|
133
|
+
|
|
134
|
+
declare const validationErrorTransform: () => moost.TInterceptorDef;
|
|
135
|
+
declare const UseValidationErrorTransform: () => ClassDecorator & MethodDecorator;
|
|
136
|
+
|
|
137
|
+
export { AsDbController, TABLE_DEF, TableController, UseValidationErrorTransform, validationErrorTransform };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,394 @@
|
|
|
1
|
+
import { ValidatorError, defineAnnotatedType, serializeAnnotatedType, throwFeatureDisabled } from "@atscript/typescript/utils";
|
|
2
|
+
import { Body, Delete, Get, HttpError, Patch, Post, Put, Url } from "@moostjs/event-http";
|
|
3
|
+
import { ApplyDecorators, Controller, Inherit, Inject, Intercept, Moost, Param, Provide, TInterceptorPriority, defineInterceptor } from "moost";
|
|
4
|
+
import { parseUrl } from "@uniqu/url";
|
|
5
|
+
|
|
6
|
+
//#region packages/moost-db/src/decorators.ts
|
|
7
|
+
const TABLE_DEF = "__atscript_db_table_def";
|
|
8
|
+
const TableController = (table, prefix) => ApplyDecorators(Provide(TABLE_DEF, () => table), Controller(prefix || table.tableName), Inherit());
|
|
9
|
+
|
|
10
|
+
//#endregion
|
|
11
|
+
//#region packages/moost-db/src/validation-interceptor.ts
|
|
12
|
+
function transformValidationError(error, reply) {
|
|
13
|
+
if (error instanceof ValidatorError) reply(new HttpError(400, {
|
|
14
|
+
message: error.message,
|
|
15
|
+
statusCode: 400,
|
|
16
|
+
errors: error.errors
|
|
17
|
+
}));
|
|
18
|
+
}
|
|
19
|
+
const validationErrorTransform = () => defineInterceptor({ error: transformValidationError }, TInterceptorPriority.CATCH_ERROR);
|
|
20
|
+
const UseValidationErrorTransform = () => Intercept(validationErrorTransform());
|
|
21
|
+
|
|
22
|
+
//#endregion
|
|
23
|
+
//#region packages/moost-db/src/dto/controls.dto.as.js
|
|
24
|
+
function _define_property$1(obj, key, value) {
|
|
25
|
+
if (key in obj) Object.defineProperty(obj, key, {
|
|
26
|
+
value,
|
|
27
|
+
enumerable: true,
|
|
28
|
+
configurable: true,
|
|
29
|
+
writable: true
|
|
30
|
+
});
|
|
31
|
+
else obj[key] = value;
|
|
32
|
+
return obj;
|
|
33
|
+
}
|
|
34
|
+
var QueryControlsDto = class {
|
|
35
|
+
static toJsonSchema() {
|
|
36
|
+
throwFeatureDisabled("JSON Schema", "jsonSchema", "emit.jsonSchema");
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
_define_property$1(QueryControlsDto, "__is_atscript_annotated_type", true);
|
|
40
|
+
_define_property$1(QueryControlsDto, "type", {});
|
|
41
|
+
_define_property$1(QueryControlsDto, "metadata", new Map());
|
|
42
|
+
_define_property$1(QueryControlsDto, "id", "QueryControlsDto");
|
|
43
|
+
var PagesControlsDto = class {
|
|
44
|
+
static toJsonSchema() {
|
|
45
|
+
throwFeatureDisabled("JSON Schema", "jsonSchema", "emit.jsonSchema");
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
_define_property$1(PagesControlsDto, "__is_atscript_annotated_type", true);
|
|
49
|
+
_define_property$1(PagesControlsDto, "type", {});
|
|
50
|
+
_define_property$1(PagesControlsDto, "metadata", new Map());
|
|
51
|
+
_define_property$1(PagesControlsDto, "id", "PagesControlsDto");
|
|
52
|
+
var GetOneControlsDto = class {
|
|
53
|
+
static toJsonSchema() {
|
|
54
|
+
throwFeatureDisabled("JSON Schema", "jsonSchema", "emit.jsonSchema");
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
_define_property$1(GetOneControlsDto, "__is_atscript_annotated_type", true);
|
|
58
|
+
_define_property$1(GetOneControlsDto, "type", {});
|
|
59
|
+
_define_property$1(GetOneControlsDto, "metadata", new Map());
|
|
60
|
+
_define_property$1(GetOneControlsDto, "id", "GetOneControlsDto");
|
|
61
|
+
let SortControlDto = class SortControlDto$1 {
|
|
62
|
+
static toJsonSchema() {
|
|
63
|
+
throwFeatureDisabled("JSON Schema", "jsonSchema", "emit.jsonSchema");
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
_define_property$1(SortControlDto, "__is_atscript_annotated_type", true);
|
|
67
|
+
_define_property$1(SortControlDto, "type", {});
|
|
68
|
+
_define_property$1(SortControlDto, "metadata", new Map());
|
|
69
|
+
_define_property$1(SortControlDto, "id", "SortControlDto");
|
|
70
|
+
let SelectControlDto = class SelectControlDto$1 {
|
|
71
|
+
static toJsonSchema() {
|
|
72
|
+
throwFeatureDisabled("JSON Schema", "jsonSchema", "emit.jsonSchema");
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
_define_property$1(SelectControlDto, "__is_atscript_annotated_type", true);
|
|
76
|
+
_define_property$1(SelectControlDto, "type", {});
|
|
77
|
+
_define_property$1(SelectControlDto, "metadata", new Map());
|
|
78
|
+
_define_property$1(SelectControlDto, "id", "SelectControlDto");
|
|
79
|
+
defineAnnotatedType("object", QueryControlsDto).prop("$skip", defineAnnotatedType().designType("number").tags("positive", "int", "number").annotate("expect.int", true).annotate("expect.min", { minValue: 0 }).optional().$type).prop("$limit", defineAnnotatedType().designType("number").tags("positive", "int", "number").annotate("expect.int", true).annotate("expect.min", { minValue: 0 }).optional().$type).prop("$count", defineAnnotatedType().designType("boolean").tags("boolean").optional().$type).prop("$sort", defineAnnotatedType().refTo(SortControlDto).optional().$type).prop("$select", defineAnnotatedType("union").item(defineAnnotatedType().refTo(SelectControlDto).$type).item(defineAnnotatedType("array").of(defineAnnotatedType().designType("string").tags("string").$type).$type).optional().$type).prop("$search", defineAnnotatedType().designType("string").tags("string").optional().$type).prop("$index", defineAnnotatedType().designType("string").tags("string").optional().$type);
|
|
80
|
+
defineAnnotatedType("object", PagesControlsDto).prop("$page", defineAnnotatedType().designType("string").tags("string").annotate("expect.pattern", {
|
|
81
|
+
pattern: "^\\d+$",
|
|
82
|
+
flags: "u",
|
|
83
|
+
message: "Expected positive number"
|
|
84
|
+
}, true).optional().$type).prop("$size", defineAnnotatedType().designType("string").tags("string").annotate("expect.pattern", {
|
|
85
|
+
pattern: "^\\d+$",
|
|
86
|
+
flags: "u",
|
|
87
|
+
message: "Expected positive number"
|
|
88
|
+
}, true).optional().$type).prop("$sort", defineAnnotatedType().refTo(SortControlDto).optional().$type).prop("$select", defineAnnotatedType("union").item(defineAnnotatedType().refTo(SelectControlDto).$type).item(defineAnnotatedType("array").of(defineAnnotatedType().designType("string").tags("string").$type).$type).optional().$type).prop("$search", defineAnnotatedType().designType("string").tags("string").optional().$type).prop("$index", defineAnnotatedType().designType("string").tags("string").optional().$type);
|
|
89
|
+
defineAnnotatedType("object", GetOneControlsDto).prop("$select", defineAnnotatedType("union").item(defineAnnotatedType().refTo(SelectControlDto).$type).item(defineAnnotatedType("array").of(defineAnnotatedType().designType("string").tags("string").$type).$type).optional().$type);
|
|
90
|
+
defineAnnotatedType("object", SortControlDto).propPattern(/./, defineAnnotatedType("union").item(defineAnnotatedType().designType("number").value(1).$type).item(defineAnnotatedType().designType("number").value(-1).$type).$type);
|
|
91
|
+
defineAnnotatedType("object", SelectControlDto).propPattern(/./, defineAnnotatedType("union").item(defineAnnotatedType().designType("number").value(1).$type).item(defineAnnotatedType().designType("number").value(0).$type).$type);
|
|
92
|
+
|
|
93
|
+
//#endregion
|
|
94
|
+
//#region packages/moost-db/src/as-db.controller.ts
|
|
95
|
+
function _define_property(obj, key, value) {
|
|
96
|
+
if (key in obj) Object.defineProperty(obj, key, {
|
|
97
|
+
value,
|
|
98
|
+
enumerable: true,
|
|
99
|
+
configurable: true,
|
|
100
|
+
writable: true
|
|
101
|
+
});
|
|
102
|
+
else obj[key] = value;
|
|
103
|
+
return obj;
|
|
104
|
+
}
|
|
105
|
+
function _ts_decorate(decorators, target, key, desc) {
|
|
106
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
107
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
108
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
109
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
110
|
+
}
|
|
111
|
+
function _ts_metadata(k, v) {
|
|
112
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
113
|
+
}
|
|
114
|
+
function _ts_param(paramIndex, decorator) {
|
|
115
|
+
return function(target, key) {
|
|
116
|
+
decorator(target, key, paramIndex);
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
var AsDbController = class {
|
|
120
|
+
/**
|
|
121
|
+
* One-time initialization hook. Override to seed data, register watchers, etc.
|
|
122
|
+
*/ init() {}
|
|
123
|
+
get queryControlsValidator() {
|
|
124
|
+
if (!this._queryControlsValidator) this._queryControlsValidator = QueryControlsDto.validator();
|
|
125
|
+
return this._queryControlsValidator;
|
|
126
|
+
}
|
|
127
|
+
get pagesControlsValidator() {
|
|
128
|
+
if (!this._pagesControlsValidator) this._pagesControlsValidator = PagesControlsDto.validator();
|
|
129
|
+
return this._pagesControlsValidator;
|
|
130
|
+
}
|
|
131
|
+
get getOneControlsValidator() {
|
|
132
|
+
if (!this._getOneControlsValidator) this._getOneControlsValidator = GetOneControlsDto.validator();
|
|
133
|
+
return this._getOneControlsValidator;
|
|
134
|
+
}
|
|
135
|
+
validateControls(controls, type) {
|
|
136
|
+
const v = type === "query" ? this.queryControlsValidator : type === "pages" ? this.pagesControlsValidator : this.getOneControlsValidator;
|
|
137
|
+
if (!v.validate(controls, true)) return v.errors[0]?.message || "Invalid controls";
|
|
138
|
+
return undefined;
|
|
139
|
+
}
|
|
140
|
+
validateInsights(insights) {
|
|
141
|
+
for (const key of insights.keys()) if (!this.table.flatMap.has(key)) return `Unknown field "${key}"`;
|
|
142
|
+
return undefined;
|
|
143
|
+
}
|
|
144
|
+
validateParsed(parsed, type) {
|
|
145
|
+
const controlsError = this.validateControls(parsed.controls, type);
|
|
146
|
+
if (controlsError) return new HttpError(400, controlsError);
|
|
147
|
+
if (parsed.insights) {
|
|
148
|
+
const insightsError = this.validateInsights(parsed.insights);
|
|
149
|
+
if (insightsError) return new HttpError(400, insightsError);
|
|
150
|
+
}
|
|
151
|
+
return undefined;
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Transform filter before querying. Override to add tenant filtering, etc.
|
|
155
|
+
*/ transformFilter(filter) {
|
|
156
|
+
return filter;
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Transform projection before querying.
|
|
160
|
+
*/ transformProjection(projection) {
|
|
161
|
+
return projection;
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Intercepts write operations. Return `undefined` to abort.
|
|
165
|
+
*/ onWrite(action, data) {
|
|
166
|
+
return data;
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Intercepts delete operations. Return `undefined` to abort.
|
|
170
|
+
*/ onRemove(id) {
|
|
171
|
+
return id;
|
|
172
|
+
}
|
|
173
|
+
parseQueryString(url) {
|
|
174
|
+
const idx = url.indexOf("?");
|
|
175
|
+
return parseUrl(idx >= 0 ? url.slice(idx + 1) : "");
|
|
176
|
+
}
|
|
177
|
+
async returnOne(result) {
|
|
178
|
+
const item = await result;
|
|
179
|
+
if (!item) return new HttpError(404);
|
|
180
|
+
return item;
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* **GET /query** — returns an array of records or a count.
|
|
184
|
+
*/ async query(url) {
|
|
185
|
+
const parsed = this.parseQueryString(url);
|
|
186
|
+
const error = this.validateParsed(parsed, "query");
|
|
187
|
+
if (error) return error;
|
|
188
|
+
const controls = parsed.controls;
|
|
189
|
+
const filter = this.transformFilter(parsed.filter);
|
|
190
|
+
const select = this.transformProjection(controls.$select);
|
|
191
|
+
if (controls.$count) return this.table.count({
|
|
192
|
+
filter,
|
|
193
|
+
controls: {
|
|
194
|
+
...controls,
|
|
195
|
+
$select: select
|
|
196
|
+
}
|
|
197
|
+
});
|
|
198
|
+
const searchTerm = controls.$search;
|
|
199
|
+
const indexName = controls.$index;
|
|
200
|
+
if (searchTerm && this.table.isSearchable()) return this.table.search(searchTerm, {
|
|
201
|
+
filter,
|
|
202
|
+
controls: {
|
|
203
|
+
...controls,
|
|
204
|
+
$select: select,
|
|
205
|
+
$limit: controls.$limit || 1e3
|
|
206
|
+
}
|
|
207
|
+
}, indexName);
|
|
208
|
+
return this.table.findMany({
|
|
209
|
+
filter,
|
|
210
|
+
controls: {
|
|
211
|
+
...controls,
|
|
212
|
+
$select: select,
|
|
213
|
+
$limit: controls.$limit || 1e3
|
|
214
|
+
}
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* **GET /pages** — returns paginated records with metadata.
|
|
219
|
+
*/ async pages(url) {
|
|
220
|
+
const parsed = this.parseQueryString(url);
|
|
221
|
+
const error = this.validateParsed(parsed, "pages");
|
|
222
|
+
if (error) return error;
|
|
223
|
+
const controls = parsed.controls;
|
|
224
|
+
const page = Math.max(Number(controls.$page || 1), 1);
|
|
225
|
+
const size = Math.max(Number(controls.$size || 10), 1);
|
|
226
|
+
const skip = (page - 1) * size;
|
|
227
|
+
const filter = this.transformFilter(parsed.filter);
|
|
228
|
+
const select = this.transformProjection(controls.$select);
|
|
229
|
+
const searchTerm = controls.$search;
|
|
230
|
+
const indexName = controls.$index;
|
|
231
|
+
const query = {
|
|
232
|
+
filter,
|
|
233
|
+
controls: {
|
|
234
|
+
...controls,
|
|
235
|
+
$select: select,
|
|
236
|
+
$skip: skip,
|
|
237
|
+
$limit: size
|
|
238
|
+
}
|
|
239
|
+
};
|
|
240
|
+
let result;
|
|
241
|
+
if (searchTerm && this.table.isSearchable()) result = await this.table.searchWithCount(searchTerm, query, indexName);
|
|
242
|
+
else result = await this.table.findManyWithCount(query);
|
|
243
|
+
return {
|
|
244
|
+
data: result.data,
|
|
245
|
+
page,
|
|
246
|
+
itemsPerPage: size,
|
|
247
|
+
pages: Math.ceil(result.count / size),
|
|
248
|
+
count: result.count
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* **GET /one/:id** — retrieves a single record by ID or unique property.
|
|
253
|
+
*/ async getOne(id, url) {
|
|
254
|
+
const parsed = this.parseQueryString(url);
|
|
255
|
+
if (Object.keys(parsed.filter).length > 0) return new HttpError(400, "Filtering is not allowed for \"one\" endpoint");
|
|
256
|
+
const error = this.validateParsed(parsed, "getOne");
|
|
257
|
+
if (error) return error;
|
|
258
|
+
const select = this.transformProjection(parsed.controls.$select);
|
|
259
|
+
return this.returnOne(this.table.findById(id, { $select: select }));
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* **POST /** — inserts one or many records.
|
|
263
|
+
*/ async insert(payload) {
|
|
264
|
+
const arr = Array.isArray(payload) ? payload : [payload];
|
|
265
|
+
if (arr.length === 1) {
|
|
266
|
+
const data$1 = await this.onWrite("insert", arr[0]);
|
|
267
|
+
if (data$1 === undefined) return new HttpError(500, "Not saved");
|
|
268
|
+
return await this.table.insertOne(data$1);
|
|
269
|
+
}
|
|
270
|
+
const data = await this.onWrite("insertMany", arr);
|
|
271
|
+
if (data === undefined) return new HttpError(500, "Not saved");
|
|
272
|
+
return await this.table.insertMany(data);
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* **PUT /** — fully replaces a record matched by primary key.
|
|
276
|
+
*/ async replace(payload) {
|
|
277
|
+
const data = await this.onWrite("replace", payload);
|
|
278
|
+
if (data === undefined) return new HttpError(500, "Not saved");
|
|
279
|
+
return await this.table.replaceOne(data);
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* **PATCH /** — partially updates a record matched by primary key.
|
|
283
|
+
*/ async update(payload) {
|
|
284
|
+
const data = await this.onWrite("update", payload);
|
|
285
|
+
if (data === undefined) return new HttpError(500, "Not saved");
|
|
286
|
+
return await this.table.updateOne(data);
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* **DELETE /:id** — removes a single record by primary key.
|
|
290
|
+
*/ async remove(id) {
|
|
291
|
+
const resolvedId = await this.onRemove(id);
|
|
292
|
+
if (resolvedId === undefined) return new HttpError(500, "Not deleted");
|
|
293
|
+
const result = await this.table.deleteOne(resolvedId);
|
|
294
|
+
if (result.deletedCount < 1) return new HttpError(404);
|
|
295
|
+
return result;
|
|
296
|
+
}
|
|
297
|
+
/**
|
|
298
|
+
* **GET /meta** — returns table metadata for UI.
|
|
299
|
+
*/ meta() {
|
|
300
|
+
return {
|
|
301
|
+
searchable: this.table.isSearchable(),
|
|
302
|
+
searchIndexes: this._searchIndexes,
|
|
303
|
+
type: this._serializedType
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
constructor(table, app) {
|
|
307
|
+
/** Reference to the underlying table. */ _define_property(this, "table", void 0);
|
|
308
|
+
/** Application-scoped logger. */ _define_property(this, "logger", void 0);
|
|
309
|
+
/** Cached serialized type definition (static, computed once). */ _define_property(this, "_serializedType", void 0);
|
|
310
|
+
/** Cached search index list (static, computed once). */ _define_property(this, "_searchIndexes", void 0);
|
|
311
|
+
_define_property(this, "_queryControlsValidator", void 0);
|
|
312
|
+
_define_property(this, "_pagesControlsValidator", void 0);
|
|
313
|
+
_define_property(this, "_getOneControlsValidator", void 0);
|
|
314
|
+
this.table = table;
|
|
315
|
+
this._serializedType = serializeAnnotatedType(table.type);
|
|
316
|
+
this._searchIndexes = table.getSearchIndexes();
|
|
317
|
+
this.logger = app.getLogger(`db [${table.tableName}]`);
|
|
318
|
+
this.logger.info("Initializing table controller");
|
|
319
|
+
try {
|
|
320
|
+
const p = this.init();
|
|
321
|
+
if (p instanceof Promise) p.catch((error) => {
|
|
322
|
+
this.logger.error(error);
|
|
323
|
+
});
|
|
324
|
+
} catch (error) {
|
|
325
|
+
this.logger.error(error);
|
|
326
|
+
throw error;
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
};
|
|
330
|
+
_ts_decorate([
|
|
331
|
+
Get("query"),
|
|
332
|
+
_ts_param(0, Url()),
|
|
333
|
+
_ts_metadata("design:type", Function),
|
|
334
|
+
_ts_metadata("design:paramtypes", [String]),
|
|
335
|
+
_ts_metadata("design:returntype", Promise)
|
|
336
|
+
], AsDbController.prototype, "query", null);
|
|
337
|
+
_ts_decorate([
|
|
338
|
+
Get("pages"),
|
|
339
|
+
_ts_param(0, Url()),
|
|
340
|
+
_ts_metadata("design:type", Function),
|
|
341
|
+
_ts_metadata("design:paramtypes", [String]),
|
|
342
|
+
_ts_metadata("design:returntype", Promise)
|
|
343
|
+
], AsDbController.prototype, "pages", null);
|
|
344
|
+
_ts_decorate([
|
|
345
|
+
Get("one/:id"),
|
|
346
|
+
_ts_param(0, Param("id")),
|
|
347
|
+
_ts_param(1, Url()),
|
|
348
|
+
_ts_metadata("design:type", Function),
|
|
349
|
+
_ts_metadata("design:paramtypes", [String, String]),
|
|
350
|
+
_ts_metadata("design:returntype", Promise)
|
|
351
|
+
], AsDbController.prototype, "getOne", null);
|
|
352
|
+
_ts_decorate([
|
|
353
|
+
Post(""),
|
|
354
|
+
_ts_param(0, Body()),
|
|
355
|
+
_ts_metadata("design:type", Function),
|
|
356
|
+
_ts_metadata("design:paramtypes", [Object]),
|
|
357
|
+
_ts_metadata("design:returntype", Promise)
|
|
358
|
+
], AsDbController.prototype, "insert", null);
|
|
359
|
+
_ts_decorate([
|
|
360
|
+
Put(""),
|
|
361
|
+
_ts_param(0, Body()),
|
|
362
|
+
_ts_metadata("design:type", Function),
|
|
363
|
+
_ts_metadata("design:paramtypes", [Object]),
|
|
364
|
+
_ts_metadata("design:returntype", Promise)
|
|
365
|
+
], AsDbController.prototype, "replace", null);
|
|
366
|
+
_ts_decorate([
|
|
367
|
+
Patch(""),
|
|
368
|
+
_ts_param(0, Body()),
|
|
369
|
+
_ts_metadata("design:type", Function),
|
|
370
|
+
_ts_metadata("design:paramtypes", [Object]),
|
|
371
|
+
_ts_metadata("design:returntype", Promise)
|
|
372
|
+
], AsDbController.prototype, "update", null);
|
|
373
|
+
_ts_decorate([
|
|
374
|
+
Delete(":id"),
|
|
375
|
+
_ts_param(0, Param("id")),
|
|
376
|
+
_ts_metadata("design:type", Function),
|
|
377
|
+
_ts_metadata("design:paramtypes", [String]),
|
|
378
|
+
_ts_metadata("design:returntype", Promise)
|
|
379
|
+
], AsDbController.prototype, "remove", null);
|
|
380
|
+
_ts_decorate([
|
|
381
|
+
Get("meta"),
|
|
382
|
+
_ts_metadata("design:type", Function),
|
|
383
|
+
_ts_metadata("design:paramtypes", []),
|
|
384
|
+
_ts_metadata("design:returntype", void 0)
|
|
385
|
+
], AsDbController.prototype, "meta", null);
|
|
386
|
+
AsDbController = _ts_decorate([
|
|
387
|
+
UseValidationErrorTransform(),
|
|
388
|
+
_ts_param(0, Inject(TABLE_DEF)),
|
|
389
|
+
_ts_metadata("design:type", Function),
|
|
390
|
+
_ts_metadata("design:paramtypes", [typeof AtscriptDbTable === "undefined" ? Object : AtscriptDbTable, typeof Moost === "undefined" ? Object : Moost])
|
|
391
|
+
], AsDbController);
|
|
392
|
+
|
|
393
|
+
//#endregion
|
|
394
|
+
export { AsDbController, TABLE_DEF, TableController, UseValidationErrorTransform, validationErrorTransform };
|
package/package.json
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@atscript/moost-db",
|
|
3
|
+
"version": "0.1.32",
|
|
4
|
+
"description": "Generic database controller for Moost with Atscript.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"annotations",
|
|
7
|
+
"atscript",
|
|
8
|
+
"database",
|
|
9
|
+
"moost",
|
|
10
|
+
"typescript"
|
|
11
|
+
],
|
|
12
|
+
"homepage": "https://github.com/moostjs/atscript/tree/main/packages/moost-db#readme",
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/moostjs/atscript/issues"
|
|
15
|
+
},
|
|
16
|
+
"license": "ISC",
|
|
17
|
+
"author": "Artem Maltsev",
|
|
18
|
+
"repository": {
|
|
19
|
+
"type": "git",
|
|
20
|
+
"url": "git+https://github.com/moostjs/atscript.git",
|
|
21
|
+
"directory": "packages/moost-db"
|
|
22
|
+
},
|
|
23
|
+
"files": [
|
|
24
|
+
"dist"
|
|
25
|
+
],
|
|
26
|
+
"type": "module",
|
|
27
|
+
"main": "dist/index.mjs",
|
|
28
|
+
"types": "dist/index.d.ts",
|
|
29
|
+
"exports": {
|
|
30
|
+
".": {
|
|
31
|
+
"types": "./dist/index.d.ts",
|
|
32
|
+
"import": "./dist/index.mjs",
|
|
33
|
+
"require": "./dist/index.cjs"
|
|
34
|
+
},
|
|
35
|
+
"./package.json": "./package.json"
|
|
36
|
+
},
|
|
37
|
+
"dependencies": {
|
|
38
|
+
"@uniqu/url": "^0.0.1"
|
|
39
|
+
},
|
|
40
|
+
"devDependencies": {
|
|
41
|
+
"@moostjs/event-http": "^0.6.2",
|
|
42
|
+
"moost": "^0.6.2",
|
|
43
|
+
"vitest": "3.2.4",
|
|
44
|
+
"@atscript/core": "^0.1.32"
|
|
45
|
+
},
|
|
46
|
+
"peerDependencies": {
|
|
47
|
+
"@moostjs/event-http": "^0.6.2",
|
|
48
|
+
"moost": "^0.6.2",
|
|
49
|
+
"@uniqu/core": "^0.0.2",
|
|
50
|
+
"@atscript/utils-db": "^0.1.32",
|
|
51
|
+
"@atscript/typescript": "^0.1.32"
|
|
52
|
+
},
|
|
53
|
+
"scripts": {
|
|
54
|
+
"pub": "pnpm publish --access public",
|
|
55
|
+
"before-build": "node ../typescript/cli.cjs -f js",
|
|
56
|
+
"test": "vitest"
|
|
57
|
+
}
|
|
58
|
+
}
|