@smartsoft001/crud-shell-nestjs 2.148.0 → 2.149.0

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/index.js DELETED
@@ -1,1818 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
- var __decorateClass = (decorators, target, key, kind) => {
4
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
5
- for (var i = decorators.length - 1, decorator; i >= 0; i--)
6
- if (decorator = decorators[i])
7
- result = (kind ? decorator(target, key, result) : decorator(result)) || result;
8
- if (kind && result) __defProp(target, key, result);
9
- return result;
10
- };
11
- var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
12
-
13
- // packages/crud/shell/nestjs/src/lib/nestjs.module.ts
14
- import { Module } from "@nestjs/common";
15
- import { JwtModule } from "@nestjs/jwt";
16
- import { PassportModule } from "@nestjs/passport";
17
-
18
- // packages/crud/shell/app-services/src/lib/services/crud/crud.service.ts
19
- import { Injectable, Logger } from "@nestjs/common";
20
- import * as CombinedStream from "combined-stream";
21
- import { Guid as Guid2 } from "guid-typescript";
22
- import { Memoize } from "lodash-decorators";
23
-
24
- // packages/shared/models/src/lib/symbols.ts
25
- var SYMBOL_MODEL = /* @__PURE__ */ Symbol.for("smartsoft:model");
26
- var SYMBOL_FIELD = /* @__PURE__ */ Symbol.for("smartsoft:field");
27
-
28
- // packages/shared/models/src/lib/decorators/model/model.decorator.ts
29
- import "reflect-metadata";
30
-
31
- // packages/shared/models/src/lib/decorators/field/field.decorator.ts
32
- import "reflect-metadata";
33
-
34
- // packages/shared/utils/src/lib/services/array/array.service.ts
35
- import * as _ from "lodash";
36
-
37
- // packages/shared/utils/src/lib/services/guid/guid.service.ts
38
- import { Guid } from "guid-typescript";
39
- var GuidService = class {
40
- /***
41
- * Create guid as string
42
- */
43
- static create() {
44
- return Guid.raw();
45
- }
46
- };
47
-
48
- // packages/shared/utils/src/lib/services/object/object.service.ts
49
- import { stringify } from "flatted";
50
- var ObjectService = class {
51
- /***
52
- * Create object with data
53
- * @param data {object} - data to set
54
- * @param type {type} - new type
55
- * @return - new type object
56
- */
57
- static createByType(data, type) {
58
- if (!data) return data;
59
- try {
60
- if (data instanceof type) return data;
61
- } catch (e) {
62
- console.warn(e);
63
- }
64
- const result = new type();
65
- Object.keys(data).forEach((key) => {
66
- result[key] = data[key];
67
- });
68
- return result;
69
- }
70
- /***
71
- * Remove object type from data
72
- * @param obj {object} - object
73
- * @return - object without type
74
- */
75
- static removeTypes(obj) {
76
- if (!obj) return obj;
77
- const result = {};
78
- Object.keys(obj).forEach((key) => {
79
- if (obj[key] && obj[key].constructor && !(obj[key] instanceof Date)) {
80
- let stringValue = "";
81
- try {
82
- stringValue = JSON.stringify(obj[key]);
83
- } catch (e) {
84
- console.warn("can't stringify without circular package");
85
- stringValue = stringify(obj[key]);
86
- }
87
- result[key] = JSON.parse(stringValue);
88
- } else {
89
- result[key] = obj[key];
90
- }
91
- });
92
- return result;
93
- }
94
- };
95
-
96
- // packages/shared/utils/src/lib/services/password/password.service.ts
97
- import md5 from "md5";
98
- var PasswordService = class _PasswordService {
99
- /**
100
- * Hash password text
101
- * @param p {string} - text
102
- * @return - hashed text
103
- */
104
- static hash(p) {
105
- return Promise.resolve(md5(p));
106
- }
107
- /**
108
- * Compare password text with hashed text
109
- * @param p {string} - password text
110
- * @param h {string} - hashed text
111
- */
112
- static async compare(p, h) {
113
- const hp = await _PasswordService.hash(p);
114
- return hp === h;
115
- }
116
- };
117
-
118
- // packages/shared/models/src/lib/utils.ts
119
- function getModelFieldKeys(type) {
120
- if (!type["__fields"]) return [];
121
- return Object.keys(type["__fields"]);
122
- }
123
- function getModelFieldOptions(instance, fieldKey) {
124
- return Reflect.getMetadata(SYMBOL_FIELD, instance, fieldKey);
125
- }
126
- function getModelFieldsWithOptions(instance) {
127
- const keys = getModelFieldKeys(instance.constructor);
128
- return keys.map((item) => {
129
- return {
130
- key: item,
131
- options: getModelFieldOptions(instance, item)
132
- };
133
- });
134
- }
135
- function isModel(instance) {
136
- if (!instance || !instance.constructor) return false;
137
- return Reflect.hasMetadata(SYMBOL_MODEL, instance.constructor);
138
- }
139
- function getInvalidFields(instance, mode, permissions) {
140
- const result = [];
141
- getModelFieldsWithOptions(instance).forEach(({ key, options }) => {
142
- let required = options.required;
143
- if ((mode === "create" || mode === "update") && options[mode] && options[mode]?.constructor) {
144
- required = options[mode].required;
145
- if (required && permissions && options[mode].permissions) {
146
- required = options[mode]?.permissions?.some(
147
- (op) => permissions.some((p) => p === op)
148
- );
149
- }
150
- }
151
- if (required && (instance[key] === null || instance[key] === void 0 || instance[key] === ""))
152
- result.push(key);
153
- });
154
- return result;
155
- }
156
- function castModel(instance, mode, permissions) {
157
- if (!isModel(instance)) return;
158
- const fieldsWithOptions = getModelFieldsWithOptions(instance);
159
- Object.keys(instance).filter((key) => key !== "id").forEach((key) => {
160
- const fieldWidthOptions = fieldsWithOptions.find((f) => f.key === key);
161
- if (!fieldWidthOptions) {
162
- delete instance[key];
163
- return;
164
- }
165
- if ((mode === "create" || mode === "update") && (!fieldWidthOptions.options[mode] || permissions && fieldWidthOptions.options[mode].permissions && !fieldWidthOptions.options[mode]?.permissions?.some((op) => permissions.some((p) => op === p)))) {
166
- delete instance[key];
167
- return;
168
- } else if (mode !== "create" && mode !== "update" && (!fieldWidthOptions.options.customs || !fieldWidthOptions.options.customs.some((c) => c.mode === mode))) {
169
- delete instance[key];
170
- return;
171
- }
172
- });
173
- }
174
-
175
- // packages/shared/domain-core/src/lib/errors.ts
176
- var DomainValidationError = class _DomainValidationError extends Error {
177
- type = _DomainValidationError;
178
- constructor(msg) {
179
- super(msg);
180
- }
181
- };
182
- var DomainForbiddenError = class _DomainForbiddenError extends Error {
183
- type = _DomainForbiddenError;
184
- constructor(msg) {
185
- super(msg);
186
- }
187
- };
188
-
189
- // packages/shared/domain-core/src/lib/repositories.ts
190
- var IUnitOfWork = class {
191
- };
192
- var IItemRepository = class {
193
- };
194
- var IAttachmentRepository = class {
195
- };
196
-
197
- // packages/crud/shell/app-services/src/lib/services/crud/crud.service.ts
198
- var CrudService = class {
199
- constructor(permissionService, repository, attachmentRepository) {
200
- this.permissionService = permissionService;
201
- this.repository = repository;
202
- this.attachmentRepository = attachmentRepository;
203
- }
204
- permissionService;
205
- repository;
206
- attachmentRepository;
207
- _logger = new Logger(CrudService.name, { timestamp: true });
208
- async create(data, user) {
209
- data.id = Guid2.raw();
210
- try {
211
- this.permissionService.valid("create", user);
212
- castModel(data, "create", user.permissions);
213
- this.checkValidCreate(data, user.permissions);
214
- if (data["password"]) {
215
- data["password"] = await PasswordService.hash(data["password"]);
216
- }
217
- if (data["passwordConfirm"]) {
218
- delete data["passwordConfirm"];
219
- }
220
- await this.repository.create(data, user);
221
- return data.id;
222
- } catch (e) {
223
- this._logger.error(e);
224
- throw e;
225
- }
226
- }
227
- async createMany(data, user, options) {
228
- data.forEach((item) => {
229
- item.id = Guid2.raw();
230
- });
231
- try {
232
- this.permissionService.valid("create", user);
233
- data.forEach((item) => {
234
- castModel(item, "create", user.permissions);
235
- this.checkValidCreate(item, user.permissions);
236
- });
237
- if (options && options.mode === "replace") {
238
- await this.repository.clear(user);
239
- }
240
- for (let index = 0; index < data.length; index++) {
241
- const item = data[index];
242
- if (item["password"]) {
243
- item["password"] = await PasswordService.hash(item["password"]);
244
- }
245
- if (item["passwordConfirm"]) {
246
- delete item["passwordConfirm"];
247
- }
248
- }
249
- await this.repository.createMany(data, user);
250
- } catch (e) {
251
- this._logger.error(e);
252
- throw e;
253
- }
254
- return data;
255
- }
256
- async readById(id, user) {
257
- try {
258
- this.permissionService.valid("read", user);
259
- const result = await this.repository.getById(id);
260
- delete result["password"];
261
- return result;
262
- } catch (e) {
263
- this._logger.error(e);
264
- throw e;
265
- }
266
- }
267
- async read(criteria, options, user) {
268
- try {
269
- this.permissionService.valid("read", user);
270
- const result = await this.repository.getByCriteria(criteria, options);
271
- result.data.forEach((item) => delete item["password"]);
272
- return result;
273
- } catch (e) {
274
- this._logger.error(e);
275
- throw e;
276
- }
277
- }
278
- readBySpec(spec, options, user) {
279
- return this.read(spec.criteria, options, user);
280
- }
281
- async update(id, data, user) {
282
- try {
283
- data.id = id;
284
- this.permissionService.valid("update", user);
285
- castModel(data, "update", user.permissions);
286
- this.checkValidUpdate(data, user.permissions);
287
- if (data["password"]) {
288
- data["password"] = await PasswordService.hash(data["password"]);
289
- }
290
- if (data["passwordConfirm"]) {
291
- delete data["passwordConfirm"];
292
- }
293
- await this.repository.update(data, user);
294
- } catch (e) {
295
- this._logger.error(e);
296
- throw e;
297
- }
298
- }
299
- async updatePartial(id, data, user) {
300
- try {
301
- data.id = id;
302
- this.permissionService.valid("update", user);
303
- castModel(data, "update", user.permissions);
304
- this.checkValidUpdatePartial(data, user.permissions);
305
- if (data["password"]) {
306
- data["password"] = await PasswordService.hash(data["password"]);
307
- }
308
- if (data["passwordConfirm"]) {
309
- delete data["passwordConfirm"];
310
- }
311
- await this.repository.updatePartial(data, user);
312
- } catch (e) {
313
- this._logger.error(e);
314
- throw e;
315
- }
316
- }
317
- async delete(id, user) {
318
- try {
319
- this.permissionService.valid("delete", user);
320
- await this.repository.delete(id, user);
321
- } catch (e) {
322
- this._logger.error(e);
323
- throw e;
324
- }
325
- }
326
- async uploadAttachment(data, options) {
327
- if (!data.id) {
328
- data.id = GuidService.create();
329
- }
330
- let oldId = null;
331
- if (options?.start) {
332
- oldId = data.id;
333
- const stream = await this.attachmentRepository.getStream(data.id, {
334
- start: 0,
335
- end: options.start - 1
336
- });
337
- const combinedStream = CombinedStream.create();
338
- combinedStream.append(stream);
339
- combinedStream.append(data.stream);
340
- data.stream = combinedStream;
341
- data.id = GuidService.create();
342
- }
343
- this.attachmentRepository.upload(data, options);
344
- if (oldId) await this.attachmentRepository.delete(data.id);
345
- return data.id;
346
- }
347
- getAttachmentInfo(id) {
348
- return this.attachmentRepository.getInfo(id);
349
- }
350
- getAttachmentStream(id, options) {
351
- return this.attachmentRepository.getStream(id, options);
352
- }
353
- async deleteAttachment(id) {
354
- return this.attachmentRepository.delete(id);
355
- }
356
- changes(criteria) {
357
- return this.repository.changesByCriteria(criteria);
358
- }
359
- checkValidCreate(item, permissions) {
360
- const array = getInvalidFields(item, "create", permissions);
361
- if (array.length) {
362
- throw new DomainValidationError("Required fields: " + array.join(", "));
363
- }
364
- }
365
- checkValidUpdate(item, permissions) {
366
- const array = getInvalidFields(item, "update", permissions);
367
- if (array.length) {
368
- throw new DomainValidationError("Required fields: " + array.join(", "));
369
- }
370
- }
371
- checkValidUpdatePartial(item, permissions) {
372
- if (!isModel(item)) return;
373
- const keys = Object.keys(item);
374
- const array = getInvalidFields(item, "update", permissions)?.filter(
375
- (invalidField) => keys.some((key) => key === invalidField)
376
- );
377
- if (array.length) {
378
- throw new DomainValidationError("Required fields: " + array.join(", "));
379
- }
380
- }
381
- };
382
- __decorateClass([
383
- Memoize()
384
- ], CrudService.prototype, "getAttachmentInfo", 1);
385
- CrudService = __decorateClass([
386
- Injectable()
387
- ], CrudService);
388
-
389
- // packages/crud/shell/app-services/src/lib/services/index.ts
390
- var SERVICES = [CrudService];
391
-
392
- // packages/shared/mongo/src/lib/mongo.config.ts
393
- var MongoConfig = class {
394
- host;
395
- port;
396
- database;
397
- username;
398
- password;
399
- collection;
400
- url;
401
- type;
402
- };
403
-
404
- // packages/shared/mongo/src/lib/mongo.unitofwork.ts
405
- import { Injectable as Injectable2 } from "@nestjs/common";
406
- import { MongoClient } from "mongodb";
407
-
408
- // packages/shared/mongo/src/lib/mongo.utils.ts
409
- function getMongoUrl(config) {
410
- let url;
411
- if (config.username && config.password)
412
- url = `mongodb://${config.username}:${config.password}@${config.host}:${config.port}`;
413
- else url = `mongodb://${config.host}:${config.port}`;
414
- url = url + "?authSource=" + config.database;
415
- if (config.host.indexOf("ondigitalocean.com") > -1) {
416
- url = url.replace("mongodb://", "mongodb+srv://");
417
- url = url + "&tls=true";
418
- }
419
- return url;
420
- }
421
-
422
- // packages/shared/mongo/src/lib/mongo.unitofwork.ts
423
- var MongoUnitOfWork = class extends IUnitOfWork {
424
- constructor(config) {
425
- super();
426
- this.config = config;
427
- }
428
- config;
429
- async scope(definition) {
430
- const client = await MongoClient.connect(this.getUrl());
431
- const session = client.startSession();
432
- const transactionOptions = {
433
- readPreference: "primary",
434
- readConcern: { level: "local" },
435
- writeConcern: { w: "majority" }
436
- };
437
- let error = null;
438
- try {
439
- await session.withTransaction(async () => {
440
- await definition({
441
- session,
442
- connection: client
443
- });
444
- }, transactionOptions);
445
- } catch (e) {
446
- error = e;
447
- } finally {
448
- await session.endSession();
449
- await client.close();
450
- }
451
- if (error) throw error;
452
- }
453
- getUrl() {
454
- return getMongoUrl(this.config);
455
- }
456
- };
457
- MongoUnitOfWork = __decorateClass([
458
- Injectable2()
459
- ], MongoUnitOfWork);
460
-
461
- // packages/shared/mongo/src/lib/repositories/attachment.repository.ts
462
- import { Injectable as Injectable3 } from "@nestjs/common";
463
- import { MongoClient as MongoClient2 } from "mongodb";
464
- import * as mongo from "mongodb";
465
- var MongoAttachmentRepository = class extends IAttachmentRepository {
466
- constructor(config) {
467
- super();
468
- this.config = config;
469
- }
470
- config;
471
- async upload(data, options) {
472
- const client = await MongoClient2.connect(this.getUrl());
473
- return await new Promise((res, rej) => {
474
- const db = client.db(this.config.database);
475
- const bucket = new mongo.GridFSBucket(db, {
476
- bucketName: this.config.collection
477
- });
478
- const writeStream = bucket.openUploadStreamWithId(
479
- data.id,
480
- data.fileName,
481
- {
482
- metadata: { contentType: data.mimeType }
483
- }
484
- );
485
- if (options?.streamCallback) options.streamCallback(writeStream);
486
- data.stream.pipe(writeStream);
487
- writeStream.on("error", (error) => {
488
- rej(error);
489
- });
490
- writeStream.on("finish", () => {
491
- res();
492
- });
493
- });
494
- }
495
- async getInfo(id) {
496
- const client = await MongoClient2.connect(this.getUrl());
497
- const db = client.db(this.config.database);
498
- const bucket = new mongo.GridFSBucket(db, {
499
- bucketName: this.config.collection
500
- });
501
- const items = await bucket.find({
502
- _id: id
503
- }).toArray();
504
- if (!items || items.length === 0) return null;
505
- return {
506
- fileName: items[0].filename,
507
- // mongodb 7 removed the deprecated top-level contentType - files written
508
- // by older driver versions still carry it, so fall back to it
509
- contentType: items[0].metadata?.["contentType"] ?? items[0].contentType,
510
- length: items[0].length
511
- };
512
- }
513
- async getStream(id, options) {
514
- const client = await MongoClient2.connect(this.getUrl());
515
- const db = client.db(this.config.database);
516
- const bucket = new mongo.GridFSBucket(db, {
517
- bucketName: this.config.collection
518
- });
519
- return bucket.openDownloadStream(id, options);
520
- }
521
- async delete(id) {
522
- const client = await MongoClient2.connect(this.getUrl());
523
- const db = client.db(this.config.database);
524
- const bucket = new mongo.GridFSBucket(db, {
525
- bucketName: this.config.collection
526
- });
527
- await bucket.delete(id);
528
- await client.close();
529
- }
530
- getUrl() {
531
- return getMongoUrl(this.config);
532
- }
533
- };
534
- MongoAttachmentRepository = __decorateClass([
535
- Injectable3()
536
- ], MongoAttachmentRepository);
537
-
538
- // packages/shared/mongo/src/lib/repositories/item.repository.ts
539
- import { Injectable as Injectable4 } from "@nestjs/common";
540
- import {
541
- MongoClient as MongoClient3
542
- } from "mongodb";
543
- import { Observable } from "rxjs";
544
- import { finalize, share } from "rxjs/operators";
545
- var MongoItemRepository = class extends IItemRepository {
546
- constructor(config) {
547
- super();
548
- this.config = config;
549
- }
550
- config;
551
- async create(item, user, repoOptions) {
552
- await this.collectionContext(async (collection) => {
553
- try {
554
- await collection.insertOne(this.getModelToCreate(item, user), {
555
- session: repoOptions?.transaction?.session
556
- });
557
- this.logChange("create", item, repoOptions, user, null).then();
558
- } catch (errInsert) {
559
- this.logChange("create", item, repoOptions, user, errInsert).then();
560
- throw errInsert;
561
- }
562
- });
563
- }
564
- async clear(user, repoOptions) {
565
- await this.collectionContext(async (collection) => {
566
- try {
567
- await collection.deleteMany(
568
- {},
569
- { session: repoOptions?.transaction?.session }
570
- );
571
- this.logChange("clear", null, repoOptions, user, null).then();
572
- } catch (errClear) {
573
- this.logChange("clear", null, repoOptions, user, errClear).then();
574
- throw errClear;
575
- }
576
- });
577
- }
578
- async createMany(list, user, repoOptions) {
579
- await this.collectionContext(async (collection) => {
580
- try {
581
- await collection.insertMany(
582
- list.map((item) => this.getModelToCreate(item, user)),
583
- { session: repoOptions?.transaction?.session }
584
- );
585
- this.logChange("createMany", null, repoOptions, user, null).then();
586
- } catch (errInsert) {
587
- this.logChange("createMany", null, repoOptions, user, errInsert).then();
588
- throw errInsert;
589
- }
590
- });
591
- }
592
- async update(item, user, repoOptions) {
593
- await this.collectionContext(async (collection) => {
594
- try {
595
- const info = await this.getInfo(item.id, collection);
596
- await collection.replaceOne(
597
- { _id: item.id },
598
- this.getModelToUpdate(item, user, info),
599
- { session: repoOptions?.transaction?.session }
600
- );
601
- this.logChange("update", item, repoOptions, user, null).then();
602
- } catch (errInsert) {
603
- this.logChange("update", item, repoOptions, user, errInsert).then();
604
- throw errInsert;
605
- }
606
- });
607
- }
608
- async updatePartial(item, user, repoOptions) {
609
- await this.collectionContext(async (collection) => {
610
- try {
611
- const info = await this.getInfo(item.id, collection);
612
- await collection.updateOne(
613
- { _id: item.id },
614
- {
615
- $set: this.getModelToUpdate(item, user, info)
616
- },
617
- { session: repoOptions?.transaction?.session }
618
- );
619
- this.logChange("updatePartial", item, repoOptions, user, null).then();
620
- } catch (errUpdate) {
621
- this.logChange(
622
- "updatePartial",
623
- item,
624
- repoOptions,
625
- user,
626
- errUpdate
627
- ).then();
628
- throw errUpdate;
629
- }
630
- });
631
- }
632
- async updatePartialManyByCriteria(criteria, set, user, repoOptions) {
633
- await this.collectionContext(async (collection) => {
634
- try {
635
- this.convertIdInCriteria(criteria);
636
- await collection.updateMany(
637
- criteria,
638
- {
639
- $set: {
640
- ...set,
641
- "__info.update": {
642
- username: user?.username,
643
- date: /* @__PURE__ */ new Date()
644
- }
645
- }
646
- },
647
- { session: repoOptions?.transaction?.session }
648
- );
649
- this.logChange(
650
- "updatePartialManyByCriteria",
651
- {
652
- ...criteria,
653
- set
654
- },
655
- repoOptions,
656
- user,
657
- null
658
- ).then();
659
- } catch (errUpdate) {
660
- this.logChange(
661
- "updatePartialManyByCriteria",
662
- {
663
- ...criteria,
664
- set
665
- },
666
- repoOptions,
667
- user,
668
- errUpdate
669
- ).then();
670
- throw errUpdate;
671
- }
672
- });
673
- }
674
- updatePartialManyBySpecification(spec, set, user, repoOptions) {
675
- return this.updatePartialManyByCriteria(
676
- spec.criteria,
677
- set,
678
- user,
679
- repoOptions
680
- );
681
- }
682
- async delete(id, user, repoOptions) {
683
- await this.collectionContext(async (collection) => {
684
- try {
685
- await collection.deleteOne(
686
- { _id: id },
687
- { session: repoOptions?.transaction?.session }
688
- );
689
- this.logChange(
690
- "delete",
691
- {
692
- id
693
- },
694
- repoOptions,
695
- user,
696
- null
697
- ).then();
698
- } catch (errDelete) {
699
- this.logChange(
700
- "delete",
701
- {
702
- id
703
- },
704
- repoOptions,
705
- user,
706
- errDelete
707
- ).then();
708
- throw errDelete;
709
- }
710
- });
711
- }
712
- async getById(id, repoOptions) {
713
- return await this.collectionContext(async (collection) => {
714
- const item = await collection.findOne(
715
- { _id: id },
716
- {
717
- session: repoOptions?.transaction?.session
718
- }
719
- );
720
- return this.getModelToResult(item);
721
- });
722
- }
723
- async getByCriteria(criteria, options = {}) {
724
- return await this.collectionContext(async (collection) => {
725
- this.convertIdInCriteria(criteria);
726
- this.generateSearch(criteria);
727
- const totalCount = await this.getCount(criteria, collection);
728
- const aggregate = [];
729
- if (criteria) {
730
- aggregate.push({ $match: criteria });
731
- }
732
- if (options?.sort) {
733
- aggregate.push({ $sort: options.sort });
734
- }
735
- if (options?.skip) {
736
- aggregate.push({ $skip: options.skip });
737
- }
738
- if (options?.limit) {
739
- aggregate.push({ $limit: options.limit });
740
- }
741
- if (options?.project) {
742
- aggregate.push({ $project: options.project });
743
- }
744
- if (options?.min) {
745
- aggregate.push({ $min: options.min });
746
- }
747
- if (options?.max) {
748
- aggregate.push({ $max: options.max });
749
- }
750
- if (options?.group) {
751
- aggregate.push({ $group: options.group });
752
- }
753
- const list = await collection.aggregate(aggregate, {
754
- allowDiskUse: options?.allowDiskUse,
755
- session: options?.session
756
- }).toArray();
757
- return {
758
- data: list.map((item) => this.getModelToResult(item)),
759
- totalCount
760
- };
761
- });
762
- }
763
- getBySpecification(spec, options = {}) {
764
- return this.getByCriteria(spec.criteria, options);
765
- }
766
- async countByCriteria(criteria) {
767
- return await this.collectionContext(async (collection) => {
768
- this.convertIdInCriteria(criteria);
769
- this.generateSearch(criteria);
770
- return await this.getCount(criteria, collection);
771
- });
772
- }
773
- countBySpecification(spec) {
774
- return this.countByCriteria(spec.criteria);
775
- }
776
- changesByCriteria(criteria) {
777
- let stream;
778
- let client;
779
- return new Observable((observer) => {
780
- (async () => {
781
- try {
782
- client = await MongoClient3.connect(this.getUrl());
783
- const db = client.db(this.config.database);
784
- const collection = db.collection(this.config.collection);
785
- const pipeline = criteria.id ? [
786
- {
787
- $match: {
788
- "documentKey._id": criteria.id
789
- }
790
- }
791
- ] : [];
792
- stream = collection.watch(pipeline).on("change", (result) => {
793
- observer.next({
794
- id: result["documentKey"]["_id"],
795
- type: this.mapChangeType(result.operationType),
796
- data: result.operationType === "update" ? result["updateDescription"] : this.getModelToResult(result["fullDocument"])
797
- });
798
- });
799
- } catch (err) {
800
- observer.error(err);
801
- }
802
- })();
803
- }).pipe(
804
- finalize(async () => {
805
- console.log("Stop watch");
806
- await stream.close();
807
- await client.close();
808
- }),
809
- share()
810
- );
811
- }
812
- async getContext(handler) {
813
- const client = await MongoClient3.connect(this.getUrl());
814
- const db = client.db(this.config.database);
815
- try {
816
- const result = await handler(db);
817
- await client.close();
818
- return result;
819
- } catch (e) {
820
- await client.close();
821
- throw e;
822
- }
823
- }
824
- async getCount(criteria, collection) {
825
- this.convertIdInCriteria(criteria);
826
- return await collection.countDocuments(criteria);
827
- }
828
- async getInfo(id, collection) {
829
- const array = await collection.aggregate([{ $match: { _id: id } }, { $project: { __info: 1 } }]).toArray();
830
- return array[0] ? array[0]["__info"] : {};
831
- }
832
- getModelToCreate(item, user) {
833
- const result = ObjectService.removeTypes(item);
834
- result["_id"] = result.id;
835
- delete result.id;
836
- result["__info"] = {
837
- create: {
838
- username: user ? user.username : null,
839
- date: /* @__PURE__ */ new Date()
840
- }
841
- };
842
- return result;
843
- }
844
- mapChangeType(dbType) {
845
- const map = {
846
- insert: "create",
847
- update: "update",
848
- delete: "delete"
849
- };
850
- return map[dbType];
851
- }
852
- getModelToUpdate(item, user, info) {
853
- const result = ObjectService.removeTypes(item);
854
- result["_id"] = result.id;
855
- delete result.id;
856
- result["__info"] = {
857
- ...info,
858
- update: {
859
- username: user ? user.username : null,
860
- date: /* @__PURE__ */ new Date()
861
- }
862
- };
863
- return result;
864
- }
865
- getModelToResult(item) {
866
- if (!item) return null;
867
- const result = ObjectService.removeTypes(item);
868
- result["id"] = result._id;
869
- delete result._id;
870
- delete result["__info"];
871
- return result;
872
- }
873
- getUrl() {
874
- return getMongoUrl(this.config);
875
- }
876
- async logChange(type, item, options, user, error) {
877
- const client = await MongoClient3.connect(this.getUrl());
878
- const db = client.db(this.config.database);
879
- try {
880
- await db.collection("changes").insertOne({
881
- type,
882
- collection: this.config.collection,
883
- item,
884
- options,
885
- user,
886
- error,
887
- date: /* @__PURE__ */ new Date()
888
- });
889
- } catch (e) {
890
- console.warn(e);
891
- } finally {
892
- await client.close();
893
- }
894
- }
895
- generateSearch(criteria) {
896
- if (!criteria["$search"]) return;
897
- if (this.config.type) {
898
- const modelFields = getModelFieldsWithOptions(
899
- new this.config.type()
900
- ).filter((i) => i.options.search);
901
- if (modelFields.length) {
902
- const searchArray = [];
903
- modelFields.forEach((val) => {
904
- const res = {};
905
- res[val.key] = {
906
- $regex: this.convertRegex(criteria["$search"]),
907
- $options: "i"
908
- };
909
- searchArray.push(res);
910
- });
911
- if (!criteria["$or"]) criteria["$or"] = searchArray;
912
- else if (criteria["$or"] && !criteria["$and"]) {
913
- criteria["$and"] = [{ $or: criteria["$or"] }, { $or: searchArray }];
914
- delete criteria["$or"];
915
- } else if (criteria["$and"]) {
916
- criteria["$and"] = [...criteria["$and"], { $or: searchArray }];
917
- }
918
- delete criteria["$search"];
919
- return;
920
- }
921
- }
922
- const customCriteria = {
923
- $text: { $search: ' "' + this.convertRegex(criteria["$search"]) + '" ' }
924
- };
925
- delete criteria["$search"];
926
- Object.assign(criteria, customCriteria);
927
- }
928
- convertIdInCriteria(criteria) {
929
- if (criteria["id"]) {
930
- criteria["_id"] = criteria["id"];
931
- delete criteria["id"];
932
- }
933
- }
934
- convertRegex(val) {
935
- return val.toString().replace(/\*/g, "[*]");
936
- }
937
- async collectionContext(callback, repoOptions) {
938
- const client = repoOptions?.transaction?.connection ? repoOptions.transaction.connection : await MongoClient3.connect(this.getUrl());
939
- const db = client.db(this.config.database);
940
- let result;
941
- try {
942
- result = await callback(db.collection(this.config.collection));
943
- } finally {
944
- if (!repoOptions?.transaction)
945
- await client.close();
946
- }
947
- return result;
948
- }
949
- };
950
- MongoItemRepository = __decorateClass([
951
- Injectable4()
952
- ], MongoItemRepository);
953
-
954
- // packages/shared/mongo/src/lib/mongo.module.ts
955
- var MongoModule = class _MongoModule {
956
- static forRoot(config) {
957
- const providers = [
958
- { provide: MongoConfig, useValue: config },
959
- { provide: IItemRepository, useClass: MongoItemRepository },
960
- { provide: IAttachmentRepository, useClass: MongoAttachmentRepository },
961
- { provide: IUnitOfWork, useClass: MongoUnitOfWork }
962
- ];
963
- return {
964
- module: _MongoModule,
965
- providers,
966
- exports: providers
967
- };
968
- }
969
- };
970
-
971
- // packages/shared/nestjs/src/lib/shared.config.ts
972
- import { Injectable as Injectable5 } from "@nestjs/common";
973
- var SharedConfig = class {
974
- tokenConfig;
975
- permissions;
976
- type;
977
- };
978
- SharedConfig = __decorateClass([
979
- Injectable5()
980
- ], SharedConfig);
981
-
982
- // packages/shared/nestjs/src/lib/auth/jwt.strategy.ts
983
- import { Injectable as Injectable6 } from "@nestjs/common";
984
- import { PassportStrategy } from "@nestjs/passport";
985
- import { ExtractJwt, Strategy } from "passport-jwt";
986
- var JwtStrategy = class extends PassportStrategy(Strategy) {
987
- constructor(config) {
988
- super({
989
- jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
990
- ignoreExpiration: false,
991
- secretOrKey: config.tokenConfig?.secretOrPrivateKey
992
- });
993
- this.config = config;
994
- }
995
- config;
996
- async validate(payload) {
997
- return {
998
- ...payload,
999
- permissions: payload.permissions,
1000
- username: payload.sub
1001
- };
1002
- }
1003
- };
1004
- JwtStrategy = __decorateClass([
1005
- Injectable6()
1006
- ], JwtStrategy);
1007
-
1008
- // packages/shared/nestjs/src/lib/auth/permission.service.ts
1009
- import { Injectable as Injectable7 } from "@nestjs/common";
1010
- var PermissionService = class {
1011
- constructor(config) {
1012
- this.config = config;
1013
- }
1014
- config;
1015
- /**
1016
- * Validates if the user has the required permissions for a given type.
1017
- * @param {PermissionType} type - The type of permission to validate.
1018
- * @param {IUser} user - The user object containing permissions.
1019
- * @throws {DomainForbiddenError} If the user does not have the required permissions.
1020
- */
1021
- valid(type, user) {
1022
- if (!this.config.permissions) return;
1023
- const typeConfig = this.config.permissions[type];
1024
- if (!typeConfig) return;
1025
- if (!user.permissions) throw new DomainForbiddenError(`Context forbidden`);
1026
- if (!typeConfig.some((tc) => user.permissions.some((up) => tc === up)))
1027
- throw new DomainForbiddenError(`Context forbidden`);
1028
- }
1029
- };
1030
- PermissionService = __decorateClass([
1031
- Injectable7()
1032
- ], PermissionService);
1033
-
1034
- // packages/shared/nestjs/src/lib/shared.module.ts
1035
- var SharedModule = class _SharedModule {
1036
- /**
1037
- * Configures the module's core functionalities.
1038
- *
1039
- * @param {SharedConfig} config - An object containing the module's configuration.
1040
- * @returns {DynamicModule} A DynamicModule object with providers and exports.
1041
- */
1042
- static forFeature(config) {
1043
- return {
1044
- module: _SharedModule,
1045
- providers: [
1046
- { provide: SharedConfig, useValue: config },
1047
- JwtStrategy,
1048
- PermissionService
1049
- ],
1050
- exports: [
1051
- { provide: SharedConfig, useValue: config },
1052
- PermissionService,
1053
- JwtStrategy
1054
- ]
1055
- };
1056
- }
1057
- /**
1058
- * Extends the forFeature() configuration by adding database settings. Use in AppModule.
1059
- *
1060
- * @param {SharedConfig & { db: { host: string; port: number; database: string; username?: string; password?: string; }}} config - An extended SharedConfig object that includes additional database settings.
1061
- * @returns {DynamicModule} A DynamicModule object that imports and exports the forFeature() configuration.
1062
- */
1063
- static forRoot(config) {
1064
- return {
1065
- module: _SharedModule,
1066
- imports: [_SharedModule.forFeature(config)],
1067
- exports: [_SharedModule.forFeature(config)]
1068
- };
1069
- }
1070
- };
1071
-
1072
- // packages/shared/nestjs/src/lib/filters/execution/exception.filter.ts
1073
- import {
1074
- Catch,
1075
- HttpException,
1076
- HttpStatus,
1077
- Logger as Logger2
1078
- } from "@nestjs/common";
1079
- var AppExceptionFilter = class {
1080
- /**
1081
- * Method to catch and handle exceptions.
1082
- *
1083
- * @param {any} exception - The exception thrown.
1084
- * @param {ArgumentsHost} host - The arguments host.
1085
- */
1086
- catch(exception, host) {
1087
- const ctx = host.switchToHttp();
1088
- const response = ctx.getResponse();
1089
- let status = HttpStatus.INTERNAL_SERVER_ERROR;
1090
- let message = null;
1091
- if (exception instanceof HttpException) {
1092
- status = exception.getStatus();
1093
- message = exception["message"];
1094
- } else if (exception["type"] === DomainValidationError) {
1095
- status = HttpStatus.BAD_REQUEST;
1096
- message = exception["message"];
1097
- } else if (exception["type"] === DomainForbiddenError) {
1098
- status = HttpStatus.FORBIDDEN;
1099
- message = exception["message"];
1100
- } else {
1101
- status = HttpStatus.INTERNAL_SERVER_ERROR;
1102
- message = "Internal server error";
1103
- }
1104
- Logger2.error(
1105
- exception["stack"] || exception["message"] || exception,
1106
- AppExceptionFilter.name
1107
- );
1108
- const result = response.status(status);
1109
- if (message && result.json) {
1110
- result.json({
1111
- details: message
1112
- });
1113
- } else if (!message && result.json) {
1114
- result.json();
1115
- } else if (message && !result.json) {
1116
- result.send({
1117
- details: message
1118
- });
1119
- } else {
1120
- result.send();
1121
- }
1122
- }
1123
- };
1124
- AppExceptionFilter = __decorateClass([
1125
- Catch()
1126
- ], AppExceptionFilter);
1127
-
1128
- // packages/shared/nestjs/src/lib/decorators/user/user.decorator.ts
1129
- import { createParamDecorator } from "@nestjs/common";
1130
- var User = createParamDecorator((_3, context) => {
1131
- const [req] = context.getArgs();
1132
- return req.user;
1133
- });
1134
-
1135
- // packages/crud/shell/nestjs/src/lib/controllers/crud/crud.controller.ts
1136
- import {
1137
- Body,
1138
- Controller,
1139
- Delete,
1140
- Get,
1141
- HttpCode,
1142
- NotFoundException,
1143
- Param,
1144
- Patch,
1145
- Post,
1146
- Put,
1147
- Query,
1148
- Req,
1149
- Res,
1150
- UseGuards
1151
- } from "@nestjs/common";
1152
- import * as Busboy from "busboy";
1153
- import { Parser } from "json2csv";
1154
- import * as _2 from "lodash";
1155
- import moment from "moment-timezone";
1156
- import * as XLSX from "xlsx";
1157
- import { Readable } from "stream";
1158
-
1159
- // packages/crud/shell/nestjs/src/lib/controllers/crud/query-to-mongo.ts
1160
- import * as querystring from "querystring";
1161
- var iso8601 = /^\d{4}(-(0[1-9]|1[0-2])(-(0[1-9]|[12][0-9]|3[01]))?)?(T([01][0-9]|2[0-3]):[0-5]\d(:[0-5]\d(\.\d+)?)?(Z|[+-]\d{2}:\d{2}))?$/;
1162
- function fieldsToMongo(fields) {
1163
- if (!fields) return null;
1164
- const hash = {};
1165
- fields.split(",").forEach(function(field) {
1166
- hash[field.trim()] = 1;
1167
- });
1168
- return hash;
1169
- }
1170
- function convertRegex(val) {
1171
- return val.toString().replace(/\*/g, "[*]");
1172
- }
1173
- function omitFieldsToMongo(omitFields) {
1174
- if (!omitFields) return null;
1175
- const hash = {};
1176
- omitFields.split(",").forEach(function(omitField) {
1177
- hash[omitField.trim()] = 0;
1178
- });
1179
- return hash;
1180
- }
1181
- function sortToMongo(sort) {
1182
- if (!sort) return null;
1183
- const hash = {};
1184
- let c;
1185
- sort.split(",").forEach(function(field) {
1186
- c = field.charAt(0);
1187
- if (c === "-") field = field.substr(1);
1188
- hash[field.trim()] = c === "-" ? -1 : 1;
1189
- });
1190
- return hash;
1191
- }
1192
- function typedValue(value) {
1193
- if (value[0] === "!") value = value.substr(1);
1194
- const regex = value.match(/^\/(.*)\/(i?)$/);
1195
- const quotedString = value.match(/(["'])(?:\\\1|.)*?\1/);
1196
- if (regex) {
1197
- return new RegExp(regex[1], regex[2]);
1198
- } else if (quotedString) {
1199
- return quotedString[0].substr(1, quotedString[0].length - 2);
1200
- } else if (value === "true") {
1201
- return true;
1202
- } else if (value === "false") {
1203
- return false;
1204
- } else if (iso8601.test(value) && value.length !== 4 && value.length !== 10) {
1205
- return new Date(value);
1206
- } else if (!isNaN(Number(value))) {
1207
- return Number(value);
1208
- }
1209
- return value;
1210
- }
1211
- function typedValues(svalue) {
1212
- const commaSplit = /("[^"]*")|('[^']*')|(\/[^/]*\/i?)|([^,]+)/g;
1213
- const values = [];
1214
- svalue.match(commaSplit).forEach(function(value) {
1215
- values.push(typedValue(value));
1216
- });
1217
- return values;
1218
- }
1219
- function comparisonToMongo(key, value) {
1220
- const join = value === "" ? key : key.concat("=", value);
1221
- const parts = join.match(/^(!?[^><~!=:]+)(?:=?([><]=?|~?=|!?=|:.+=)(.+))?$/);
1222
- let op;
1223
- const hash = {};
1224
- if (!parts) return null;
1225
- key = parts[1];
1226
- op = parts[2];
1227
- if (!op) {
1228
- if (key[0] !== "!") value = { $exists: true };
1229
- else {
1230
- key = key.substr(1);
1231
- value = { $exists: false };
1232
- }
1233
- } else if (op === "=" && parts[3] === "!") {
1234
- value = { $exists: false };
1235
- } else if (op === "=" || op === "!=") {
1236
- if (op === "=" && parts[3][0] === "!") op = "!=";
1237
- const array = typedValues(parts[3]);
1238
- if (array.length > 1) {
1239
- value = {};
1240
- op = op === "=" ? "$in" : "$nin";
1241
- value[op] = array;
1242
- } else if (op === "!=") {
1243
- value = array[0] instanceof RegExp ? { $not: array[0] } : { $ne: array[0] };
1244
- } else if (array[0][0] === "!") {
1245
- const sValue = array[0].substr(1);
1246
- const regex = sValue.match(/^\/(.*)\/(i?)$/);
1247
- value = regex ? { $not: new RegExp(regex[1], regex[2]) } : { $ne: sValue };
1248
- } else {
1249
- value = array[0];
1250
- }
1251
- } else if (op[0] === ":" && op[op.length - 1] === "=") {
1252
- op = "$" + op.substr(1, op.length - 2);
1253
- const array = [];
1254
- parts[3].split(",").forEach(function(value2) {
1255
- array.push(typedValue(value2));
1256
- });
1257
- value = {};
1258
- value[op] = array.length === 1 ? array[0] : array;
1259
- } else {
1260
- value = typedValue(parts[3]);
1261
- if (op === ">") value = { $gt: value };
1262
- else if (op === ">=") value = { $gte: value };
1263
- else if (op === "<") value = { $lt: value };
1264
- else if (op === "<=") value = { $lte: value };
1265
- else if (op === "~=")
1266
- value = {
1267
- $regex: value ? convertRegex(value) : "",
1268
- $options: "i"
1269
- };
1270
- }
1271
- hash.key = key;
1272
- hash.value = value;
1273
- return hash;
1274
- }
1275
- function hasOrdinalKeys(obj) {
1276
- let c = 0;
1277
- for (const key in obj) {
1278
- if (Number(key) !== c++) return false;
1279
- }
1280
- return true;
1281
- }
1282
- function queryCriteriaToMongo(query, options = null) {
1283
- const hash = {};
1284
- let deep, p;
1285
- options = options || {};
1286
- for (const key in query) {
1287
- if (Object.prototype.hasOwnProperty.call(query, key) && (!options.ignore || options.ignore.indexOf(key) === -1)) {
1288
- deep = typeof query[key] === "object" && !hasOrdinalKeys(query[key]);
1289
- if (deep) {
1290
- p = {
1291
- key,
1292
- value: queryCriteriaToMongo(query[key])
1293
- };
1294
- } else {
1295
- p = comparisonToMongo(key, query[key]);
1296
- }
1297
- if (p) {
1298
- if (!hash[p.key]) {
1299
- hash[p.key] = p.value;
1300
- } else if (typeof p.value === "string") {
1301
- hash[p.key] = Object.assign(hash[p.key], {
1302
- $eq: p.value
1303
- });
1304
- } else {
1305
- hash[p.key] = Object.assign(hash[p.key], p.value);
1306
- }
1307
- }
1308
- }
1309
- }
1310
- return hash;
1311
- }
1312
- function queryOptionsToMongo(query, options) {
1313
- const hash = {}, fields = fieldsToMongo(query[options.keywords.fields]), omitFields = omitFieldsToMongo(query[options.keywords.omit]), sort = sortToMongo(query[options.keywords.sort]), maxLimit = options.maxLimit || 9007199254740992;
1314
- let limit = options.maxLimit || 0;
1315
- if (fields) hash.fields = fields;
1316
- if (omitFields) hash.fields = omitFields;
1317
- if (sort) hash.sort = sort;
1318
- if (query[options.keywords.offset])
1319
- hash.skip = Number(query[options.keywords.offset]);
1320
- if (query[options.keywords.limit])
1321
- limit = Math.min(Number(query[options.keywords.limit]), maxLimit);
1322
- if (limit) {
1323
- hash.limit = limit;
1324
- } else if (options.maxLimit) {
1325
- hash.limit = maxLimit;
1326
- }
1327
- return hash;
1328
- }
1329
- function q2m(query = null, options = null) {
1330
- query = query || {};
1331
- options = options || {};
1332
- options.keywords = options.keywords || {};
1333
- const defaultKeywords = {
1334
- fields: "fields",
1335
- omit: "omit",
1336
- sort: "sort",
1337
- offset: "offset",
1338
- limit: "limit"
1339
- };
1340
- options.keywords = Object.assign(defaultKeywords, options.keywords);
1341
- const ignoreKeywords = [
1342
- options.keywords.fields,
1343
- options.keywords.omit,
1344
- options.keywords.sort,
1345
- options.keywords.offset,
1346
- options.keywords.limit
1347
- ];
1348
- if (!options.ignore) {
1349
- options.ignore = [];
1350
- } else {
1351
- options.ignore = typeof options.ignore === "string" ? [options.ignore] : options.ignore;
1352
- }
1353
- options.ignore = options.ignore.concat(ignoreKeywords);
1354
- if (!options.parser) options.parser = querystring;
1355
- if (typeof query === "string") query = options.parser.parse(query);
1356
- return {
1357
- criteria: queryCriteriaToMongo(query, options),
1358
- options: queryOptionsToMongo(query, options),
1359
- links: function(url, totalCount) {
1360
- const offset = this.options.skip || 0;
1361
- const limit = Math.min(this.options.limit || 0, totalCount);
1362
- const links = {};
1363
- const last = {};
1364
- if (!limit) return null;
1365
- options = options || {};
1366
- if (offset > 0) {
1367
- query[options.keywords.offset] = Math.max(offset - limit, 0);
1368
- links["prev"] = url + "?" + options.parser.stringify(query);
1369
- query[options.keywords.offset] = 0;
1370
- links["first"] = url + "?" + options.parser.stringify(query);
1371
- }
1372
- if (offset + limit < totalCount) {
1373
- last.pages = Math.ceil(totalCount / limit);
1374
- last.offset = (last.pages - 1) * limit;
1375
- query[options.keywords.offset] = Math.min(offset + limit, last.offset);
1376
- links["next"] = url + "?" + options.parser.stringify(query);
1377
- query[options.keywords.offset] = last.offset;
1378
- links["last"] = url + "?" + options.parser.stringify(query);
1379
- }
1380
- return links;
1381
- }
1382
- };
1383
- }
1384
-
1385
- // packages/crud/shell/nestjs/src/lib/guards/auth/auth.guard.ts
1386
- import { Injectable as Injectable8, UnauthorizedException, Logger as Logger3 } from "@nestjs/common";
1387
- import { AuthGuard } from "@nestjs/passport";
1388
- var AuthJwtGuard = class extends AuthGuard("jwt") {
1389
- logger = new Logger3(AuthJwtGuard.name, { timestamp: true });
1390
- handleRequest(err, user, info) {
1391
- if (err || !user) {
1392
- this.logger.warn(JSON.stringify(info));
1393
- throw err || new UnauthorizedException();
1394
- }
1395
- return user;
1396
- }
1397
- };
1398
- AuthJwtGuard = __decorateClass([
1399
- Injectable8()
1400
- ], AuthJwtGuard);
1401
- var AuthOrAnonymousJwtGuard = class extends AuthGuard("jwt") {
1402
- handleRequest(err, user, info) {
1403
- return user;
1404
- }
1405
- };
1406
- AuthOrAnonymousJwtGuard = __decorateClass([
1407
- Injectable8()
1408
- ], AuthOrAnonymousJwtGuard);
1409
-
1410
- // packages/crud/shell/nestjs/src/lib/controllers/crud/crud.controller.ts
1411
- var CrudController = class {
1412
- constructor(service) {
1413
- this.service = service;
1414
- }
1415
- service;
1416
- static getLink(req) {
1417
- return req.protocol + "://" + req.headers.host + req.url;
1418
- }
1419
- async create(data, user, res) {
1420
- const id = await this.service.create(data, user);
1421
- res.set("Location", CrudController.getLink(res.req) + "/" + id);
1422
- return res.send({
1423
- id
1424
- });
1425
- }
1426
- async createMany(data, user, res, mode) {
1427
- const result = await this.service.createMany(data, user, { mode });
1428
- return res.send(result);
1429
- }
1430
- async readById(params, user) {
1431
- const result = await this.service.readById(params.id, user);
1432
- if (!result) {
1433
- throw new NotFoundException("Invalid id");
1434
- }
1435
- return result;
1436
- }
1437
- async read(user, req, res) {
1438
- const object = this.getQueryObject(req.query);
1439
- const { data, totalCount } = await this.service.read(
1440
- object.criteria,
1441
- {
1442
- ...object.options,
1443
- allowDiskUse: req.headers["content-type"] === "text/csv" || req.headers["content-type"] === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
1444
- },
1445
- user
1446
- );
1447
- if (req.headers["content-type"] === "text/csv") {
1448
- res.set({
1449
- "Content-Type": "text/csv"
1450
- });
1451
- res.send(this.parseToCsv(data));
1452
- }
1453
- if (req.headers["content-type"] === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") {
1454
- res.set({
1455
- "Content-Type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
1456
- });
1457
- res.send(this.parseToXlsx(data));
1458
- }
1459
- res.send({
1460
- data,
1461
- totalCount,
1462
- links: object.links(
1463
- CrudController.getLink(req).split("?")[0],
1464
- totalCount
1465
- )
1466
- });
1467
- }
1468
- async update(params, data, user) {
1469
- await this.service.update(params.id, data, user);
1470
- }
1471
- async updatePartial(params, data, user) {
1472
- await this.service.updatePartial(params.id, data, user);
1473
- }
1474
- async delete(params, user) {
1475
- await this.service.delete(params.id, user);
1476
- }
1477
- uploadAttachment(request, response) {
1478
- const busboy = new Busboy({
1479
- headers: request.headers
1480
- });
1481
- const id = GuidService.create();
1482
- const readable = new Readable();
1483
- readable._read = () => {
1484
- };
1485
- let fileName, encoding, mimeType;
1486
- busboy.on(
1487
- "file",
1488
- (field, file, resultFileName, resultEncoding, resultMimeType) => {
1489
- fileName = resultFileName;
1490
- encoding = resultEncoding;
1491
- mimeType = resultMimeType;
1492
- this.service.uploadAttachment({
1493
- id,
1494
- stream: readable,
1495
- fileName,
1496
- encoding,
1497
- mimeType
1498
- });
1499
- file.on("data", (data) => {
1500
- readable.push(data);
1501
- });
1502
- }
1503
- );
1504
- busboy.on("finish", function() {
1505
- readable.push(null);
1506
- response.set("Location", CrudController.getLink(response.req) + "/" + id);
1507
- response.json({
1508
- id,
1509
- fileName,
1510
- contentType: mimeType,
1511
- length: readable.readableLength
1512
- });
1513
- response.end();
1514
- });
1515
- return request.pipe(busboy);
1516
- }
1517
- async downloadAttachment(id, request, response) {
1518
- const fileInfo = await this.service.getAttachmentInfo(id);
1519
- if (request.headers.range) {
1520
- const range = request.headers.range.substr(6).split("-");
1521
- const start = parseInt(range[0], 10);
1522
- const end = parseInt(range[1], 10) || null;
1523
- const readstream = await this.service.getAttachmentStream(id, {
1524
- start,
1525
- end
1526
- });
1527
- response.status(206);
1528
- response.set({
1529
- "Accept-Ranges": "bytes",
1530
- "Content-Type": fileInfo.contentType,
1531
- "Content-Range": `bytes ${start}-${end ? end : fileInfo.length - 1}/${fileInfo.length}`,
1532
- "Content-Length": (end ? end : fileInfo.length) - start,
1533
- "Content-Disposition": `attachment; filename="${encodeURI(fileInfo.fileName)}"`
1534
- });
1535
- response.on("close", () => {
1536
- readstream.destroy();
1537
- });
1538
- readstream.pipe(response);
1539
- } else {
1540
- const readstream = await this.service.getAttachmentStream(id);
1541
- response.on("close", () => {
1542
- readstream.destroy();
1543
- });
1544
- response.status(200);
1545
- response.set({
1546
- "Accept-Range": "bytes",
1547
- "Content-Type": fileInfo.contentType,
1548
- "Content-Length": fileInfo.length,
1549
- "Content-Disposition": `attachment; filename="${encodeURI(fileInfo.fileName)}"`
1550
- });
1551
- readstream.pipe(response);
1552
- }
1553
- }
1554
- async deleteAttachment(id) {
1555
- await this.service.deleteAttachment(id);
1556
- }
1557
- getQueryObject(queryObject) {
1558
- let q = "";
1559
- Object.keys(queryObject).forEach((key) => {
1560
- q += `&${key}=${queryObject[key]}`;
1561
- });
1562
- const result = q2m(q);
1563
- return result;
1564
- }
1565
- parseToXlsx(data) {
1566
- if (!data || !data.length) {
1567
- return "";
1568
- }
1569
- const { res } = this.getDataWithFields(data);
1570
- const ws = XLSX.utils.json_to_sheet(res);
1571
- const wb = XLSX.utils.book_new();
1572
- XLSX.utils.book_append_sheet(wb, ws, "data");
1573
- return XLSX.write(wb, { bookType: "xlsx", type: "buffer" });
1574
- }
1575
- parseToCsv(data) {
1576
- if (!data || !data.length) {
1577
- return "";
1578
- }
1579
- const { res, fields } = this.getDataWithFields(data);
1580
- return new Parser(fields).parse(data);
1581
- }
1582
- getDataWithFields(data) {
1583
- const fields = [];
1584
- const execute = (item, baseKey, baseItem) => {
1585
- Object.keys(item).forEach((key) => {
1586
- if (item[key] && typeof item[key] === "string") {
1587
- item[key] = item[key].replace(/<[^>]*>?/gm, "");
1588
- }
1589
- if (item[key] && item[key] instanceof Date) {
1590
- item[key] = moment(item[key]).tz("Europe/Warsaw").format("YYYY-MM-DD HH:mm:ss");
1591
- }
1592
- const val = item[key];
1593
- if (_2.isArray(val)) {
1594
- return;
1595
- } else if (_2.isObject(val) && Object.keys(val).length) {
1596
- execute(val, baseKey + key + "_", baseItem);
1597
- } else if (baseKey) {
1598
- baseItem[baseKey + key] = val;
1599
- if (!fields.some((f) => f === baseKey + key))
1600
- fields.push(baseKey + key);
1601
- } else {
1602
- if (!fields.some((f) => f === key)) fields.push(key);
1603
- }
1604
- });
1605
- };
1606
- data.forEach((item) => {
1607
- execute(item, "", item);
1608
- });
1609
- data.forEach((item) => {
1610
- Object.keys(item).forEach((key) => {
1611
- if (!fields.some((f) => f === key)) {
1612
- delete item[key];
1613
- }
1614
- });
1615
- });
1616
- return { res: data, fields };
1617
- }
1618
- };
1619
- __decorateClass([
1620
- UseGuards(AuthJwtGuard),
1621
- Post(),
1622
- HttpCode(200),
1623
- __decorateParam(0, Body()),
1624
- __decorateParam(1, User()),
1625
- __decorateParam(2, Res())
1626
- ], CrudController.prototype, "create", 1);
1627
- __decorateClass([
1628
- UseGuards(AuthJwtGuard),
1629
- Post("bulk"),
1630
- __decorateParam(0, Body()),
1631
- __decorateParam(1, User()),
1632
- __decorateParam(2, Res()),
1633
- __decorateParam(3, Query("mode"))
1634
- ], CrudController.prototype, "createMany", 1);
1635
- __decorateClass([
1636
- UseGuards(AuthOrAnonymousJwtGuard),
1637
- Get(":id"),
1638
- __decorateParam(0, Param()),
1639
- __decorateParam(1, User())
1640
- ], CrudController.prototype, "readById", 1);
1641
- __decorateClass([
1642
- UseGuards(AuthOrAnonymousJwtGuard),
1643
- Get(),
1644
- __decorateParam(0, User()),
1645
- __decorateParam(1, Req()),
1646
- __decorateParam(2, Res())
1647
- ], CrudController.prototype, "read", 1);
1648
- __decorateClass([
1649
- UseGuards(AuthJwtGuard),
1650
- Put(":id"),
1651
- __decorateParam(0, Param()),
1652
- __decorateParam(1, Body()),
1653
- __decorateParam(2, User())
1654
- ], CrudController.prototype, "update", 1);
1655
- __decorateClass([
1656
- UseGuards(AuthJwtGuard),
1657
- Patch(":id"),
1658
- __decorateParam(0, Param()),
1659
- __decorateParam(1, Body()),
1660
- __decorateParam(2, User())
1661
- ], CrudController.prototype, "updatePartial", 1);
1662
- __decorateClass([
1663
- UseGuards(AuthJwtGuard),
1664
- Delete(":id"),
1665
- __decorateParam(0, Param()),
1666
- __decorateParam(1, User())
1667
- ], CrudController.prototype, "delete", 1);
1668
- __decorateClass([
1669
- Post("attachments"),
1670
- __decorateParam(0, Req()),
1671
- __decorateParam(1, Res())
1672
- ], CrudController.prototype, "uploadAttachment", 1);
1673
- __decorateClass([
1674
- Get("attachments/:id"),
1675
- __decorateParam(0, Param("id")),
1676
- __decorateParam(1, Req()),
1677
- __decorateParam(2, Res())
1678
- ], CrudController.prototype, "downloadAttachment", 1);
1679
- __decorateClass([
1680
- Delete("attachments/:id"),
1681
- __decorateParam(0, Param("id"))
1682
- ], CrudController.prototype, "deleteAttachment", 1);
1683
- CrudController = __decorateClass([
1684
- Controller("")
1685
- ], CrudController);
1686
-
1687
- // packages/crud/shell/nestjs/src/lib/controllers/index.ts
1688
- var CONTROLLERS = [CrudController];
1689
-
1690
- // packages/crud/shell/nestjs/src/lib/gateways/crud/crud.gateway.ts
1691
- import {
1692
- ConnectedSocket,
1693
- MessageBody,
1694
- SubscribeMessage,
1695
- WebSocketGateway
1696
- } from "@nestjs/websockets";
1697
- import { Observable as Observable2 } from "rxjs";
1698
- var CrudGateway = class {
1699
- constructor(service) {
1700
- this.service = service;
1701
- }
1702
- service;
1703
- _clientsSubscriptions;
1704
- handleFilter(data, client) {
1705
- const event = "changes";
1706
- return new Observable2((observer) => {
1707
- this.clearSubscription(client);
1708
- this._clientsSubscriptions.set(
1709
- client.id,
1710
- this.service.changes(data).subscribe(
1711
- (res) => {
1712
- observer.next({ event, data: res });
1713
- },
1714
- (error) => observer.error(error)
1715
- )
1716
- );
1717
- });
1718
- }
1719
- afterInit(server) {
1720
- this._clientsSubscriptions = /* @__PURE__ */ new Map();
1721
- console.log("CrudGateway Init");
1722
- }
1723
- handleDisconnect(client) {
1724
- this.clearSubscription(client);
1725
- console.log(`Client disconnected: ${client.id}`);
1726
- }
1727
- clearSubscription(client) {
1728
- if (this._clientsSubscriptions.has(client.id)) {
1729
- this._clientsSubscriptions.get(client.id).unsubscribe();
1730
- this._clientsSubscriptions.delete(client.id);
1731
- }
1732
- }
1733
- handleConnection(client, ...args) {
1734
- console.log(`Client connected: ${client.id}`);
1735
- }
1736
- };
1737
- __decorateClass([
1738
- SubscribeMessage("changes"),
1739
- __decorateParam(0, MessageBody()),
1740
- __decorateParam(1, ConnectedSocket())
1741
- ], CrudGateway.prototype, "handleFilter", 1);
1742
- CrudGateway = __decorateClass([
1743
- WebSocketGateway({
1744
- transports: ["websocket"],
1745
- path: "/" + process.env.URL_PREFIX + "/_socket",
1746
- namespace: "/" + process.env.URL_PREFIX
1747
- })
1748
- ], CrudGateway);
1749
-
1750
- // packages/crud/shell/nestjs/src/lib/gateways/index.ts
1751
- var GATEWAYS = [CrudGateway];
1752
-
1753
- // packages/crud/shell/nestjs/src/lib/nestjs.module.ts
1754
- var CrudShellNestjsModule = class {
1755
- static forRoot(options) {
1756
- return {
1757
- module: CrudShellNestjsModule,
1758
- controllers: options.restApi ? CONTROLLERS : [],
1759
- providers: [
1760
- ...SERVICES,
1761
- ...options.socket ? GATEWAYS : [],
1762
- AuthJwtGuard
1763
- ],
1764
- imports: [
1765
- ...options.restApi && options.tokenConfig.secretOrPrivateKey ? [
1766
- PassportModule.register({
1767
- defaultStrategy: "jwt",
1768
- session: false
1769
- }),
1770
- JwtModule.register({
1771
- secret: options.tokenConfig.secretOrPrivateKey,
1772
- signOptions: {
1773
- expiresIn: options.tokenConfig.expiredIn
1774
- }
1775
- })
1776
- ] : [],
1777
- SharedModule.forFeature(options),
1778
- MongoModule.forRoot(options.db)
1779
- ],
1780
- exports: [...SERVICES, AuthJwtGuard, MongoModule.forRoot(options.db)]
1781
- };
1782
- }
1783
- };
1784
- CrudShellNestjsModule = __decorateClass([
1785
- Module({})
1786
- ], CrudShellNestjsModule);
1787
- var CrudShellNestjsCoreModule = class {
1788
- static forRoot(options) {
1789
- return {
1790
- module: CrudShellNestjsModule,
1791
- providers: [...SERVICES, ...GATEWAYS, AuthJwtGuard],
1792
- imports: [
1793
- PassportModule.register({ defaultStrategy: "jwt", session: false }),
1794
- JwtModule.register({
1795
- secret: options.tokenConfig.secretOrPrivateKey,
1796
- signOptions: {
1797
- expiresIn: options.tokenConfig.expiredIn
1798
- }
1799
- }),
1800
- SharedModule.forRoot(options),
1801
- MongoModule.forRoot(options.db)
1802
- ],
1803
- exports: []
1804
- };
1805
- }
1806
- };
1807
- CrudShellNestjsCoreModule = __decorateClass([
1808
- Module({})
1809
- ], CrudShellNestjsCoreModule);
1810
- export {
1811
- AuthJwtGuard,
1812
- AuthOrAnonymousJwtGuard,
1813
- CONTROLLERS,
1814
- CrudController,
1815
- CrudShellNestjsCoreModule,
1816
- CrudShellNestjsModule,
1817
- GATEWAYS
1818
- };