@akanjs/server 0.0.40 → 0.0.41

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/schema.js DELETED
@@ -1,275 +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 __name = (target, value) => __defProp(target, "name", { value, configurable: true });
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
- var schema_exports = {};
20
- __export(schema_exports, {
21
- addSchema: () => addSchema,
22
- schemaOf: () => schemaOf
23
- });
24
- module.exports = __toCommonJS(schema_exports);
25
- var import_base = require("@akanjs/base");
26
- var import_common = require("@akanjs/common");
27
- var import_constant = require("@akanjs/constant");
28
- var import_document = require("@akanjs/document");
29
- var import_signal = require("@akanjs/signal");
30
- var import_mongoose = require("mongoose");
31
- var import__ = require(".");
32
- let ScalarSchemaStorage = class ScalarSchemaStorage2 {
33
- static {
34
- __name(this, "ScalarSchemaStorage");
35
- }
36
- };
37
- let SchemaStorage = class SchemaStorage2 {
38
- static {
39
- __name(this, "SchemaStorage");
40
- }
41
- };
42
- const scalarMongoTypeMap = /* @__PURE__ */ new Map([
43
- [
44
- import_base.ID,
45
- import_document.ObjectId
46
- ],
47
- [
48
- import_base.Int,
49
- Number
50
- ],
51
- [
52
- import_base.Float,
53
- Number
54
- ],
55
- [
56
- import_base.JSON,
57
- import_mongoose.Schema.Types.Mixed
58
- ],
59
- [
60
- Map,
61
- Map
62
- ],
63
- [
64
- String,
65
- String
66
- ],
67
- [
68
- Boolean,
69
- Boolean
70
- ],
71
- [
72
- Date,
73
- Date
74
- ]
75
- ]);
76
- const applyMongoProp = /* @__PURE__ */ __name((schemaProps, fieldMeta) => {
77
- if ([
78
- "id",
79
- "createdAt",
80
- "updatedAt"
81
- ].includes(fieldMeta.key) || fieldMeta.fieldType === "resolve") return;
82
- const type = fieldMeta.isClass ? fieldMeta.isScalar ? createSchema(fieldMeta.modelRef) : import_document.ObjectId : scalarMongoTypeMap.get(fieldMeta.modelRef) ?? fieldMeta.modelRef;
83
- let prop = {};
84
- if (fieldMeta.optArrDepth) {
85
- prop.type = type;
86
- prop.required = true;
87
- if (fieldMeta.isClass && !fieldMeta.refPath) prop.ref = (0, import_constant.getClassMeta)(fieldMeta.modelRef).refName;
88
- if (fieldMeta.refPath) prop.refPath = fieldMeta.refPath;
89
- if (typeof fieldMeta.min === "number") prop.min = fieldMeta.min;
90
- if (typeof fieldMeta.max === "number") prop.max = fieldMeta.max;
91
- if (fieldMeta.enum) prop.enum = [
92
- ...fieldMeta.enum.values,
93
- ...fieldMeta.nullable ? [
94
- null
95
- ] : []
96
- ];
97
- if (typeof fieldMeta.minlength === "number") prop.minlength = fieldMeta.minlength;
98
- if (typeof fieldMeta.maxlength === "number") prop.maxlength = fieldMeta.maxlength;
99
- if (fieldMeta.validate) {
100
- prop.validate = function(value) {
101
- return fieldMeta.validate?.(fieldMeta.name === "Date" && !!value ? (0, import_base.dayjs)() : value, this) ?? true;
102
- };
103
- }
104
- prop = {
105
- type: (0, import_base.arraiedModel)(prop, fieldMeta.optArrDepth),
106
- default: [],
107
- required: true
108
- };
109
- if (fieldMeta.modelRef.prototype === Date.prototype) {
110
- prop.get = (dates) => dates.map((date) => (0, import_base.dayjs)(date));
111
- prop.set = (days) => days.map((day) => day.toDate());
112
- }
113
- if (fieldMeta.isClass && !fieldMeta.isScalar || fieldMeta.modelRef.prototype === import_base.ID.prototype) {
114
- prop.get = (ids) => ids.map((id) => id.toString());
115
- prop.set = (ids) => ids.map((id) => new import_mongoose.Types.ObjectId(id));
116
- }
117
- } else {
118
- prop.type = (0, import_base.arraiedModel)(type, fieldMeta.arrDepth);
119
- prop.required = !fieldMeta.nullable;
120
- if (fieldMeta.isMap) {
121
- prop.of = scalarMongoTypeMap.get(fieldMeta.of) ?? createSchema(fieldMeta.of);
122
- if (!fieldMeta.default) prop.default = /* @__PURE__ */ new Map();
123
- }
124
- if (fieldMeta.default !== null) {
125
- if (typeof fieldMeta.default === "function") prop.default = function() {
126
- const def = fieldMeta.default(this);
127
- return (0, import_common.isDayjs)(def) ? def.toDate() : def;
128
- };
129
- else prop.default = (0, import_common.isDayjs)(fieldMeta.default) ? fieldMeta.default.toDate() : fieldMeta.default instanceof import_base.Enum ? [
130
- ...fieldMeta.default.values
131
- ] : fieldMeta.default;
132
- }
133
- if (typeof fieldMeta.immutable !== "undefined") prop.immutable = fieldMeta.immutable;
134
- if (fieldMeta.isClass && !fieldMeta.refPath) prop.ref = (0, import_constant.getClassMeta)(fieldMeta.modelRef).refName;
135
- if (fieldMeta.refPath) prop.refPath = fieldMeta.refPath;
136
- if (typeof fieldMeta.min === "number") prop.min = fieldMeta.min;
137
- if (typeof fieldMeta.max === "number") prop.max = fieldMeta.max;
138
- if (fieldMeta.enum) prop.enum = [
139
- ...fieldMeta.enum.values,
140
- ...fieldMeta.nullable ? [
141
- null
142
- ] : []
143
- ];
144
- if (typeof fieldMeta.select === "boolean") prop.select = fieldMeta.select;
145
- if (typeof fieldMeta.minlength === "number") prop.minlength = fieldMeta.minlength;
146
- if (typeof fieldMeta.maxlength === "number") prop.maxlength = fieldMeta.maxlength;
147
- if (fieldMeta.nullable) {
148
- prop.get = (v) => v === void 0 ? void 0 : v;
149
- prop.set = (v) => v === null ? void 0 : v;
150
- }
151
- if (fieldMeta.modelRef.prototype === Date.prototype) {
152
- prop.get = (date) => date ? (0, import_base.dayjs)(date) : void 0;
153
- prop.set = (day) => day ? (0, import_base.dayjs)(day).toDate() : void 0;
154
- }
155
- if (fieldMeta.isClass && !fieldMeta.isScalar || fieldMeta.modelRef.prototype === import_base.ID.prototype) {
156
- prop.get = (id) => id ? id.toString() : void 0;
157
- prop.set = (id) => id ? new import_mongoose.Types.ObjectId(id) : void 0;
158
- }
159
- if (fieldMeta.isClass && fieldMeta.isScalar && fieldMeta.default === null && !fieldMeta.nullable) {
160
- prop.default = (0, import_signal.makeDefault)(fieldMeta.modelRef);
161
- }
162
- if (fieldMeta.validate) {
163
- prop.validate = function(value) {
164
- return fieldMeta.validate?.(fieldMeta.name === "Date" && !!value ? (0, import_base.dayjs)() : value, this) ?? true;
165
- };
166
- }
167
- }
168
- schemaProps[fieldMeta.key] = prop;
169
- }, "applyMongoProp");
170
- const createSchema = /* @__PURE__ */ __name((modelRef) => {
171
- const classMeta = (0, import_constant.getClassMeta)(modelRef);
172
- const schemaMeta = Reflect.getMetadata(classMeta.refName, ScalarSchemaStorage.prototype);
173
- if (schemaMeta) return schemaMeta;
174
- const fieldMetas = (0, import_constant.getFieldMetas)(modelRef);
175
- const schemaProps = {};
176
- fieldMetas.forEach((fieldMeta) => {
177
- applyMongoProp(schemaProps, fieldMeta);
178
- });
179
- const schema = new import_mongoose.Schema(schemaProps);
180
- Reflect.defineMetadata(classMeta.refName, schema, ScalarSchemaStorage.prototype);
181
- return schema;
182
- }, "createSchema");
183
- const schemaOf = /* @__PURE__ */ __name((modelRef, docRef, middleware) => {
184
- const classMeta = (0, import_constant.getClassMeta)(docRef);
185
- const schemaMeta = Reflect.getMetadata(classMeta.refName, SchemaStorage.prototype);
186
- if (schemaMeta) return schemaMeta;
187
- const fieldMetas = (0, import_constant.getFieldMetas)(docRef);
188
- const schemaProps = {
189
- createdAt: {
190
- type: Date,
191
- get: /* @__PURE__ */ __name((date) => date ? (0, import_base.dayjs)(date) : date, "get"),
192
- set: /* @__PURE__ */ __name((day) => day ? (0, import_base.dayjs)(day).toDate() : day, "set")
193
- },
194
- updatedAt: {
195
- type: Date,
196
- get: /* @__PURE__ */ __name((date) => date ? (0, import_base.dayjs)(date) : date, "get"),
197
- set: /* @__PURE__ */ __name((day) => day ? (0, import_base.dayjs)(day).toDate() : day, "set")
198
- }
199
- };
200
- fieldMetas.forEach((fieldMeta) => {
201
- applyMongoProp(schemaProps, fieldMeta);
202
- });
203
- const schema = new import_mongoose.Schema(schemaProps, (0, import_document.getDefaultSchemaOptions)());
204
- schema.methods.refresh = async function() {
205
- Object.assign(this, await this.constructor.findById(this._id));
206
- return this;
207
- };
208
- Object.getOwnPropertyNames(docRef.prototype).forEach((name) => {
209
- if (name === "constructor") return;
210
- schema.methods[name] = Object.getOwnPropertyDescriptor(docRef.prototype, name)?.value;
211
- });
212
- schema.pre("save", async function(next) {
213
- const model = this.constructor;
214
- if (this.isNew) model.addSummary([
215
- "total",
216
- this.status
217
- ]);
218
- else if (!!this.removedAt && this.isModified("removedAt")) model.subSummary([
219
- "total",
220
- this.status
221
- ]);
222
- next();
223
- });
224
- const onSchema = Object.getOwnPropertyDescriptor(middleware.prototype, "onSchema")?.value;
225
- onSchema?.(schema);
226
- schema.index({
227
- removedAt: -1
228
- });
229
- Reflect.defineMetadata(classMeta.refName, schema, SchemaStorage.prototype);
230
- return schema;
231
- }, "schemaOf");
232
- const addSchema = /* @__PURE__ */ __name((modelRef, docRef, inputRef, middleware) => {
233
- const originDocClassMeta = (0, import_constant.getClassMeta)(docRef);
234
- const originInputClassMeta = (0, import_constant.getClassMeta)(inputRef);
235
- const originDoc = (0, import_constant.getFullModelRef)(originDocClassMeta.refName);
236
- const originInput = (0, import_constant.getInputModelRef)(originInputClassMeta.refName);
237
- const classMeta = (0, import_constant.getClassMeta)(docRef);
238
- const modelSchema = Reflect.getMetadata(classMeta.refName, SchemaStorage.prototype);
239
- if (!modelSchema) throw new Error(`Schema of ${classMeta.refName} not found`);
240
- const fieldMetas = (0, import_constant.getFieldMetas)(docRef);
241
- const schemaProps = {
242
- createdAt: {
243
- type: Date,
244
- get: /* @__PURE__ */ __name((date) => date ? (0, import_base.dayjs)(date) : date, "get"),
245
- set: /* @__PURE__ */ __name((day) => day ? (0, import_base.dayjs)(day).toDate() : day, "set")
246
- },
247
- updatedAt: {
248
- type: Date,
249
- get: /* @__PURE__ */ __name((date) => date ? (0, import_base.dayjs)(date) : date, "get"),
250
- set: /* @__PURE__ */ __name((day) => day ? (0, import_base.dayjs)(day).toDate() : day, "set")
251
- }
252
- };
253
- fieldMetas.forEach((fieldMeta) => {
254
- applyMongoProp(schemaProps, fieldMeta);
255
- (0, import__.applyNestField)(originDoc, fieldMeta);
256
- });
257
- const inputFieldMetas = (0, import_constant.getFieldMetas)(inputRef);
258
- inputFieldMetas.forEach((fieldMeta) => {
259
- (0, import__.applyNestField)(originInput, fieldMeta, "input");
260
- });
261
- const schema = new import_mongoose.Schema(schemaProps, (0, import_document.getDefaultSchemaOptions)());
262
- modelSchema.add(schema);
263
- Object.getOwnPropertyNames(docRef.prototype).forEach((name) => {
264
- if (name === "constructor") return;
265
- modelSchema.methods[name] = Object.getOwnPropertyDescriptor(docRef.prototype, name)?.value;
266
- });
267
- const onSchema = Object.getOwnPropertyDescriptor(middleware.prototype, "onSchema")?.value;
268
- onSchema?.(modelSchema);
269
- return modelSchema;
270
- }, "addSchema");
271
- // Annotate the CommonJS export names for ESM import in node:
272
- 0 && (module.exports = {
273
- addSchema,
274
- schemaOf
275
- });
@@ -1,282 +0,0 @@
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 __name = (target, value) => __defProp(target, "name", { value, configurable: true });
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
- var searchDaemon_exports = {};
30
- __export(searchDaemon_exports, {
31
- SearchDaemonModule: () => SearchDaemonModule,
32
- makeTextFilter: () => makeTextFilter
33
- });
34
- module.exports = __toCommonJS(searchDaemon_exports);
35
- var import_common = require("@akanjs/common");
36
- var import_constant = require("@akanjs/constant");
37
- var import_document = require("@akanjs/document");
38
- var import_common2 = require("@nestjs/common");
39
- var import_mongoose = require("@nestjs/mongoose");
40
- var import_meilisearch = __toESM(require("meilisearch"));
41
- function _ts_decorate(decorators, target, key, desc) {
42
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
43
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
44
- 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;
45
- return c > 3 && r && Object.defineProperty(target, key, r), r;
46
- }
47
- __name(_ts_decorate, "_ts_decorate");
48
- function _ts_metadata(k, v) {
49
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
50
- }
51
- __name(_ts_metadata, "_ts_metadata");
52
- function _ts_param(paramIndex, decorator) {
53
- return function(target, key) {
54
- decorator(target, key, paramIndex);
55
- };
56
- }
57
- __name(_ts_param, "_ts_param");
58
- const hasTextField = /* @__PURE__ */ __name((modelRef) => {
59
- const fieldMetas = (0, import_constant.getFieldMetas)(modelRef);
60
- return fieldMetas.some((fieldMeta) => !!fieldMeta.text || fieldMeta.isScalar && fieldMeta.isClass && fieldMeta.select && hasTextField(fieldMeta.modelRef));
61
- }, "hasTextField");
62
- const getTextFieldKeys = /* @__PURE__ */ __name((modelRef) => {
63
- const allSearchFields = [];
64
- const allFilterFields = [];
65
- const fieldMetaMap = (0, import_constant.getFieldMetaMap)(modelRef);
66
- const fieldMetas = [
67
- ...fieldMetaMap.values()
68
- ];
69
- const stringTextFields = fieldMetas.filter((fieldMeta) => !!fieldMeta.text).map((fieldMeta) => {
70
- if (fieldMeta.text === "filter") allFilterFields.push(fieldMeta.key);
71
- else if (fieldMeta.text === "search") allSearchFields.push(fieldMeta.key);
72
- return fieldMeta.key;
73
- });
74
- const scalarTextFields = fieldMetas.filter((fieldMeta) => fieldMeta.isScalar && fieldMeta.isClass && fieldMeta.select && hasTextField(fieldMeta.modelRef)).map((fieldMeta) => fieldMeta.key);
75
- const deepFields = scalarTextFields.map((key) => {
76
- const fieldMeta = fieldMetaMap.get(key);
77
- if (!fieldMeta) throw new Error(`No fieldMeta for ${key}`);
78
- const { stringTextFields: stringTextFields2, allTextFields, allSearchFields: allSearchFields2, allFilterFields: allFilterFields2 } = getTextFieldKeys(fieldMeta.modelRef);
79
- allFilterFields2.push(...allSearchFields2.map((field) => `${key}.${field}`));
80
- allSearchFields2.push(...stringTextFields2.map((field) => `${key}.${field}`));
81
- return [
82
- ...stringTextFields2.map((field) => `${key}.${field}`),
83
- ...allTextFields.map((field) => `${key}.${field}`)
84
- ];
85
- }).flat();
86
- return {
87
- stringTextFields,
88
- scalarTextFields,
89
- allTextFields: [
90
- ...stringTextFields,
91
- ...deepFields
92
- ],
93
- allSearchFields,
94
- allFilterFields
95
- };
96
- }, "getTextFieldKeys");
97
- const makeTextFilter = /* @__PURE__ */ __name((modelRef) => {
98
- const fieldMetaMap = (0, import_constant.getFieldMetaMap)(modelRef);
99
- const { stringTextFields, scalarTextFields } = getTextFieldKeys(modelRef);
100
- const filterData = /* @__PURE__ */ __name((data, assignObj = {}) => {
101
- if (Array.isArray(data)) return data.map((d) => filterData(d));
102
- return Object.assign(Object.fromEntries([
103
- ...stringTextFields.map((key) => [
104
- key,
105
- data[key]
106
- ]),
107
- ...scalarTextFields.map((key) => {
108
- const fieldMeta = fieldMetaMap.get(key);
109
- if (!fieldMeta) throw new Error(`No fieldMeta for ${key}`);
110
- const filterFunc = makeTextFilter(fieldMeta.modelRef);
111
- return [
112
- key,
113
- filterFunc(data[key])
114
- ];
115
- })
116
- ]), assignObj);
117
- }, "filterData");
118
- return filterData;
119
- }, "makeTextFilter");
120
- const getSortableAttributes = /* @__PURE__ */ __name((refName) => {
121
- const cnst = (0, import_constant.getCnstMeta)(refName);
122
- const sortMap = (0, import_constant.getFilterSortMap)(cnst.Filter);
123
- const sortFields = Object.values(sortMap).filter((val) => typeof val === "object").map((sort) => Object.keys(sort)).flat();
124
- return [
125
- ...new Set(sortFields)
126
- ];
127
- }, "getSortableAttributes");
128
- let SearchDaemon = class SearchDaemon2 {
129
- static {
130
- __name(this, "SearchDaemon");
131
- }
132
- connection;
133
- meili;
134
- logger;
135
- constructor(connection, meili) {
136
- this.connection = connection;
137
- this.meili = meili;
138
- this.logger = new import_common.Logger("SearchDaemon");
139
- }
140
- async onModuleInit() {
141
- const databaseModelNames = (0, import_document.getAllDatabaseModelNames)();
142
- const indexes = (await this.meili.getIndexes({
143
- limit: 1e3
144
- })).results;
145
- const indexMap = new Map(indexes.map((index) => [
146
- index.uid,
147
- index
148
- ]));
149
- const indexCreationNames = [];
150
- const indexUpdateNames = [];
151
- for (const modelName of databaseModelNames) {
152
- const indexName = (0, import_common.lowerlize)(modelName);
153
- const modelRef = (0, import_constant.getFullModelRef)(modelName);
154
- if (!hasTextField(modelRef)) continue;
155
- const index = indexMap.get(indexName);
156
- if (!index) indexCreationNames.push(indexName);
157
- else if (index.primaryKey !== "id") indexUpdateNames.push(indexName);
158
- }
159
- for (const indexName of indexCreationNames) await this.meili.createIndex(indexName, {
160
- primaryKey: "id"
161
- });
162
- for (const indexName of indexUpdateNames) await this.meili.updateIndex(indexName, {
163
- primaryKey: "id"
164
- });
165
- for (const modelName of databaseModelNames) {
166
- const indexName = (0, import_common.lowerlize)(modelName);
167
- const model = this.connection.models[modelName];
168
- const modelRef = (0, import_constant.getFullModelRef)(modelName);
169
- if (!hasTextField(modelRef)) continue;
170
- const searchIndex = this.meili.index(indexName);
171
- const { stringTextFields, scalarTextFields, allSearchFields, allFilterFields } = getTextFieldKeys(modelRef);
172
- const settings = await searchIndex.getSettings();
173
- const allSearchFieldSet = new Set(allSearchFields);
174
- const allFilterFieldSet = new Set(allFilterFields);
175
- const searchFieldSet = new Set(settings.searchableAttributes);
176
- const filterFieldSet = new Set(settings.filterableAttributes);
177
- const needUpdateSetting = !allSearchFields.every((field) => searchFieldSet.has(field)) || !allFilterFields.every((field) => filterFieldSet.has(field)) || !settings.searchableAttributes?.every((field) => allSearchFieldSet.has(field)) || !settings.filterableAttributes?.every((field) => allFilterFieldSet.has(field));
178
- if (needUpdateSetting) {
179
- this.logger.info(`update index settings (${modelName})`);
180
- await searchIndex.updateSettings({
181
- searchableAttributes: allSearchFields,
182
- filterableAttributes: allFilterFields,
183
- sortableAttributes: getSortableAttributes(indexName)
184
- });
185
- }
186
- const stringTextFieldSet = new Set(stringTextFields);
187
- const scalarTextFieldSet = new Set(scalarTextFields);
188
- const filterText = makeTextFilter(modelRef);
189
- model.watch().on("change", async (data) => {
190
- try {
191
- const id = data.documentKey._id.toString();
192
- if (data.operationType === "delete") {
193
- this.logger.trace(`delete text doc (${modelName}): ${id}`);
194
- return await searchIndex.deleteDocument(id);
195
- } else if (data.operationType === "insert") {
196
- this.logger.trace(`insert text doc (${modelName}): ${data.documentKey._id}`);
197
- if (!data.fullDocument) throw new Error("No fullDocument");
198
- const textFilteredData = filterText(data.fullDocument);
199
- return await searchIndex.addDocuments([
200
- textFilteredData
201
- ]);
202
- } else if (data.operationType === "update") {
203
- const updatedFields = data.updateDescription?.updatedFields ?? {};
204
- const isRemoved = !!updatedFields.removedAt;
205
- if (isRemoved) {
206
- this.logger.trace(`remove text doc (${modelName}): ${id}`);
207
- return await searchIndex.deleteDocument(id);
208
- }
209
- this.logger.trace(`update text doc (${modelName}): ${data.documentKey._id}`);
210
- const updatedFieldKeys = Object.keys(updatedFields);
211
- const removedFieldKeys = data.updateDescription?.removedFields ?? [];
212
- const isScalarTextFieldUpdated = [
213
- ...updatedFieldKeys,
214
- ...removedFieldKeys
215
- ].map((key) => key.split(".")[0]).some((key) => scalarTextFieldSet.has(key));
216
- if (isScalarTextFieldUpdated) {
217
- const doc = await model.findById(data.documentKey._id);
218
- if (!doc) this.logger.error(`No doc for ${data.documentKey._id}`);
219
- const textFilteredData = filterText(doc, {
220
- id
221
- });
222
- return await searchIndex.updateDocuments([
223
- textFilteredData
224
- ]);
225
- } else {
226
- const updateKeys = updatedFieldKeys.filter((key) => stringTextFieldSet.has(key));
227
- const removeKeys = removedFieldKeys.filter((key) => stringTextFieldSet.has(key));
228
- if (!updateKeys.length && !removeKeys.length) return;
229
- const textFilteredData = Object.fromEntries([
230
- [
231
- "id",
232
- id
233
- ],
234
- ...updateKeys.map((key) => [
235
- key,
236
- updatedFields[key]
237
- ]),
238
- ...removeKeys.map((key) => [
239
- key,
240
- null
241
- ])
242
- ]);
243
- return await searchIndex.updateDocuments([
244
- textFilteredData
245
- ]);
246
- }
247
- }
248
- } catch (e) {
249
- this.logger.error(e);
250
- }
251
- });
252
- }
253
- }
254
- };
255
- SearchDaemon = _ts_decorate([
256
- (0, import_common2.Injectable)(),
257
- _ts_param(0, (0, import_mongoose.InjectConnection)()),
258
- _ts_param(1, (0, import_common2.Inject)("MEILI_CLIENT")),
259
- _ts_metadata("design:type", Function),
260
- _ts_metadata("design:paramtypes", [
261
- typeof Connection === "undefined" ? Object : Connection,
262
- typeof import_meilisearch.default === "undefined" ? Object : import_meilisearch.default
263
- ])
264
- ], SearchDaemon);
265
- class SearchDaemonModule {
266
- static {
267
- __name(this, "SearchDaemonModule");
268
- }
269
- }
270
- SearchDaemonModule = _ts_decorate([
271
- (0, import_common2.Global)(),
272
- (0, import_common2.Module)({
273
- providers: [
274
- SearchDaemon
275
- ]
276
- })
277
- ], SearchDaemonModule);
278
- // Annotate the CommonJS export names for ESM import in node:
279
- 0 && (module.exports = {
280
- SearchDaemonModule,
281
- makeTextFilter
282
- });
package/src/types.js DELETED
@@ -1,15 +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 __copyProps = (to, from, except, desc) => {
6
- if (from && typeof from === "object" || typeof from === "function") {
7
- for (let key of __getOwnPropNames(from))
8
- if (!__hasOwnProp.call(to, key) && key !== except)
9
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
10
- }
11
- return to;
12
- };
13
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
14
- var types_exports = {};
15
- module.exports = __toCommonJS(types_exports);