@akanjs/server 0.0.4

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.
@@ -0,0 +1,142 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
+ // If the importer is in node compatibility mode or this is not an ESM
21
+ // file that has been converted to a CommonJS file using a Babel-
22
+ // compatible transform (i.e. "__esModule" has not been set), then set
23
+ // "default" to the CommonJS "module.exports" for node compatibility.
24
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
+ mod
26
+ ));
27
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
+ var resolver_exports = {};
29
+ __export(resolver_exports, {
30
+ resolverOf: () => resolverOf
31
+ });
32
+ module.exports = __toCommonJS(resolver_exports);
33
+ var import_base = require("@akanjs/base");
34
+ var import_common = require("@akanjs/common");
35
+ var import_constant = require("@akanjs/constant");
36
+ var import_nest = require("@akanjs/nest");
37
+ var import_signal = require("@akanjs/signal");
38
+ var import_common2 = require("@nestjs/common");
39
+ var Nest = __toESM(require("@nestjs/graphql"));
40
+ var import_graphql_type_json = __toESM(require("graphql-type-json"));
41
+ var import_graphql_upload = require("graphql-upload");
42
+ var import_gql = require("./gql");
43
+ const scalarNestReturnMap = /* @__PURE__ */ new Map([
44
+ [import_base.Upload, import_graphql_upload.GraphQLUpload],
45
+ [import_base.ID, Nest.ID],
46
+ [import_base.Int, Nest.Int],
47
+ [import_base.Float, Nest.Float],
48
+ [import_base.JSON, import_graphql_type_json.default],
49
+ [Boolean, Boolean],
50
+ [Date, Date],
51
+ [String, String],
52
+ [Map, import_graphql_type_json.default]
53
+ ]);
54
+ const getNestReturn = (returns, type = "object") => {
55
+ const [model, arrDepth] = (0, import_base.getNonArrayModel)(returns());
56
+ const modelRef = scalarNestReturnMap.get(model) ?? (type === "object" ? (0, import_gql.generateGql)(model) : (0, import_gql.generateGqlInput)(model));
57
+ return () => (0, import_base.arraiedModel)(modelRef, arrDepth);
58
+ };
59
+ const internalArgMap = {
60
+ Parent: Nest.Parent,
61
+ Account: import_nest.Account,
62
+ UserIp: import_nest.UserIp,
63
+ Access: import_nest.Access,
64
+ Self: import_nest.Self,
65
+ Me: import_nest.Me,
66
+ Req: import_nest.Req,
67
+ Res: import_nest.Res
68
+ };
69
+ const resolverOf = (sigRef, allSrvs) => {
70
+ const Rsv = (0, import_signal.copySignal)(sigRef);
71
+ const sigMeta = (0, import_signal.getSigMeta)(Rsv);
72
+ const gqlMetas = (0, import_signal.getGqlMetas)(Rsv);
73
+ Object.keys(allSrvs).forEach((srv) => {
74
+ (0, import_common2.Inject)(allSrvs[srv])(Rsv.prototype, (0, import_common.lowerlize)(srv));
75
+ });
76
+ for (const gqlMeta of gqlMetas) {
77
+ if (gqlMeta.guards.some((guard) => guard === "None") || gqlMeta.signalOption.onlyFor === "restapi" || !["Query", "Mutation"].includes(gqlMeta.type))
78
+ continue;
79
+ else if (gqlMeta.signalOption.sso)
80
+ continue;
81
+ const [argMetas, internalArgMetas] = (0, import_signal.getArgMetas)(Rsv, gqlMeta.key);
82
+ const descriptor = Object.getOwnPropertyDescriptor(Rsv.prototype, gqlMeta.key) ?? {};
83
+ for (const argMeta of argMetas) {
84
+ Nest.Args({
85
+ name: argMeta.name,
86
+ type: getNestReturn(argMeta.returns, "input"),
87
+ ...argMeta.argsOption
88
+ })(Rsv.prototype, gqlMeta.key, argMeta.idx);
89
+ }
90
+ for (const internalArgMeta of internalArgMetas) {
91
+ const decorate = internalArgMap[internalArgMeta.type];
92
+ decorate(internalArgMeta.option ?? {})(Rsv.prototype, gqlMeta.key, internalArgMeta.idx);
93
+ }
94
+ (0, import_common2.UseGuards)(...gqlMeta.guards.map((guard) => import_nest.guards[guard]))(Rsv.prototype, gqlMeta.key, descriptor);
95
+ if (gqlMeta.type === "Query")
96
+ Nest.Query(getNestReturn(gqlMeta.returns), gqlMeta.signalOption)(Rsv.prototype, gqlMeta.key, descriptor);
97
+ else if (gqlMeta.type === "Mutation")
98
+ Nest.Mutation(getNestReturn(gqlMeta.returns), gqlMeta.signalOption)(Rsv.prototype, gqlMeta.key, descriptor);
99
+ }
100
+ const resolveFieldMetas = (0, import_signal.getResolveFieldMetas)(Rsv);
101
+ if (sigMeta.returns) {
102
+ const modelRef = sigMeta.returns();
103
+ const fieldMetas = (0, import_constant.getFieldMetas)(modelRef);
104
+ fieldMetas.filter((fieldMeta) => fieldMeta.isClass && !fieldMeta.isScalar).forEach((fieldMeta) => {
105
+ const classMeta = (0, import_constant.getClassMeta)(fieldMeta.modelRef);
106
+ const modelName = (0, import_common.lowerlize)(classMeta.type === "light" ? classMeta.refName.slice(5) : classMeta.refName);
107
+ const className = (0, import_common.capitalize)(modelName);
108
+ const serviceName = `${modelName}Service`;
109
+ Rsv.prototype[fieldMeta.key] = async function(parent) {
110
+ const service = this[serviceName];
111
+ return fieldMeta.arrDepth ? await service[`load${className}Many`](parent[fieldMeta.key]) : await service[`load${className}`](parent[fieldMeta.key]);
112
+ };
113
+ Nest.Parent()(Rsv.prototype, fieldMeta.key, 0);
114
+ Nest.ResolveField(getNestReturn(() => (0, import_base.arraiedModel)(fieldMeta.modelRef, fieldMeta.arrDepth)))(
115
+ Rsv.prototype,
116
+ fieldMeta.key,
117
+ Object.getOwnPropertyDescriptor(Rsv.prototype, fieldMeta.key) ?? {}
118
+ );
119
+ });
120
+ }
121
+ for (const resolveFieldMeta of resolveFieldMetas) {
122
+ const [, internalArgMetas] = (0, import_signal.getArgMetas)(Rsv, resolveFieldMeta.key);
123
+ for (const internalArgMeta of internalArgMetas) {
124
+ const decorate = internalArgMap[internalArgMeta.type];
125
+ decorate(internalArgMeta.option ?? {})(Rsv.prototype, resolveFieldMeta.key, internalArgMeta.idx);
126
+ }
127
+ Nest.ResolveField(getNestReturn(resolveFieldMeta.returns))(
128
+ Rsv.prototype,
129
+ resolveFieldMeta.key,
130
+ Object.getOwnPropertyDescriptor(Rsv.prototype, resolveFieldMeta.key) ?? {}
131
+ );
132
+ }
133
+ if (sigMeta.returns)
134
+ Nest.Resolver(getNestReturn(sigMeta.returns))(Rsv);
135
+ else
136
+ Nest.Resolver()(Rsv);
137
+ return Rsv;
138
+ };
139
+ // Annotate the CommonJS export names for ESM import in node:
140
+ 0 && (module.exports = {
141
+ resolverOf
142
+ });
@@ -0,0 +1,33 @@
1
+ import { Type } from "@akanjs/base";
2
+ import { FilterQuery, PipelineStage, type ProjectionType, Schema } from "mongoose";
3
+ import { type BaseMiddleware } from ".";
4
+ export declare const getDefaultSchemaOptions: <TSchema, TDocument>() => {
5
+ toJSON: {
6
+ getters: boolean;
7
+ virtuals: boolean;
8
+ };
9
+ toObject: {
10
+ getters: boolean;
11
+ virtuals: boolean;
12
+ };
13
+ _id: boolean;
14
+ id: boolean;
15
+ timestamps: boolean;
16
+ methods: {
17
+ refresh: () => Promise<any>;
18
+ };
19
+ statics: {
20
+ pickOne: (query: FilterQuery<TSchema>, projection?: ProjectionType<TSchema>) => Promise<TDocument>;
21
+ pickById: (docId: string | undefined, projection?: ProjectionType<TSchema>) => Promise<TDocument>;
22
+ sample: (query: FilterQuery<TSchema>, size?: number, aggregations?: PipelineStage[]) => Promise<TDocument[]>;
23
+ sampleOne: (query: FilterQuery<TSchema>, aggregations?: PipelineStage[]) => Promise<TDocument | null>;
24
+ addSummary: (prefix?: string, num?: number) => Promise<void>;
25
+ moveSummary: (prev: string, next: string, num?: number) => Promise<void>;
26
+ subSummary: (prefix?: string, num?: number) => Promise<void>;
27
+ };
28
+ };
29
+ export declare const schemaOf: <Mdl, Doc, Middleware extends BaseMiddleware>(modelRef: Type<Mdl>, docRef: Type<Doc>, middleware: Type<Middleware>) => Schema<null, Mdl, Doc, undefined, null, Mdl>;
30
+ export declare const addSchema: <Mdl, Doc, Input, Middleware extends BaseMiddleware>(modelRef: Type<Mdl>, docRef: Type<Doc>, inputRef: Type<Input>, middleware: Type<Middleware>) => Schema<null, Mdl, Doc, undefined, null, Mdl>;
31
+ export declare const convertAggregateMatch: (query: any) => {
32
+ [k: string]: any;
33
+ };
package/src/schema.js ADDED
@@ -0,0 +1,343 @@
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 schema_exports = {};
19
+ __export(schema_exports, {
20
+ addSchema: () => addSchema,
21
+ convertAggregateMatch: () => convertAggregateMatch,
22
+ getDefaultSchemaOptions: () => getDefaultSchemaOptions,
23
+ schemaOf: () => schemaOf
24
+ });
25
+ module.exports = __toCommonJS(schema_exports);
26
+ var import_base = require("@akanjs/base");
27
+ var import_common = require("@akanjs/common");
28
+ var import_constant = require("@akanjs/constant");
29
+ var import_signal = require("@akanjs/signal");
30
+ var import_mongoose = require("mongoose");
31
+ var import__ = require(".");
32
+ class ScalarSchemaStorage {
33
+ }
34
+ class SchemaStorage {
35
+ }
36
+ const getDefaultSchemaOptions = () => ({
37
+ toJSON: { getters: false, virtuals: true },
38
+ toObject: { getters: false, virtuals: true },
39
+ _id: true,
40
+ id: true,
41
+ timestamps: true,
42
+ methods: {
43
+ refresh: async function() {
44
+ Object.assign(this, await this.constructor.findById(this._id));
45
+ return this;
46
+ }
47
+ },
48
+ statics: {
49
+ pickOne: async function(query, projection) {
50
+ const doc = await this.findOne(query, projection);
51
+ if (!doc)
52
+ throw new Error("No Document");
53
+ return doc;
54
+ },
55
+ pickById: async function(docId, projection) {
56
+ if (!docId)
57
+ throw new Error("No Document ID");
58
+ const doc = await this.findById(docId, projection);
59
+ if (!doc)
60
+ throw new Error("No Document");
61
+ return doc;
62
+ },
63
+ sample: async function(query, size = 1, aggregations = []) {
64
+ const objs = await this.aggregate([
65
+ { $match: convertAggregateMatch(query) },
66
+ { $sample: { size } },
67
+ ...aggregations
68
+ ]);
69
+ return objs.map((obj) => new this(obj));
70
+ },
71
+ sampleOne: async function(query, aggregations = []) {
72
+ const obj = await this.aggregate([
73
+ { $match: convertAggregateMatch(query) },
74
+ { $sample: { size: 1 } },
75
+ ...aggregations
76
+ ]);
77
+ return obj.length ? new this(obj[0]) : null;
78
+ },
79
+ addSummary: async function(prefix = "total", num = 1) {
80
+ const update = Array.isArray(prefix) ? {
81
+ $inc: {
82
+ ...prefix.reduce((acc, cur) => ({ ...acc, [`${cur}${this.modelName}`]: num }), {})
83
+ }
84
+ } : { $inc: { [`${prefix}${this.modelName}`]: num } };
85
+ await this.db.collection("summaries").updateOne({ status: "active" }, update);
86
+ },
87
+ moveSummary: async function(prev, next, num = 1) {
88
+ await this.db.collection("summaries").updateOne(
89
+ { status: "active" },
90
+ {
91
+ $inc: {
92
+ [`${prev}${this.modelName}`]: -num,
93
+ [`${next}${this.modelName}`]: num
94
+ }
95
+ }
96
+ );
97
+ },
98
+ subSummary: async function(prefix = "total", num = 1) {
99
+ const update = Array.isArray(prefix) ? {
100
+ $inc: {
101
+ ...prefix.reduce((acc, cur) => ({ ...acc, [`${cur}${this.modelName}`]: -num }), {})
102
+ }
103
+ } : { $inc: { [`${prefix}${this.modelName}`]: -num } };
104
+ await this.db.collection("summaries").updateOne({ status: "active" }, update);
105
+ }
106
+ }
107
+ });
108
+ const scalarMongoTypeMap = /* @__PURE__ */ new Map([
109
+ [import_base.ID, import__.ObjectId],
110
+ [import_base.Int, Number],
111
+ [import_base.Float, Number],
112
+ [import_base.JSON, import_mongoose.Schema.Types.Mixed],
113
+ [Map, Map],
114
+ [String, String],
115
+ [Boolean, Boolean],
116
+ [Date, Date]
117
+ ]);
118
+ const applyMongoProp = (schemaProps, fieldMeta) => {
119
+ if (["id", "createdAt", "updatedAt"].includes(fieldMeta.key) || fieldMeta.fieldType === "resolve")
120
+ return;
121
+ const type = fieldMeta.isClass ? fieldMeta.isScalar ? createSchema(fieldMeta.modelRef) : import__.ObjectId : scalarMongoTypeMap.get(fieldMeta.modelRef) ?? fieldMeta.modelRef;
122
+ let prop = {};
123
+ if (fieldMeta.optArrDepth) {
124
+ prop.type = type;
125
+ prop.required = true;
126
+ if (fieldMeta.isClass && !fieldMeta.refPath)
127
+ prop.ref = (0, import_constant.getClassMeta)(fieldMeta.modelRef).refName;
128
+ if (fieldMeta.refPath)
129
+ prop.refPath = fieldMeta.refPath;
130
+ if (typeof fieldMeta.min === "number")
131
+ prop.min = fieldMeta.min;
132
+ if (typeof fieldMeta.max === "number")
133
+ prop.max = fieldMeta.max;
134
+ if (fieldMeta.enum)
135
+ prop.enum = [...fieldMeta.enum.values, ...fieldMeta.nullable ? [null] : []];
136
+ if (typeof fieldMeta.minlength === "number")
137
+ prop.minlength = fieldMeta.minlength;
138
+ if (typeof fieldMeta.maxlength === "number")
139
+ prop.maxlength = fieldMeta.maxlength;
140
+ if (fieldMeta.validate) {
141
+ prop.validate = function(value) {
142
+ return fieldMeta.validate?.(fieldMeta.name === "Date" && !!value ? (0, import_base.dayjs)() : value, this) ?? true;
143
+ };
144
+ }
145
+ prop = { type: (0, import_base.arraiedModel)(prop, fieldMeta.optArrDepth), default: [], required: true };
146
+ if (fieldMeta.modelRef.prototype === Date.prototype) {
147
+ prop.get = (dates) => dates.map((date) => (0, import_base.dayjs)(date));
148
+ prop.set = (days) => days.map((day) => day.toDate());
149
+ }
150
+ if (fieldMeta.isClass && !fieldMeta.isScalar || fieldMeta.modelRef.prototype === import_base.ID.prototype) {
151
+ prop.get = (ids) => ids.map((id) => id.toString());
152
+ prop.set = (ids) => ids.map((id) => new import_mongoose.Types.ObjectId(id));
153
+ }
154
+ } else {
155
+ prop.type = (0, import_base.arraiedModel)(type, fieldMeta.arrDepth);
156
+ prop.required = !fieldMeta.nullable;
157
+ if (fieldMeta.isMap) {
158
+ prop.of = scalarMongoTypeMap.get(fieldMeta.of) ?? createSchema(fieldMeta.of);
159
+ if (!fieldMeta.default)
160
+ prop.default = /* @__PURE__ */ new Map();
161
+ }
162
+ if (fieldMeta.default !== null) {
163
+ if (typeof fieldMeta.default === "function")
164
+ prop.default = function() {
165
+ const def = fieldMeta.default(this);
166
+ return (0, import_common.isDayjs)(def) ? def.toDate() : def;
167
+ };
168
+ else
169
+ prop.default = (0, import_common.isDayjs)(fieldMeta.default) ? fieldMeta.default.toDate() : fieldMeta.default instanceof import_base.Enum ? [...fieldMeta.default.values] : fieldMeta.default;
170
+ }
171
+ if (typeof fieldMeta.immutable !== "undefined")
172
+ prop.immutable = fieldMeta.immutable;
173
+ if (fieldMeta.isClass && !fieldMeta.refPath)
174
+ prop.ref = (0, import_constant.getClassMeta)(fieldMeta.modelRef).refName;
175
+ if (fieldMeta.refPath)
176
+ prop.refPath = fieldMeta.refPath;
177
+ if (typeof fieldMeta.min === "number")
178
+ prop.min = fieldMeta.min;
179
+ if (typeof fieldMeta.max === "number")
180
+ prop.max = fieldMeta.max;
181
+ if (fieldMeta.enum)
182
+ prop.enum = [...fieldMeta.enum.values, ...fieldMeta.nullable ? [null] : []];
183
+ if (typeof fieldMeta.select === "boolean")
184
+ prop.select = fieldMeta.select;
185
+ if (typeof fieldMeta.minlength === "number")
186
+ prop.minlength = fieldMeta.minlength;
187
+ if (typeof fieldMeta.maxlength === "number")
188
+ prop.maxlength = fieldMeta.maxlength;
189
+ if (fieldMeta.nullable) {
190
+ prop.get = (v) => v === void 0 ? void 0 : v;
191
+ prop.set = (v) => v === null ? void 0 : v;
192
+ }
193
+ if (fieldMeta.modelRef.prototype === Date.prototype) {
194
+ prop.get = (date) => date ? (0, import_base.dayjs)(date) : void 0;
195
+ prop.set = (day) => day ? (0, import_base.dayjs)(day).toDate() : void 0;
196
+ }
197
+ if (fieldMeta.isClass && !fieldMeta.isScalar || fieldMeta.modelRef.prototype === import_base.ID.prototype) {
198
+ prop.get = (id) => id ? id.toString() : void 0;
199
+ prop.set = (id) => id ? new import_mongoose.Types.ObjectId(id) : void 0;
200
+ }
201
+ if (fieldMeta.isClass && fieldMeta.isScalar && fieldMeta.default === null && !fieldMeta.nullable) {
202
+ prop.default = (0, import_signal.makeDefault)(fieldMeta.modelRef);
203
+ }
204
+ if (fieldMeta.validate) {
205
+ prop.validate = function(value) {
206
+ return fieldMeta.validate?.(fieldMeta.name === "Date" && !!value ? (0, import_base.dayjs)() : value, this) ?? true;
207
+ };
208
+ }
209
+ }
210
+ schemaProps[fieldMeta.key] = prop;
211
+ };
212
+ const createSchema = (modelRef) => {
213
+ const classMeta = (0, import_constant.getClassMeta)(modelRef);
214
+ const schemaMeta = Reflect.getMetadata(classMeta.refName, ScalarSchemaStorage.prototype);
215
+ if (schemaMeta)
216
+ return schemaMeta;
217
+ const fieldMetas = (0, import_constant.getFieldMetas)(modelRef);
218
+ const schemaProps = {};
219
+ fieldMetas.forEach((fieldMeta) => {
220
+ applyMongoProp(schemaProps, fieldMeta);
221
+ });
222
+ const schema = new import_mongoose.Schema(schemaProps);
223
+ Reflect.defineMetadata(classMeta.refName, schema, ScalarSchemaStorage.prototype);
224
+ return schema;
225
+ };
226
+ const schemaOf = (modelRef, docRef, middleware) => {
227
+ const classMeta = (0, import_constant.getClassMeta)(docRef);
228
+ const schemaMeta = Reflect.getMetadata(classMeta.refName, SchemaStorage.prototype);
229
+ if (schemaMeta)
230
+ return schemaMeta;
231
+ const fieldMetas = (0, import_constant.getFieldMetas)(docRef);
232
+ const schemaProps = {
233
+ createdAt: {
234
+ type: Date,
235
+ get: (date) => date ? (0, import_base.dayjs)(date) : date,
236
+ set: (day) => day ? (0, import_base.dayjs)(day).toDate() : day
237
+ },
238
+ updatedAt: {
239
+ type: Date,
240
+ get: (date) => date ? (0, import_base.dayjs)(date) : date,
241
+ set: (day) => day ? (0, import_base.dayjs)(day).toDate() : day
242
+ }
243
+ };
244
+ fieldMetas.forEach((fieldMeta) => {
245
+ applyMongoProp(schemaProps, fieldMeta);
246
+ });
247
+ const schema = new import_mongoose.Schema(schemaProps, getDefaultSchemaOptions());
248
+ schema.methods.refresh = async function() {
249
+ Object.assign(this, await this.constructor.findById(this._id));
250
+ return this;
251
+ };
252
+ Object.getOwnPropertyNames(docRef.prototype).forEach((name) => {
253
+ if (name === "constructor")
254
+ return;
255
+ schema.methods[name] = Object.getOwnPropertyDescriptor(docRef.prototype, name)?.value;
256
+ });
257
+ schema.pre("save", async function(next) {
258
+ const model = this.constructor;
259
+ if (this.isNew)
260
+ model.addSummary(["total", this.status]);
261
+ else if (!!this.removedAt && this.isModified("removedAt"))
262
+ model.subSummary(["total", this.status]);
263
+ next();
264
+ });
265
+ const onSchema = Object.getOwnPropertyDescriptor(middleware.prototype, "onSchema")?.value;
266
+ onSchema?.(schema);
267
+ schema.index({ removedAt: -1 });
268
+ Reflect.defineMetadata(classMeta.refName, schema, SchemaStorage.prototype);
269
+ return schema;
270
+ };
271
+ const addSchema = (modelRef, docRef, inputRef, middleware) => {
272
+ const originDocClassMeta = (0, import_constant.getClassMeta)(docRef);
273
+ const originInputClassMeta = (0, import_constant.getClassMeta)(inputRef);
274
+ const originDoc = (0, import_constant.getFullModelRef)(originDocClassMeta.refName);
275
+ const originInput = (0, import_constant.getInputModelRef)(originInputClassMeta.refName);
276
+ const classMeta = (0, import_constant.getClassMeta)(docRef);
277
+ const modelSchema = Reflect.getMetadata(classMeta.refName, SchemaStorage.prototype);
278
+ if (!modelSchema)
279
+ throw new Error(`Schema of ${classMeta.refName} not found`);
280
+ const fieldMetas = (0, import_constant.getFieldMetas)(docRef);
281
+ const schemaProps = {
282
+ createdAt: {
283
+ type: Date,
284
+ get: (date) => date ? (0, import_base.dayjs)(date) : date,
285
+ set: (day) => day ? (0, import_base.dayjs)(day).toDate() : day
286
+ },
287
+ updatedAt: {
288
+ type: Date,
289
+ get: (date) => date ? (0, import_base.dayjs)(date) : date,
290
+ set: (day) => day ? (0, import_base.dayjs)(day).toDate() : day
291
+ }
292
+ };
293
+ fieldMetas.forEach((fieldMeta) => {
294
+ applyMongoProp(schemaProps, fieldMeta);
295
+ (0, import__.applyNestField)(originDoc, fieldMeta);
296
+ });
297
+ const inputFieldMetas = (0, import_constant.getFieldMetas)(inputRef);
298
+ inputFieldMetas.forEach((fieldMeta) => {
299
+ (0, import__.applyNestField)(originInput, fieldMeta, "input");
300
+ });
301
+ const schema = new import_mongoose.Schema(schemaProps, getDefaultSchemaOptions());
302
+ modelSchema.add(schema);
303
+ Object.getOwnPropertyNames(docRef.prototype).forEach((name) => {
304
+ if (name === "constructor")
305
+ return;
306
+ modelSchema.methods[name] = Object.getOwnPropertyDescriptor(docRef.prototype, name)?.value;
307
+ });
308
+ const onSchema = Object.getOwnPropertyDescriptor(middleware.prototype, "onSchema")?.value;
309
+ onSchema?.(modelSchema);
310
+ return modelSchema;
311
+ };
312
+ const convertOperatorValue = (value) => {
313
+ if (Array.isArray(value))
314
+ return value.map((v) => convertOperatorValue(v));
315
+ else if (!value)
316
+ return value;
317
+ else if ((0, import_mongoose.isValidObjectId)(value))
318
+ return new import_mongoose.Types.ObjectId(value);
319
+ else if ((0, import_common.isValidDate)(value))
320
+ return (0, import_base.dayjs)(value).toDate();
321
+ else if (value.constructor !== Object)
322
+ return value;
323
+ else if (typeof value !== "object")
324
+ return value;
325
+ else
326
+ return Object.fromEntries(
327
+ Object.entries(value).map(([key, value2]) => [key, convertOperatorValue(value2)])
328
+ );
329
+ };
330
+ const convertAggregateMatch = (query) => {
331
+ return Object.fromEntries(
332
+ Object.entries(query).map(([key, value]) => {
333
+ return [key, convertOperatorValue(value)];
334
+ })
335
+ );
336
+ };
337
+ // Annotate the CommonJS export names for ESM import in node:
338
+ 0 && (module.exports = {
339
+ addSchema,
340
+ convertAggregateMatch,
341
+ getDefaultSchemaOptions,
342
+ schemaOf
343
+ });
@@ -0,0 +1,7 @@
1
+ import type { Type } from "@akanjs/base";
2
+ import { type TextDoc } from "@akanjs/constant";
3
+ export declare const makeTextFilter: (modelRef: Type) => (data: Record<string, any>, assignObj?: {
4
+ [key: string]: string;
5
+ }) => TextDoc;
6
+ export declare class SearchDaemonModule {
7
+ }