@akanjs/server 0.0.28 → 0.0.30

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/src/database.d.ts DELETED
@@ -1,114 +0,0 @@
1
- import { type Dayjs } from "@akanjs/base";
2
- import { Logger } from "@akanjs/common";
3
- import { type DocumentModel, type FilterType, type FindQueryOption, type GetActionObject, type ListQueryOption, type QueryOf, type SortOf } from "@akanjs/constant";
4
- import type DataLoader from "dataloader";
5
- import type { Filter, MeiliSearch } from "meilisearch";
6
- import type { HydratedDocument } from "mongoose";
7
- import type { RedisClientType } from "redis";
8
- import type { BaseMiddleware, Database, Mdl } from "./dbDecorators";
9
- export type DataInputOf<Input, Obj> = {
10
- [K in keyof Input as Input[K] extends any[] ? never : K]: Input[K];
11
- } & {
12
- [K in keyof Input as Input[K] extends any[] ? K : never]?: Input[K];
13
- } & Partial<Obj>;
14
- interface RedisSetOptions {
15
- expireAt?: Dayjs;
16
- }
17
- declare class CacheDatabase<T = any> {
18
- private readonly refName;
19
- private readonly redis;
20
- private logger;
21
- constructor(refName: string, redis: RedisClientType);
22
- set(topic: string, key: string, value: string | number | Buffer, option?: RedisSetOptions): Promise<void>;
23
- get<T extends string | number | Buffer>(topic: string, key: string): Promise<T | undefined>;
24
- delete(topic: string, key: string): Promise<void>;
25
- }
26
- declare class SearchDatabase<T = any> {
27
- readonly refName: string;
28
- readonly meili: MeiliSearch;
29
- private logger;
30
- private index;
31
- constructor(refName: string, meili: MeiliSearch);
32
- searchIds(searchText: string | undefined | null, option?: {
33
- filter?: Filter;
34
- skip?: number | null;
35
- limit?: number | null;
36
- sort?: string[] | null;
37
- }): Promise<{
38
- ids: string[];
39
- total: number;
40
- }>;
41
- count(searchText: string | undefined | null, option?: {
42
- filter?: Filter;
43
- skip?: number | null;
44
- limit?: number | null;
45
- sort?: string | null;
46
- }): Promise<number>;
47
- }
48
- export type DatabaseModel<T extends string, Input, Doc, Obj, Insight, Filter, Summary = any> = DatabaseModelWithQuerySort<T, Input, Doc, Obj, Insight, GetActionObject<Filter>, SortOf<Filter>, Summary>;
49
- type DatabaseModelWithQuerySort<T extends string, Input, Doc, Obj, Insight, Query, Sort, Summary = any> = {
50
- logger: Logger;
51
- __model: Mdl<Doc, Obj>;
52
- __cache: CacheDatabase<T>;
53
- __search: SearchDatabase<T>;
54
- __loader: DataLoader<string, Doc, string>;
55
- __list(query?: QueryOf<Doc>, queryOption?: ListQueryOption<Sort, Obj>): Promise<Doc[]>;
56
- __listIds(query?: QueryOf<Doc>, queryOption?: ListQueryOption<Sort, Obj>): Promise<string[]>;
57
- __find(query?: QueryOf<Doc>, queryOption?: FindQueryOption<Sort, Obj>): Promise<Doc | null>;
58
- __findId(query?: QueryOf<Doc>, queryOption?: FindQueryOption<Sort, Obj>): Promise<string | null>;
59
- __pick(query?: QueryOf<Doc>, queryOption?: FindQueryOption<Sort, Obj>): Promise<Doc>;
60
- __pickId(query?: QueryOf<Doc>, queryOption?: FindQueryOption<Sort, Obj>): Promise<string>;
61
- __exists(query?: QueryOf<Doc>): Promise<string | null>;
62
- __count(query?: QueryOf<Doc>): Promise<number>;
63
- __insight(query?: QueryOf<Doc>): Promise<Insight>;
64
- getDefaultSummary(addQuery?: QueryOf<Doc>): Promise<Summary>;
65
- } & {
66
- [key in Capitalize<T>]: Mdl<Doc, Obj>;
67
- } & {
68
- [key in `${T}Loader`]: DataLoader<string, Doc, string>;
69
- } & {
70
- [key in `${T}Cache`]: CacheDatabase<T>;
71
- } & {
72
- [key in `${T}Search`]: SearchDatabase<T>;
73
- } & {
74
- [K in `get${Capitalize<T>}`]: (id: string) => Promise<Doc>;
75
- } & {
76
- [K in `load${Capitalize<T>}`]: (id?: string) => Promise<Doc | null>;
77
- } & {
78
- [K in `load${Capitalize<T>}Many`]: (ids: string) => Promise<Doc[]>;
79
- } & {
80
- [K in `create${Capitalize<T>}`]: (data: DataInputOf<Input, DocumentModel<Obj>>) => Promise<Doc>;
81
- } & {
82
- [K in `update${Capitalize<T>}`]: (id: string, data: DataInputOf<Input, DocumentModel<Obj>>) => Promise<Doc>;
83
- } & {
84
- [K in `remove${Capitalize<T>}`]: (id: string) => Promise<Doc>;
85
- } & {
86
- [K in `search${Capitalize<T>}`]: (searchText: string, queryOption?: ListQueryOption<Sort, Obj>) => Promise<{
87
- docs: Doc[];
88
- count: number;
89
- }>;
90
- } & {
91
- [K in `searchDocs${Capitalize<T>}`]: (searchText: string, queryOption?: ListQueryOption<Sort, Obj>) => Promise<Doc[]>;
92
- } & {
93
- [K in `searchCount${Capitalize<T>}`]: (searchText: string) => Promise<number>;
94
- } & {
95
- [K in keyof Query as K extends string ? `list${Capitalize<K>}` : never]: Query[K] extends (...args: infer Args) => any ? (...args: [...Args, queryOption?: ListQueryOption<Sort, Obj>]) => Promise<Doc[]> : never;
96
- } & {
97
- [K in keyof Query as K extends string ? `listIds${Capitalize<K>}` : never]: Query[K] extends (...args: infer Args) => any ? (...args: [...Args, queryOption?: ListQueryOption<Sort, Obj>]) => Promise<string[]> : never;
98
- } & {
99
- [K in keyof Query as K extends string ? `find${Capitalize<K>}` : never]: Query[K] extends (...args: infer Args) => any ? (...args: [...Args, queryOption?: FindQueryOption<Sort, Obj>]) => Promise<Doc | null> : never;
100
- } & {
101
- [K in keyof Query as K extends string ? `findId${Capitalize<K>}` : never]: Query[K] extends (...args: infer Args) => any ? (...args: [...Args, queryOption?: FindQueryOption<Sort, Obj>]) => Promise<string | null> : never;
102
- } & {
103
- [K in keyof Query as K extends string ? `pick${Capitalize<K>}` : never]: Query[K] extends (...args: infer Args) => any ? (...args: [...Args, queryOption?: FindQueryOption<Sort, Obj>]) => Promise<Doc> : never;
104
- } & {
105
- [K in keyof Query as K extends string ? `pickId${Capitalize<K>}` : never]: Query[K] extends (...args: infer Args) => any ? (...args: [...Args, queryOption?: FindQueryOption<Sort, Obj>]) => Promise<string> : never;
106
- } & {
107
- [K in keyof Query as K extends string ? `exists${Capitalize<K>}` : never]: Query[K] extends (...args: infer Args) => any ? (...args: [...Args]) => Promise<string | null> : never;
108
- } & {
109
- [K in keyof Query as K extends string ? `count${Capitalize<K>}` : never]: Query[K] extends (...args: infer Args) => any ? (...args: [...Args]) => Promise<number> : never;
110
- } & {
111
- [K in keyof Query as K extends string ? `insight${Capitalize<K>}` : never]: Query[K] extends (...args: infer Args) => any ? (...args: [...Args]) => Promise<Insight> : never;
112
- };
113
- export declare const databaseModelOf: <T extends string, Input, Doc extends HydratedDocument<any>, Model extends Mdl<any, any>, Middleware extends BaseMiddleware, Insight, Obj, Filter extends FilterType, Summary>(database: Database<T, Input, Doc, Model, Middleware, Insight, Obj, Filter, Summary>, model: Mdl<any, any>, redis: RedisClientType, meili: MeiliSearch) => DatabaseModel<T, Input, Doc, Model, Insight, Filter, Summary>;
114
- export {};
package/src/database.js DELETED
@@ -1,312 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
- var __getOwnPropNames = Object.getOwnPropertyNames;
4
- var __hasOwnProp = Object.prototype.hasOwnProperty;
5
- var __export = (target, all) => {
6
- for (var name in all)
7
- __defProp(target, name, { get: all[name], enumerable: true });
8
- };
9
- var __copyProps = (to, from, except, desc) => {
10
- if (from && typeof from === "object" || typeof from === "function") {
11
- for (let key of __getOwnPropNames(from))
12
- if (!__hasOwnProp.call(to, key) && key !== except)
13
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
- }
15
- return to;
16
- };
17
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
- var database_exports = {};
19
- __export(database_exports, {
20
- databaseModelOf: () => databaseModelOf
21
- });
22
- module.exports = __toCommonJS(database_exports);
23
- var import_base = require("@akanjs/base");
24
- var import_common = require("@akanjs/common");
25
- var import_constant = require("@akanjs/constant");
26
- var import_dataLoader = require("./dataLoader");
27
- var import_schema = require("./schema");
28
- var import_serviceDecorators = require("./serviceDecorators");
29
- class CacheDatabase {
30
- constructor(refName, redis) {
31
- this.refName = refName;
32
- this.redis = redis;
33
- this.logger = new import_common.Logger(`${refName}Cache`);
34
- }
35
- logger;
36
- async set(topic, key, value, option = {}) {
37
- const setOption = { PXAT: option.expireAt?.toDate().getTime() };
38
- await this.redis.set(`${this.refName}:${topic}:${key}`, value, setOption);
39
- }
40
- async get(topic, key) {
41
- const value = await this.redis.get(`${this.refName}:${topic}:${key}`);
42
- return value;
43
- }
44
- async delete(topic, key) {
45
- await this.redis.del(`${this.refName}:${topic}:${key}`);
46
- }
47
- }
48
- class SearchDatabase {
49
- constructor(refName, meili) {
50
- this.refName = refName;
51
- this.meili = meili;
52
- this.logger = new import_common.Logger(`${refName}Search`);
53
- this.index = meili.index((0, import_common.lowerlize)(refName));
54
- }
55
- logger;
56
- index;
57
- async searchIds(searchText, option = {}) {
58
- const { skip = 0, limit = import_constant.DEFAULT_PAGE_SIZE, sort } = option;
59
- if (!searchText) {
60
- const { results, total } = await this.index.getDocuments({ offset: skip ?? 0, limit: limit ?? 0 });
61
- return { ids: results.map((result) => result.id), total };
62
- }
63
- const { hits, estimatedTotalHits } = await this.index.search(searchText, {
64
- offset: skip ?? 0,
65
- limit: limit ?? 0,
66
- sort: sort ?? [],
67
- filter: option.filter,
68
- attributesToRetrieve: ["id"]
69
- });
70
- return { ids: hits.map((hit) => hit.id), total: estimatedTotalHits };
71
- }
72
- async count(searchText, option = {}) {
73
- const { skip = 0, limit = import_constant.DEFAULT_PAGE_SIZE, sort = "" } = option;
74
- if (!searchText) {
75
- const { results, total } = await this.index.getDocuments({ offset: skip ?? 0, limit: limit ?? 0 });
76
- return total;
77
- }
78
- const { hits, estimatedTotalHits } = await this.index.search(searchText, {
79
- offset: skip ?? 0,
80
- limit: limit ?? 0,
81
- filter: option.filter,
82
- attributesToRetrieve: ["id"]
83
- });
84
- return estimatedTotalHits;
85
- }
86
- }
87
- class DatabaseModelStorage {
88
- __ModelType__ = "DatabaseModelStorage";
89
- }
90
- const databaseModelOf = (database, model, redis, meili) => {
91
- //! 잘되는지 확인 필요
92
- const [modelName, className] = [database.refName, (0, import_common.capitalize)(database.refName)];
93
- const insightFieldMetas = (0, import_constant.getFieldMetas)(database.Insight);
94
- const accumulator = Object.fromEntries(insightFieldMetas.map((fieldMeta) => [fieldMeta.key, fieldMeta.accumulate]));
95
- const defaultInsight = Object.fromEntries(insightFieldMetas.map((fieldMeta) => [fieldMeta.key, fieldMeta.default]));
96
- const makeSafeQuery = (query) => ({ removedAt: { $exists: false }, ...query ?? {} });
97
- const makeSafeMatchStage = (query) => ({
98
- $match: { removedAt: { $exists: false }, ...(0, import_schema.convertAggregateMatch)(query) }
99
- });
100
- const getListQuery = (query, queryOption) => {
101
- const find = makeSafeQuery(query);
102
- const sort = (0, import_constant.getFilterSort)(database.Filter, queryOption?.sort ?? "latest");
103
- const skip = queryOption?.skip ?? 0;
104
- const limit = queryOption?.limit === null ? import_constant.DEFAULT_PAGE_SIZE : queryOption?.limit ?? 0;
105
- const select = queryOption?.select;
106
- const sample = queryOption?.sample;
107
- return { find, sort, skip, limit, select, sample };
108
- };
109
- const getFindQuery = (query, queryOption) => {
110
- const find = makeSafeQuery(query);
111
- const sort = (0, import_constant.getFilterSort)(database.Filter, queryOption?.sort ?? "latest");
112
- const skip = queryOption?.skip ?? 0;
113
- const select = queryOption?.select;
114
- const sample = queryOption?.sample ?? false;
115
- return { find, sort, skip, select, sample };
116
- };
117
- const getSearchSort = (sortKey) => {
118
- const sort = (0, import_constant.getFilterSort)(database.Filter, sortKey ?? "latest");
119
- return Object.entries(sort).map(([key, value]) => `${key}:${value === 1 ? "asc" : "desc"}`);
120
- };
121
- const loader = (0, import_dataLoader.createLoader)(model);
122
- const cacheDatabase = new CacheDatabase(database.refName, redis);
123
- const searchDatabase = new SearchDatabase(database.refName, meili);
124
- const DatabaseModel = Reflect.getMetadata(database.refName, DatabaseModelStorage.prototype) ?? class DatabaseModel {
125
- logger = new import_common.Logger(`${modelName}Model`);
126
- __model = model;
127
- __cache = cacheDatabase;
128
- __search = searchDatabase;
129
- __loader = loader;
130
- async __list(query, queryOption) {
131
- const { find, sort, skip, limit, select, sample } = getListQuery(query, queryOption);
132
- return sample ? await this.__model.sample(find, limit) : await this.__model.find(find, select).sort(sort).skip(skip).limit(limit);
133
- }
134
- async __listIds(query, queryOption) {
135
- const { find, sort, skip, limit, sample } = getListQuery(query, queryOption);
136
- return (sample ? await this.__model.sample(find, limit, [{ $project: { _id: 1 } }]) : await this.__model.find(find).sort(sort).skip(skip).limit(limit).select("_id")).map(({ _id }) => _id.toString());
137
- }
138
- async __find(query, queryOption) {
139
- const { find, sort, skip, select, sample } = getFindQuery(query, queryOption);
140
- const doc = sample ? await this.__model.sampleOne(find) : await this.__model.findOne(find, select).sort(sort).skip(skip);
141
- if (!doc)
142
- return null;
143
- return doc;
144
- }
145
- async __findId(query, queryOption) {
146
- const { find, sort, skip, sample } = getFindQuery(query, queryOption);
147
- const doc = sample ? await this.__model.sampleOne(find, [{ $project: { _id: 1 } }]) : await this.__model.findOne(find).sort(sort).skip(skip).select("_id");
148
- if (!doc)
149
- return null;
150
- return doc._id.toString();
151
- }
152
- async __pick(query, queryOption) {
153
- const { find, sort, skip, select, sample } = getFindQuery(query, queryOption);
154
- const doc = sample ? await this.__model.sampleOne(find) : await this.__model.findOne(find, select).sort(sort).skip(skip);
155
- if (!doc)
156
- throw new Error(`No Document (${database.refName}): ${JSON.stringify(query)}`);
157
- return doc;
158
- }
159
- async __pickId(query, queryOption) {
160
- const { find, sort, skip, sample } = getFindQuery(query, queryOption);
161
- const doc = sample ? await this.__model.sampleOne(find, [{ $project: { _id: 1 } }]) : await this.__model.findOne(find).sort(sort).skip(skip).select("_id");
162
- if (!doc)
163
- throw new Error(`No Document (${database.refName}): ${JSON.stringify(query)}`);
164
- return doc._id.toString();
165
- }
166
- async __exists(query) {
167
- const find = makeSafeQuery(query);
168
- const existingId = await this.__model.exists(find);
169
- return existingId?.toString() ?? null;
170
- }
171
- async __count(query) {
172
- const find = makeSafeQuery(query);
173
- return await this.__model.countDocuments(find);
174
- }
175
- async __insight(query) {
176
- if (!accumulator)
177
- throw new Error(`No Insight (${database.refName})`);
178
- const res = await this.__model.aggregate([
179
- makeSafeMatchStage(query),
180
- { $group: { _id: null, ...accumulator } }
181
- ]);
182
- const data = res[0];
183
- return data ?? defaultInsight;
184
- }
185
- async getDefaultSummary(addQuery = {}) {
186
- if (!database.Summary)
187
- return {};
188
- const fieldMetas = (0, import_constant.getFieldMetas)(database.Summary);
189
- const summary = {};
190
- await Promise.all(
191
- fieldMetas.filter((fieldMeta) => !!fieldMeta.query).map(async (fieldMeta) => {
192
- const query = typeof fieldMeta.query === "function" ? fieldMeta.query() : fieldMeta.query;
193
- summary[fieldMeta.key] = query ? await model.countDocuments({ ...query, ...addQuery }) : fieldMeta.default;
194
- })
195
- );
196
- return summary;
197
- }
198
- async [`get${className}`](id) {
199
- const doc = await this.__loader.load(id);
200
- if (!doc)
201
- throw new Error(`No Document (${database.refName}): ${id}`);
202
- return doc;
203
- }
204
- async [`load${className}`](id) {
205
- return id ? await this.__loader.load(id) : null;
206
- }
207
- async [`load${className}Many`](ids) {
208
- return await this.__loader.loadMany(ids);
209
- }
210
- async [`create${className}`](data) {
211
- return await new this.__model(data).save();
212
- }
213
- async [`update${className}`](id, data) {
214
- const doc = await this.__model.pickById(id);
215
- return await doc.set(data).save();
216
- }
217
- async [`remove${className}`](id) {
218
- const doc = await this.__model.pickById(id);
219
- return await doc.set({ removedAt: (0, import_base.dayjs)() }).save();
220
- }
221
- async [`search${className}`](searchText, queryOption = {}) {
222
- const { skip, limit, sort } = queryOption;
223
- const { ids, total } = await this.__search.searchIds(searchText, { skip, limit, sort: getSearchSort(sort) });
224
- const docs = await this.__loader.loadMany(ids);
225
- return { docs, count: total };
226
- }
227
- async [`searchDocs${className}`](searchText, queryOption = {}) {
228
- const { skip, limit, sort } = queryOption;
229
- const { ids } = await this.__search.searchIds(searchText, { skip, limit, sort: getSearchSort(sort) });
230
- return await this.__loader.loadMany(ids);
231
- }
232
- async [`searchCount${className}`](searchText) {
233
- return await this.__search.count(searchText);
234
- }
235
- };
236
- DatabaseModel.prototype[className] = model;
237
- DatabaseModel.prototype[`${modelName}Loader`] = loader;
238
- DatabaseModel.prototype[`${modelName}Cache`] = cacheDatabase;
239
- DatabaseModel.prototype[`${modelName}Search`] = searchDatabase;
240
- const getQueryDataFromKey = (queryKey, args) => {
241
- const lastArg = args.at(-1);
242
- const hasQueryOption = lastArg && typeof lastArg === "object" && (typeof lastArg.select === "object" || typeof lastArg.skip === "number" || typeof lastArg.limit === "number" || typeof lastArg.sort === "string");
243
- const queryFn = (0, import_constant.getFilterQuery)(database.Filter, queryKey);
244
- const query = queryFn(...hasQueryOption ? args.slice(0, -1) : args);
245
- const queryOption = hasQueryOption ? lastArg : {};
246
- return { query, queryOption };
247
- };
248
- const filterKeyMetaMap = (0, import_constant.getFilterKeyMetaMapOnPrototype)(database.Filter.prototype);
249
- const queryKeys = [...filterKeyMetaMap.keys()];
250
- queryKeys.forEach((queryKey) => {
251
- const queryFn = (0, import_constant.getFilterQuery)(database.Filter, queryKey);
252
- DatabaseModel.prototype[`list${(0, import_common.capitalize)(queryKey)}`] = async function(...args) {
253
- const { query, queryOption } = getQueryDataFromKey(queryKey, args);
254
- return this.__list(query, queryOption);
255
- };
256
- DatabaseModel.prototype[`listIds${(0, import_common.capitalize)(queryKey)}`] = async function(...args) {
257
- const { query, queryOption } = getQueryDataFromKey(queryKey, args);
258
- return this.__listIds(query, queryOption);
259
- };
260
- DatabaseModel.prototype[`find${(0, import_common.capitalize)(queryKey)}`] = async function(...args) {
261
- const { query, queryOption } = getQueryDataFromKey(queryKey, args);
262
- return this.__find(query, queryOption);
263
- };
264
- DatabaseModel.prototype[`findId${(0, import_common.capitalize)(queryKey)}`] = async function(...args) {
265
- const { query, queryOption } = getQueryDataFromKey(queryKey, args);
266
- return this.__findId(query, queryOption);
267
- };
268
- DatabaseModel.prototype[`pick${(0, import_common.capitalize)(queryKey)}`] = async function(...args) {
269
- const { query, queryOption } = getQueryDataFromKey(queryKey, args);
270
- return this.__pick(query, queryOption);
271
- };
272
- DatabaseModel.prototype[`pickId${(0, import_common.capitalize)(queryKey)}`] = async function(...args) {
273
- const { query, queryOption } = getQueryDataFromKey(queryKey, args);
274
- return this.__pickId(query, queryOption);
275
- };
276
- DatabaseModel.prototype[`exists${(0, import_common.capitalize)(queryKey)}`] = async function(...args) {
277
- const query = queryFn(...args);
278
- return this.__exists(query);
279
- };
280
- DatabaseModel.prototype[`count${(0, import_common.capitalize)(queryKey)}`] = async function(...args) {
281
- const query = queryFn(...args);
282
- return this.__count(query);
283
- };
284
- DatabaseModel.prototype[`insight${(0, import_common.capitalize)(queryKey)}`] = async function(...args) {
285
- const query = queryFn(...args);
286
- return this.__insight(query);
287
- };
288
- });
289
- const loaderMetas = (0, import_dataLoader.getLoaderMetas)(database.Model);
290
- loaderMetas.forEach((loaderMeta) => {
291
- const loader2 = loaderMeta.type === "Field" ? (0, import_dataLoader.createLoader)(model, loaderMeta.fieldName) : loaderMeta.type === "ArrayField" ? (0, import_dataLoader.createArrayLoader)(model, loaderMeta.fieldName) : loaderMeta.type === "Query" ? (0, import_dataLoader.createQueryLoader)(model, loaderMeta.queryKeys ?? []) : null;
292
- DatabaseModel.prototype[loaderMeta.key] = loader2;
293
- });
294
- Object.getOwnPropertyNames(database.Model.prototype).forEach((key) => {
295
- DatabaseModel.prototype[key] = database.Model.prototype[key];
296
- });
297
- const createDescriptor = Object.getOwnPropertyDescriptor(DatabaseModel.prototype, `create${className}`);
298
- if (createDescriptor)
299
- (0, import_serviceDecorators.Transaction)()(DatabaseModel.prototype, `create${className}`, createDescriptor);
300
- const updateDescriptor = Object.getOwnPropertyDescriptor(DatabaseModel.prototype, `update${className}`);
301
- if (updateDescriptor)
302
- (0, import_serviceDecorators.Transaction)()(DatabaseModel.prototype, `update${className}`, updateDescriptor);
303
- const removeDescriptor = Object.getOwnPropertyDescriptor(DatabaseModel.prototype, `remove${className}`);
304
- if (removeDescriptor)
305
- (0, import_serviceDecorators.Transaction)()(DatabaseModel.prototype, `remove${className}`, removeDescriptor);
306
- Reflect.defineMetadata(database.refName, DatabaseModel, DatabaseModelStorage.prototype);
307
- return new DatabaseModel();
308
- };
309
- // Annotate the CommonJS export names for ESM import in node:
310
- 0 && (module.exports = {
311
- databaseModelOf
312
- });
@@ -1,68 +0,0 @@
1
- import { BaseObject, Type } from "@akanjs/base";
2
- import { type ConstantModel, type DocumentModel, type FilterType } from "@akanjs/constant";
3
- import type { FilterQuery, HydratedDocument, Model as MongooseModel, PipelineStage, ProjectionType, Schema } from "mongoose";
4
- import type { DatabaseModel } from "./database";
5
- export type { FilterQuery as QueryOf };
6
- interface DefaultDocMtds<TDocument> {
7
- refresh(): Promise<this>;
8
- set(data: Partial<TDocument>): this;
9
- save(): Promise<this>;
10
- }
11
- type HydratedDocumentWithId<TDocument> = Omit<HydratedDocument<TDocument, DefaultDocMtds<TDocument>>, "id" | "set" | "save"> & {
12
- id: string;
13
- } & DefaultDocMtds<TDocument>;
14
- export type Doc<M> = HydratedDocumentWithId<DocumentModel<M>>;
15
- interface DefaultMdlStats<TDocument, TSchema> {
16
- pickOneAndWrite: (query: FilterQuery<TSchema>, rawData: Partial<TSchema>) => Promise<TDocument>;
17
- pickAndWrite: (docId: string, rawData: Partial<TSchema>) => Promise<TDocument>;
18
- pickOne: (query: FilterQuery<TSchema>, projection?: ProjectionType<TSchema>) => Promise<TDocument>;
19
- pickById: (docId: string | undefined, projection?: ProjectionType<TSchema>) => Promise<TDocument>;
20
- addSummary: (prefix?: string | string[], num?: number) => Promise<void>;
21
- moveSummary: (prev: string, next: string, num?: number) => Promise<void>;
22
- subSummary: (prefix?: string | string[], num?: number) => Promise<void>;
23
- sample: (query: FilterQuery<TSchema>, size?: number, aggregations?: PipelineStage[]) => Promise<TDocument[]>;
24
- sampleOne: (query: FilterQuery<TSchema>, aggregations?: PipelineStage[]) => Promise<TDocument | null>;
25
- }
26
- export type Mdl<Doc extends HydratedDocument<any>, Raw> = MongooseModel<Raw, unknown, unknown, unknown, Doc> & DefaultMdlStats<Doc, DocumentModel<Raw>>;
27
- export type SchemaOf<Mdl, Doc> = Schema<null, Mdl, Doc, undefined, null, Mdl>;
28
- export interface BaseMiddleware {
29
- onSchema: (schema: SchemaOf<any, any>) => void;
30
- }
31
- export interface Database<T extends string, Input, Doc extends HydratedDocument<any>, Model, Middleware extends BaseMiddleware, Obj, Insight, Filter extends FilterType, Summary> {
32
- refName: T;
33
- Input: Type<Input>;
34
- Doc: Type<Doc>;
35
- Model: Type<Model>;
36
- Middleware: Type<Middleware>;
37
- Obj: Type<Obj>;
38
- Insight: Type<Insight>;
39
- Filter: Type<Filter>;
40
- Summary?: Type<Summary>;
41
- }
42
- export declare const dbOf: <T extends string, Input, Doc extends HydratedDocument<any>, Model extends DatabaseModel<T, Input, any, Obj, Insight, Filter>, Middleware extends BaseMiddleware, Obj, Insight, Filter extends FilterType, Summary>(refName: T, Input: Type<Input>, Doc: Type<Doc>, Model: Type<Model>, Middleware: Type<Middleware>, Obj: Type<Obj>, Insight: Type<Insight>, Filter: Type<Filter>, Summary?: Type<Summary>) => Database<T, Input, Doc, Model, Middleware, Obj, Insight, Filter, Summary>;
43
- export declare class InputDatabaseStorage {
44
- }
45
- export declare class DocumentDatabaseStorage {
46
- }
47
- export declare class ModelDatabaseStorage {
48
- }
49
- export declare class MiddlewareDatabaseStorage {
50
- }
51
- export declare const getAllDatabaseModelNames: () => string[];
52
- export declare const Database: {
53
- Input: (returns: () => Type) => (target: any) => void;
54
- Document: (returns: () => Type) => (target: any) => void;
55
- Model: (returns: () => Type) => (target: any) => void;
56
- Middleware: (returns: () => Type) => (target: any) => void;
57
- };
58
- export declare const Model: <Doc, T extends string, Input, Full, Light, Insight, Summary, Filter extends FilterType>(docRef: Type<Doc>, cnst: ConstantModel<T, Input, Full, Light, Insight, Filter, Summary>) => Type<DatabaseModel<T, DocumentModel<Input>, Doc, Full, Insight, Filter, Summary>>;
59
- export declare const AddModel: <Doc, T extends string, Input, Full, Light, Insight, Filter extends FilterType, Summary>(modelRef: Type, cnst: ConstantModel<T, Input, Full, Light, Insight, Filter, Summary>) => Type<DatabaseModel<T, DocumentModel<Input>, Doc, Full, Insight, Filter, Summary>>;
60
- export declare const Input: <InputModel>(inputRef: Type<InputModel>) => Type<DocumentModel<InputModel>>;
61
- export declare const AddInput: <A, B>(modelRef: Type<A>, addRef: Type<B>) => Type<A & DocumentModel<B>>;
62
- export declare const Document: <ObjectModel>(objectRef: Type<ObjectModel>) => Type<ObjectModel extends BaseObject ? Doc<ObjectModel> : DocumentModel<ObjectModel>>;
63
- export declare const AddDocument: <A, B>(modelRef: Type<A>, addRef: Type<B>) => Type<A & Doc<B>>;
64
- export declare const Middleware: <DbModel, Doc>(model: Type<DbModel>, doc: Type<Doc>) => {
65
- new (): {
66
- onSchema(schema: SchemaOf<DbModel, Doc>): void;
67
- };
68
- };
@@ -1,130 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
- var __getOwnPropNames = Object.getOwnPropertyNames;
4
- var __hasOwnProp = Object.prototype.hasOwnProperty;
5
- var __export = (target, all) => {
6
- for (var name in all)
7
- __defProp(target, name, { get: all[name], enumerable: true });
8
- };
9
- var __copyProps = (to, from, except, desc) => {
10
- if (from && typeof from === "object" || typeof from === "function") {
11
- for (let key of __getOwnPropNames(from))
12
- if (!__hasOwnProp.call(to, key) && key !== except)
13
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
- }
15
- return to;
16
- };
17
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
- var dbDecorators_exports = {};
19
- __export(dbDecorators_exports, {
20
- AddDocument: () => AddDocument,
21
- AddInput: () => AddInput,
22
- AddModel: () => AddModel,
23
- Database: () => Database,
24
- Document: () => Document,
25
- DocumentDatabaseStorage: () => DocumentDatabaseStorage,
26
- Input: () => Input,
27
- InputDatabaseStorage: () => InputDatabaseStorage,
28
- Middleware: () => Middleware,
29
- MiddlewareDatabaseStorage: () => MiddlewareDatabaseStorage,
30
- Model: () => Model,
31
- ModelDatabaseStorage: () => ModelDatabaseStorage,
32
- dbOf: () => dbOf,
33
- getAllDatabaseModelNames: () => getAllDatabaseModelNames
34
- });
35
- module.exports = __toCommonJS(dbDecorators_exports);
36
- var import_constant = require("@akanjs/constant");
37
- const dbOf = (refName, Input2, Doc, Model2, Middleware2, Obj, Insight, Filter, Summary) => {
38
- return { refName, Input: Input2, Doc, Model: Model2, Middleware: Middleware2, Obj, Insight, Filter, Summary };
39
- };
40
- class InputDatabaseStorage {
41
- }
42
- class DocumentDatabaseStorage {
43
- }
44
- class ModelDatabaseStorage {
45
- }
46
- class MiddlewareDatabaseStorage {
47
- }
48
- const getAllDatabaseModelNames = () => {
49
- const modelNames = Reflect.getMetadataKeys(ModelDatabaseStorage.prototype) ?? [];
50
- return modelNames;
51
- };
52
- const Database = {
53
- Input: (returns) => {
54
- return function(target) {
55
- const modelRef = returns();
56
- const classMeta = (0, import_constant.getClassMeta)(modelRef);
57
- Reflect.defineMetadata(classMeta.refName, target, InputDatabaseStorage.prototype);
58
- };
59
- },
60
- Document: (returns) => {
61
- return function(target) {
62
- const modelRef = returns();
63
- const classMeta = (0, import_constant.getClassMeta)(modelRef);
64
- Reflect.defineMetadata(classMeta.refName, target, DocumentDatabaseStorage.prototype);
65
- };
66
- },
67
- Model: (returns) => {
68
- return function(target) {
69
- const modelRef = returns();
70
- const classMeta = (0, import_constant.getClassMeta)(modelRef);
71
- Reflect.defineMetadata(classMeta.refName, target, ModelDatabaseStorage.prototype);
72
- };
73
- },
74
- Middleware: (returns) => {
75
- return function(target) {
76
- const modelRef = returns();
77
- const classMeta = (0, import_constant.getClassMeta)(modelRef);
78
- Reflect.defineMetadata(classMeta.refName, target, MiddlewareDatabaseStorage.prototype);
79
- };
80
- }
81
- };
82
- const Model = (docRef, cnst) => {
83
- class DefaultModel {
84
- }
85
- return DefaultModel;
86
- };
87
- const AddModel = (modelRef, cnst) => {
88
- return modelRef;
89
- };
90
- const Input = (inputRef) => {
91
- return inputRef;
92
- };
93
- const AddInput = (modelRef, addRef) => {
94
- const fieldMetaMap = (0, import_constant.getFieldMetaMap)(modelRef);
95
- const addFieldMetas = (0, import_constant.getFieldMetaMap)(addRef);
96
- (0, import_constant.setFieldMetaMap)(modelRef, new Map([...fieldMetaMap, ...addFieldMetas]));
97
- return modelRef;
98
- };
99
- const Document = (objectRef) => {
100
- return objectRef;
101
- };
102
- const AddDocument = (modelRef, addRef) => {
103
- const fieldMetaMap = (0, import_constant.getFieldMetaMap)(modelRef);
104
- const addFieldMetas = (0, import_constant.getFieldMetaMap)(addRef);
105
- (0, import_constant.setFieldMetaMap)(modelRef, new Map([...fieldMetaMap, ...addFieldMetas]));
106
- return modelRef;
107
- };
108
- const Middleware = (model, doc) => {
109
- return class Middleware {
110
- onSchema(schema) {
111
- }
112
- };
113
- };
114
- // Annotate the CommonJS export names for ESM import in node:
115
- 0 && (module.exports = {
116
- AddDocument,
117
- AddInput,
118
- AddModel,
119
- Database,
120
- Document,
121
- DocumentDatabaseStorage,
122
- Input,
123
- InputDatabaseStorage,
124
- Middleware,
125
- MiddlewareDatabaseStorage,
126
- Model,
127
- ModelDatabaseStorage,
128
- dbOf,
129
- getAllDatabaseModelNames
130
- });