@punks/backend-entity-manager 0.0.94 → 0.0.95

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/dist/cjs/index.js CHANGED
@@ -285,941 +285,550 @@ class EntitySerializer {
285
285
  }
286
286
  }
287
287
 
288
- const PLATFORM_EVENT_NAMESPACE = "platform";
289
- const PlatformEvents = {
290
- Messaging: {
291
- EmailSent: `${PLATFORM_EVENT_NAMESPACE}:messaging.emailSent`,
292
- },
293
- };
294
-
295
- class NestEntityAuthorizationMiddleware {
288
+ class EntitiesCountAction {
289
+ constructor(services) {
290
+ this.services = services;
291
+ }
292
+ async execute(filters) {
293
+ return await this.services.resolveCountQuery().execute(filters);
294
+ }
296
295
  }
297
296
 
298
- class NestEntityActions {
299
- // todo: resolve entity name from decorator
300
- constructor(entityName, registry) {
301
- this.services = registry.resolveEntityServicesCollection(entityName);
297
+ class EntityCreateAction {
298
+ constructor(services) {
299
+ this.services = services;
300
+ this.logger = backendCore.Log.getLogger(`${services.getEntityName()} -> Create`);
302
301
  }
303
- get manager() {
304
- if (!this.actionsInstance) {
305
- this.actionsInstance =
306
- this.services.resolveEntityActions();
307
- }
308
- return this.actionsInstance;
302
+ async execute(input) {
303
+ this.logger.debug("Create action started", { input });
304
+ const converter = this.services.resolveConverter();
305
+ const createInput = converter?.createDtoToEntity(input) ?? input;
306
+ const entity = await this.services
307
+ .resolveCreateCommand()
308
+ .execute(createInput);
309
+ const result = converter?.toEntityDto(entity) ?? entity;
310
+ this.logger.debug("Create action completed", { input, result });
311
+ return result;
309
312
  }
310
313
  }
311
314
 
312
- class NestEntityManager {
313
- // todo: resolve entity name from decorator
314
- constructor(entityName, registry) {
315
- this.services = registry.resolveEntityServicesCollection(entityName);
315
+ class EntityDeleteAction {
316
+ constructor(services) {
317
+ this.services = services;
318
+ this.logger = backendCore.Log.getLogger(`${services.getEntityName()} -> Delete`);
316
319
  }
317
- get manager() {
318
- if (!this.managerInstance) {
319
- this.managerInstance =
320
- this.services.resolveEntityManager();
321
- }
322
- return this.managerInstance;
320
+ async execute(id) {
321
+ this.logger.debug("Delete action started", { id });
322
+ await this.services.resolveDeleteCommand().execute(id);
323
+ this.logger.debug("Delete action completed", { id });
323
324
  }
324
325
  }
325
326
 
326
- class NestEntitySerializer extends EntitySerializer {
327
- constructor(entityName, registry) {
328
- super(entityName);
329
- // this.services = registry.resolveEntityServicesCollection(entityName)
327
+ class EntitiesDeleteAction {
328
+ constructor(services) {
329
+ this.services = services;
330
+ this.logger = backendCore.Log.getLogger(`${services.getEntityName()} -> DeleteItems`);
331
+ }
332
+ async execute(params) {
333
+ this.logger.debug("DeleteItems action started");
334
+ await this.services.resolveDeleteItemsCommand().execute(params);
335
+ this.logger.debug("DeleteItems action completed");
330
336
  }
331
337
  }
332
338
 
333
- const EntityManagerSymbols = {
334
- AppInitializer: Symbol.for("WP:APP_INITIALIZER"),
335
- EventsTracker: Symbol.for("WP:EVENTS_TRACKER"),
336
- Entity: Symbol.for("WP:ENTITY"),
337
- EntityActions: Symbol.for("WP:ENTITY_ACTIONS"),
338
- EntityAdapter: Symbol.for("WP:ENTITY_ADAPTER"),
339
- EntityAuthMiddleware: Symbol.for("WP:ENTITY_AUTH_MIDDLEWARE"),
340
- EntityRepository: Symbol.for("WP:ENTITY_REPOSITORY"),
341
- EntityConnector: Symbol.for("WP:ENTITY_CONNECTOR"),
342
- EntityConverter: Symbol.for("WP:ENTITY_CONVERTER"),
343
- EntitySerializer: Symbol.for("WP:ENTITY_SERIALIZER"),
344
- EntityManager: Symbol.for("WP:ENTITY_MANAGER"),
345
- EntityQueryBuilder: Symbol.for("WP:ENTITY_QUERY_BUILDER"),
346
- EntitySeeder: Symbol.for("WP:ENTITY_SEEDER"),
347
- EmailProvider: Symbol.for("WP:EMAIL_PROVIDER"),
348
- EmailTemplate: Symbol.for("WP:EMAIL_TEMPLATE"),
349
- BucketProvider: Symbol.for("WP:BUCKET_PROVIDER"),
350
- PipelineTemplate: Symbol.for("WP:PIPELINE_TEMPLATE"),
351
- };
352
-
353
- const WpEntityAuthMiddleware = (entityName, props = {}) => common.applyDecorators(common.Injectable(), common.SetMetadata(EntityManagerSymbols.EntityAuthMiddleware, {
354
- entityName,
355
- ...props,
356
- }));
357
-
358
- const WpBucketProvider = (providerId) => common.applyDecorators(common.Injectable(), common.SetMetadata(EntityManagerSymbols.BucketProvider, {
359
- providerId,
360
- }));
361
-
362
- const WpEntityActions = (entityName, props = {}) => common.applyDecorators(common.Injectable(), common.SetMetadata(EntityManagerSymbols.EntityActions, {
363
- entityName,
364
- ...props,
365
- }));
366
-
367
- const WpEntityAdapter = (entityName, props = {}) => common.applyDecorators(common.Injectable(), common.SetMetadata(EntityManagerSymbols.EntityAdapter, {
368
- entityName,
369
- ...props,
370
- }));
371
-
372
- const WpEntityConnector = (entityName, props = {}) => common.applyDecorators(common.Injectable(), common.SetMetadata(EntityManagerSymbols.EntityConnector, {
373
- entityName,
374
- ...props,
375
- }));
376
-
377
- const WpEntityConverter = (entityName, props = {}) => common.applyDecorators(common.Injectable(), common.SetMetadata(EntityManagerSymbols.EntityConverter, {
378
- entityName,
379
- ...props,
380
- }));
339
+ class EntityExistsAction {
340
+ constructor(services) {
341
+ this.services = services;
342
+ }
343
+ async execute(filters) {
344
+ return await this.services.resolveExistsQuery().execute(filters);
345
+ }
346
+ }
381
347
 
382
- const WpEmailTemplate = (templateId) => common.applyDecorators(common.Injectable(), common.SetMetadata(EntityManagerSymbols.EmailTemplate, {
383
- templateId,
384
- }));
385
- const WpEmailProvider = (providerId) => common.applyDecorators(common.Injectable(), common.SetMetadata(EntityManagerSymbols.EmailProvider, {
386
- providerId,
387
- }));
348
+ class EntitiesExportAction {
349
+ constructor(services) {
350
+ this.services = services;
351
+ this.logger = backendCore.Log.getLogger(`${services.getEntityName()} -> Export`);
352
+ }
353
+ async execute(input) {
354
+ this.logger.debug("Export action started", { input });
355
+ const result = await this.services.resolveExportCommand().execute(input);
356
+ this.logger.debug("Export action completed", { input });
357
+ return result;
358
+ }
359
+ }
388
360
 
389
- const WpEntity = (name, props = {}) => common.applyDecorators(common.SetMetadata(EntityManagerSymbols.Entity, {
390
- name,
391
- ...props,
392
- }));
361
+ class EntityGetAction {
362
+ constructor(services) {
363
+ this.services = services;
364
+ }
365
+ async execute(id) {
366
+ const entity = await this.services.resolveGetQuery().execute(id);
367
+ const converter = this.services.resolveConverter();
368
+ return entity
369
+ ? converter?.toEntityDto(entity) ?? entity
370
+ : undefined;
371
+ }
372
+ }
393
373
 
394
- const WpAppInitializer = (props = {}) => common.applyDecorators(common.Injectable(), common.SetMetadata(EntityManagerSymbols.AppInitializer, props));
374
+ class EntitiesImportAction {
375
+ constructor(services) {
376
+ this.services = services;
377
+ this.logger = backendCore.Log.getLogger(`${services.getEntityName()} -> Import`);
378
+ }
379
+ async execute(input) {
380
+ this.logger.debug("Import action started", { input });
381
+ const result = await this.services.resolveImportCommand().execute(input);
382
+ this.logger.debug("Import action completed", { input });
383
+ return result;
384
+ }
385
+ }
395
386
 
396
- const WpEntityRepository = (entityName, props = {}) => common.applyDecorators(common.Injectable(), common.SetMetadata(EntityManagerSymbols.EntityRepository, {
397
- entityName,
398
- ...props,
399
- }));
387
+ class EntitiesSampleDownloadAction {
388
+ constructor(services) {
389
+ this.services = services;
390
+ this.logger = backendCore.Log.getLogger(`${services.getEntityName()} -> Import`);
391
+ }
392
+ async execute(input) {
393
+ this.logger.debug("Sample download action started", { input });
394
+ const result = await this.services
395
+ .resolveSampleDownloadCommand()
396
+ .execute(input);
397
+ this.logger.debug("Sample download action completed", { input });
398
+ return result;
399
+ }
400
+ }
400
401
 
401
- const WpEntityManager = (entityName, props = {}) => common.applyDecorators(common.Injectable(), common.SetMetadata(EntityManagerSymbols.EntityManager, {
402
- entityName,
403
- ...props,
404
- }));
402
+ class EntitiesSearchAction {
403
+ constructor(services) {
404
+ this.services = services;
405
+ }
406
+ async execute(request) {
407
+ const results = await this.services
408
+ .resolveSearchQuery()
409
+ .execute(request);
410
+ const converter = this.services.resolveConverter();
411
+ return {
412
+ facets: results.facets,
413
+ paging: results.paging,
414
+ request: results.request,
415
+ items: results.items.map((x) => (converter?.toListItemDto(x) ?? x)),
416
+ };
417
+ }
418
+ }
405
419
 
406
- const WpEntityQueryBuilder = (entityName, props = {}) => common.applyDecorators(common.Injectable(), common.SetMetadata(EntityManagerSymbols.EntityQueryBuilder, {
407
- entityName,
408
- ...props,
409
- }));
420
+ class EntityUpdateAction {
421
+ constructor(services) {
422
+ this.services = services;
423
+ this.logger = backendCore.Log.getLogger(`${services.getEntityName()} -> Update`);
424
+ }
425
+ async execute(id, input) {
426
+ this.logger.debug("Update action started", { id, input });
427
+ const converter = this.services.resolveConverter();
428
+ const updateInput = converter?.updateDtoToEntity(input) ?? input;
429
+ const entity = await this.services
430
+ .resolveUpdateCommand()
431
+ .execute(id, updateInput);
432
+ const result = converter?.toEntityDto(entity) ?? entity;
433
+ this.logger.debug("Update action started", { id, input, result });
434
+ return result;
435
+ }
436
+ }
410
437
 
411
- const WpPipeline = (name, props = {}) => common.applyDecorators(common.Injectable(), common.SetMetadata(EntityManagerSymbols.PipelineTemplate, {
412
- name,
413
- ...props,
414
- }));
438
+ class EntityUpsertAction {
439
+ constructor(services) {
440
+ this.services = services;
441
+ this.logger = backendCore.Log.getLogger(`${services.getEntityName()} -> Upsert`);
442
+ }
443
+ async execute(id, input) {
444
+ this.logger.debug("Upsert action started", { id, input });
445
+ const converter = this.services.resolveConverter();
446
+ const updateInput = converter?.updateDtoToEntity(input) ?? input;
447
+ const entity = await this.services
448
+ .resolveUpsertCommand()
449
+ .execute(id, updateInput);
450
+ const result = converter?.toEntityDto(entity) ?? entity;
451
+ this.logger.debug("Upsert action started", { id, input, result });
452
+ return result;
453
+ }
454
+ }
415
455
 
416
- const WpEntitySeeder = (entityName, props = {}) => common.applyDecorators(common.Injectable(), common.SetMetadata(EntityManagerSymbols.EntitySeeder, {
417
- entityName,
418
- ...props,
419
- }));
420
-
421
- const WpEntitySerializer = (entityName, props = {}) => common.applyDecorators(common.Injectable(), common.SetMetadata(EntityManagerSymbols.EntitySerializer, {
422
- entityName,
423
- ...props,
424
- }));
425
-
426
- const WpEventsTracker = (props = {}) => common.applyDecorators(common.Injectable(), common.SetMetadata(EntityManagerSymbols.EventsTracker, {
427
- ...props,
428
- }));
429
-
430
- /******************************************************************************
431
- Copyright (c) Microsoft Corporation.
432
-
433
- Permission to use, copy, modify, and/or distribute this software for any
434
- purpose with or without fee is hereby granted.
435
-
436
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
437
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
438
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
439
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
440
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
441
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
442
- PERFORMANCE OF THIS SOFTWARE.
443
- ***************************************************************************** */
444
-
445
- function __decorate(decorators, target, key, desc) {
446
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
447
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
448
- 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;
449
- return c > 3 && r && Object.defineProperty(target, key, r), r;
450
- }
451
-
452
- function __metadata(metadataKey, metadataValue) {
453
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
454
- }
455
-
456
- typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
457
- var e = new Error(message);
458
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
459
- };
460
-
461
- class NumericFacetItem {
462
- }
463
- __decorate([
464
- swagger.ApiProperty(),
465
- __metadata("design:type", Number)
466
- ], NumericFacetItem.prototype, "value", void 0);
467
- __decorate([
468
- swagger.ApiProperty({ required: false }),
469
- __metadata("design:type", String)
470
- ], NumericFacetItem.prototype, "name", void 0);
471
- __decorate([
472
- swagger.ApiProperty({ required: false }),
473
- __metadata("design:type", Number)
474
- ], NumericFacetItem.prototype, "count", void 0);
475
- class NumericFacet {
476
- }
477
- __decorate([
478
- swagger.ApiProperty({ type: [NumericFacetItem] }),
479
- __metadata("design:type", Array)
480
- ], NumericFacet.prototype, "items", void 0);
481
- class BooleanFacetItem {
482
- }
483
- __decorate([
484
- swagger.ApiProperty(),
485
- __metadata("design:type", Boolean)
486
- ], BooleanFacetItem.prototype, "value", void 0);
487
- __decorate([
488
- swagger.ApiProperty({ required: false }),
489
- __metadata("design:type", String)
490
- ], BooleanFacetItem.prototype, "name", void 0);
491
- __decorate([
492
- swagger.ApiProperty({ required: false }),
493
- __metadata("design:type", Number)
494
- ], BooleanFacetItem.prototype, "count", void 0);
495
- class BooleanFacet {
496
- }
497
- __decorate([
498
- swagger.ApiProperty({ type: [BooleanFacetItem] }),
499
- __metadata("design:type", Array)
500
- ], BooleanFacet.prototype, "items", void 0);
501
- class StringFacetItem {
502
- }
503
- __decorate([
504
- swagger.ApiProperty(),
505
- __metadata("design:type", String)
506
- ], StringFacetItem.prototype, "value", void 0);
507
- __decorate([
508
- swagger.ApiProperty({ required: false }),
509
- __metadata("design:type", String)
510
- ], StringFacetItem.prototype, "name", void 0);
511
- __decorate([
512
- swagger.ApiProperty({ required: false }),
513
- __metadata("design:type", Number)
514
- ], StringFacetItem.prototype, "count", void 0);
515
- class StringFacet {
516
- }
517
- __decorate([
518
- swagger.ApiProperty({ type: [StringFacetItem] }),
519
- __metadata("design:type", Array)
520
- ], StringFacet.prototype, "items", void 0);
521
-
522
- const AuthenticationExtensionSymbols = {
523
- UserService: Symbol.for("WP.EXT:AUTHENTICATION.USER_SERVICE"),
524
- RolesService: Symbol.for("WP.EXT:AUTHENTICATION.ROLES_SERVICE"),
525
- UserRolesService: Symbol.for("WP.EXT:AUTHENTICATION.USER_ROLES_SERVICE"),
526
- };
527
- const AuthenticationGuardsSymbols = {
528
- Authenticated: "guard:authenticated",
529
- Public: "guard:public",
530
- Roles: "guard:roles",
531
- MemberOf: "guard:memberOf",
532
- };
533
-
534
- const Public = () => common.SetMetadata(AuthenticationGuardsSymbols.Public, true);
535
- const Authenticated = () => common.SetMetadata(AuthenticationGuardsSymbols.Authenticated, true);
536
- const Roles = (...roles) => common.SetMetadata(AuthenticationGuardsSymbols.Roles, roles);
537
- const MemberOf = (...groups) => common.SetMetadata(AuthenticationGuardsSymbols.MemberOf, groups);
538
- const buildRolesGuard = ({ mainRole, inheritedRoles, }, options) => Roles(mainRole.uid, ...(options?.inheritRoles && inheritedRoles
539
- ? inheritedRoles.map((role) => role.uid)
540
- : []));
541
-
542
- const WpRolesService = () => common.applyDecorators(common.Injectable(), common.SetMetadata(AuthenticationExtensionSymbols.RolesService, true));
543
-
544
- const WpUserService = () => common.applyDecorators(common.Injectable(), common.SetMetadata(AuthenticationExtensionSymbols.UserService, true));
545
-
546
- const WpUserRolesService = () => common.applyDecorators(common.Injectable(), common.SetMetadata(AuthenticationExtensionSymbols.UserRolesService, true));
547
-
548
- const AuthenticationEmailTemplates = {
549
- Registration: "registration",
550
- PasswordReset: "passwordReset",
551
- EmailVerify: "emailVerify",
552
- };
553
-
554
- class AuthenticationError extends Error {
555
- constructor(message) {
556
- super(message);
557
- this.name = "AuthenticationError";
456
+ class EntityCreateCommand {
457
+ constructor(services) {
458
+ this.services = services;
558
459
  }
559
- }
560
- class InvalidCredentialsError extends AuthenticationError {
561
- constructor(message) {
562
- super(message);
563
- this.name = "InvalidCredentialsError";
460
+ async execute(input) {
461
+ var entity = this.adaptEntity(input);
462
+ await this.authorize(entity);
463
+ var createdItem = await this.services.resolveRepository().create(entity);
464
+ await this.services
465
+ .resolveEventsManager()
466
+ .processEntityCreatedEvent(createdItem);
467
+ return createdItem;
564
468
  }
565
- }
566
- class OperationTokenMismatchError extends AuthenticationError {
567
- constructor(message) {
568
- super(message);
569
- this.name = "OperationTokenMismatchError";
469
+ adaptEntity(input) {
470
+ const adapter = this.services.resolveAdapter();
471
+ return adapter
472
+ ? adapter.createDataToEntity(input)
473
+ : input;
474
+ }
475
+ async authorize(entity) {
476
+ const authorization = this.services.resolveAuthorizationMiddleware();
477
+ if (!authorization) {
478
+ return;
479
+ }
480
+ const contextService = this.services.resolveAuthenticationContextProvider();
481
+ const context = await contextService?.getContext();
482
+ if (!context) {
483
+ return;
484
+ }
485
+ const authorizationResult = await authorization.canCreate(entity, context);
486
+ if (!authorizationResult.isAuthorized)
487
+ throw new EntityOperationUnauthorizedException(exports.EntityOperationType.Create, this.services.getEntityName(), entity);
570
488
  }
571
489
  }
572
490
 
573
- const AUTHENTICATION_EVENTS_NAMESPACE = "authentication";
574
- const AuthenticationEvents = {
575
- UserLogin: `${AUTHENTICATION_EVENTS_NAMESPACE}:user.login`,
576
- UserRegistrationStarted: `${AUTHENTICATION_EVENTS_NAMESPACE}:user.registrationStarted`,
577
- UserRegistrationCompleted: `${AUTHENTICATION_EVENTS_NAMESPACE}:user.registrationCompleted`,
578
- UserPasswordResetStarted: `${AUTHENTICATION_EVENTS_NAMESPACE}:user.passwordResetStarted`,
579
- UserPasswordResetCompleted: `${AUTHENTICATION_EVENTS_NAMESPACE}:user.passwordResetCompleted`,
580
- };
581
-
582
- exports.AuthGuard = class AuthGuard {
583
- constructor(reflector) {
584
- this.reflector = reflector;
491
+ class EntityDeleteCommand {
492
+ constructor(services) {
493
+ this.services = services;
585
494
  }
586
- canActivate(context) {
587
- const isPublic = this.getIsPublic(context);
588
- if (isPublic) {
589
- return true;
495
+ async execute(id) {
496
+ if (backendCore.isNullOrUndefined(id)) {
497
+ throw new MissingEntityIdError();
590
498
  }
591
- const auth = this.getCurrentAuth(context);
592
- const allowedRoles = this.getAllowedRoles(context);
593
- if (allowedRoles) {
594
- return this.isRoleMatching(allowedRoles, auth?.roles ?? []);
499
+ await this.authorize(id);
500
+ await this.services.resolveRepository().delete(id);
501
+ await this.services.resolveEventsManager().processEntityDeletedEvent(id);
502
+ }
503
+ async authorize(id) {
504
+ const authorization = this.services.resolveAuthorizationMiddleware();
505
+ if (!authorization) {
506
+ return;
595
507
  }
596
- const isForAllAuthenticated = this.getIsForAllAuthenticated(context);
597
- if (isForAllAuthenticated) {
598
- return !!auth?.user;
508
+ const entity = await this.services.resolveRepository().get(id);
509
+ if (entity == null) {
510
+ throw new EntityNotFoundException(id);
599
511
  }
600
- return false;
512
+ const contextService = this.services.resolveAuthenticationContextProvider();
513
+ const context = await contextService?.getContext();
514
+ if (!context) {
515
+ return;
516
+ }
517
+ const authorizationResult = await authorization.canDelete(entity, context);
518
+ if (!authorizationResult.isAuthorized)
519
+ throw new EntityOperationUnauthorizedException(exports.EntityOperationType.Delete, this.services.getEntityName(), entity);
601
520
  }
602
- isRoleMatching(allowedRoles, userRoles) {
603
- return userRoles.some((role) => allowedRoles.includes(role.uid));
521
+ }
522
+
523
+ class EntitiesDeleteCommand {
524
+ constructor(services) {
525
+ this.services = services;
604
526
  }
605
- getIsForAllAuthenticated(context) {
606
- return this.getMetadata(AuthenticationGuardsSymbols.Authenticated, context);
527
+ async execute(params) {
528
+ await this.authorize();
529
+ const context = await this.getContext();
530
+ const deleteResult = await this.services
531
+ .resolveQueryBuilder()
532
+ .delete(params.filters, context);
533
+ // todo: add entities deleted event
534
+ return deleteResult;
607
535
  }
608
- getIsPublic(context) {
609
- return this.getMetadata(AuthenticationGuardsSymbols.Public, context);
536
+ async getContext() {
537
+ const authorization = this.services.resolveAuthorizationMiddleware();
538
+ if (!authorization) {
539
+ return undefined;
540
+ }
541
+ const contextService = this.services.resolveAuthenticationContextProvider();
542
+ return await contextService.getContext();
610
543
  }
611
- getAllowedRoles(context) {
612
- return this.getMetadata(AuthenticationGuardsSymbols.Roles, context);
613
- }
614
- getCurrentAuth(context) {
615
- const request = context.switchToHttp()?.getRequest();
616
- return request?.auth?.user
617
- ? {
618
- user: request.auth.user,
619
- roles: request.auth.roles,
620
- }
621
- : undefined;
622
- }
623
- getMetadata(symbol, context) {
624
- return this.reflector.getAllAndOverride(symbol, [
625
- context.getHandler(),
626
- context.getClass(),
627
- ]);
544
+ async authorize() {
545
+ const authorization = this.services.resolveAuthorizationMiddleware();
546
+ if (!authorization) {
547
+ return;
548
+ }
549
+ const contextService = this.services.resolveAuthenticationContextProvider();
550
+ const context = await contextService?.getContext();
551
+ if (!context) {
552
+ return;
553
+ }
554
+ const authorizationResult = await authorization.canDeleteItems(context);
555
+ if (!authorizationResult.isAuthorized)
556
+ throw new EntityOperationUnauthorizedException(exports.EntityOperationType.Delete, this.services.getEntityName());
628
557
  }
629
- };
630
- exports.AuthGuard = __decorate([
631
- common.Injectable(),
632
- __metadata("design:paramtypes", [core.Reflector])
633
- ], exports.AuthGuard);
634
-
635
- exports.UserCreationError = void 0;
636
- (function (UserCreationError) {
637
- UserCreationError["UserAlreadyExists"] = "userAlreadyExists";
638
- })(exports.UserCreationError || (exports.UserCreationError = {}));
639
-
640
- const sessionStorage = new async_hooks.AsyncLocalStorage();
558
+ }
641
559
 
642
- exports.AppSessionService = class AppSessionService {
643
- getValue(key) {
644
- return this.getSession().get(key);
645
- }
646
- setValue(key, value) {
647
- this.getSession().set(key, value);
648
- }
649
- clearValue(key) {
650
- this.getSession().set(key, undefined);
560
+ const createDayPath = (d) => `${d.getFullYear()}/${(d.getMonth() + 1).toString().padStart(2, "0")}/${d
561
+ .getDate()
562
+ .toString()
563
+ .padStart(2, "0")}`;
564
+ class EntitiesExportCommand {
565
+ constructor(services, settings) {
566
+ this.services = services;
567
+ this.settings = settings;
651
568
  }
652
- getRequest() {
653
- return this.getSession().request;
569
+ async execute(input) {
570
+ const exportEntities = await this.getExportEntities(input.filter);
571
+ const outputFile = await this.buildExportFile(exportEntities.items, input.options.format);
572
+ const downloadUrl = await this.uploadExportFile(outputFile);
573
+ return {
574
+ downloadUrl,
575
+ file: {
576
+ content: outputFile.content,
577
+ contentType: outputFile.contentType,
578
+ name: outputFile.fileName,
579
+ },
580
+ };
654
581
  }
655
- getSession() {
656
- const store = sessionStorage.getStore();
657
- if (!store) {
658
- throw new Error("No active context found");
659
- }
660
- return store;
582
+ async buildExportFile(data, format) {
583
+ return await this.services.resolveSerializer().serialize(data, format);
661
584
  }
662
- };
663
- exports.AppSessionService = __decorate([
664
- common.Injectable()
665
- ], exports.AppSessionService);
666
-
667
- exports.AppHashingService = class AppHashingService {
668
- async hash(value, salt) {
669
- return await bcrypt.hash(value, salt);
585
+ async uploadExportFile(file) {
586
+ await this.bucket.fileUpload({
587
+ bucket: this.settings.exportBucket.bucket,
588
+ filePath: this.buildAbsoluteBucketPath(file.fileName),
589
+ content: file.content,
590
+ contentType: file.contentType,
591
+ });
592
+ return await this.bucket.filePublicUrlCreate({
593
+ bucket: this.settings.exportBucket.bucket,
594
+ expirationMinutes: this.settings.exportBucket.publicLinksExpirationMinutes,
595
+ filePath: this.buildAbsoluteBucketPath(file.fileName),
596
+ });
670
597
  }
671
- async compare(hash, value, salt) {
672
- return (await this.hash(value, salt)) === hash;
598
+ buildAbsoluteBucketPath(relativePath) {
599
+ return `${this.settings.exportBucket.rootFolderPath ?? ""}/exports/${createDayPath(new Date())}/${relativePath}`;
673
600
  }
674
- };
675
- exports.AppHashingService = __decorate([
676
- common.Injectable()
677
- ], exports.AppHashingService);
678
-
679
- class EntitiesCountAction {
680
- constructor(services) {
681
- this.services = services;
601
+ async getExportEntities(filters) {
602
+ return this.services.resolveSearchQuery().execute(filters ?? {});
682
603
  }
683
- async execute(filters) {
684
- return await this.services.resolveCountQuery().execute(filters);
604
+ get bucket() {
605
+ return this.services.getRootServices().resolveBucketProvider();
685
606
  }
686
607
  }
687
608
 
688
- class EntityCreateAction {
689
- constructor(services) {
609
+ class EntitiesImportCommand {
610
+ constructor(services, settings) {
690
611
  this.services = services;
691
- this.logger = backendCore.Log.getLogger(`${services.getEntityName()} -> Create`);
612
+ this.settings = settings;
692
613
  }
693
614
  async execute(input) {
694
- this.logger.debug("Create action started", { input });
695
- const converter = this.services.resolveConverter();
696
- const createInput = converter?.createDtoToEntity(input) ?? input;
697
- const entity = await this.services
698
- .resolveCreateCommand()
699
- .execute(createInput);
700
- const result = converter?.toEntityDto(entity) ?? entity;
701
- this.logger.debug("Create action completed", { input, result });
702
- return result;
703
- }
704
- }
705
-
706
- class EntityDeleteAction {
707
- constructor(services) {
708
- this.services = services;
709
- this.logger = backendCore.Log.getLogger(`${services.getEntityName()} -> Delete`);
615
+ await this.uploadImportFile({
616
+ content: input.file.content,
617
+ contentType: input.file.contentType,
618
+ fileName: input.file.fileName,
619
+ });
620
+ const importEntities = await this.parseImportFile(input.file.content, input.format);
621
+ for (const entry of importEntities) {
622
+ await this.importEntity(entry);
623
+ }
624
+ return {
625
+ statistics: {
626
+ importedCount: importEntities.length,
627
+ createdCount: 0,
628
+ unchangedCount: 0,
629
+ updatedCount: 0,
630
+ },
631
+ };
710
632
  }
711
- async execute(id) {
712
- this.logger.debug("Delete action started", { id });
713
- await this.services.resolveDeleteCommand().execute(id);
714
- this.logger.debug("Delete action completed", { id });
633
+ async importEntity(entry) {
634
+ try {
635
+ if (!entry.id) {
636
+ return this.services.resolveCreateCommand().execute(entry.item);
637
+ }
638
+ return this.services.resolveUpsertCommand().execute(entry.id, entry.item);
639
+ }
640
+ catch (error) {
641
+ throw new Error(`Error importing entry with id ${entry.id}`);
642
+ }
715
643
  }
716
- }
717
-
718
- class EntitiesDeleteAction {
719
- constructor(services) {
720
- this.services = services;
721
- this.logger = backendCore.Log.getLogger(`${services.getEntityName()} -> DeleteItems`);
644
+ async parseImportFile(content, format) {
645
+ return await this.services.resolveSerializer().parse(content, format);
722
646
  }
723
- async execute(params) {
724
- this.logger.debug("DeleteItems action started");
725
- await this.services.resolveDeleteItemsCommand().execute(params);
726
- this.logger.debug("DeleteItems action completed");
647
+ async uploadImportFile(file) {
648
+ await this.bucket.fileUpload({
649
+ bucket: this.settings.exportBucket.bucket,
650
+ filePath: this.buildAbsoluteBucketPath(file.fileName),
651
+ content: file.content,
652
+ contentType: file.contentType,
653
+ });
727
654
  }
728
- }
729
-
730
- class EntityExistsAction {
731
- constructor(services) {
732
- this.services = services;
655
+ buildAbsoluteBucketPath(relativePath) {
656
+ return `${this.settings.exportBucket.rootFolderPath ?? ""}/imports/${createDayPath(new Date())}/${relativePath}`;
733
657
  }
734
- async execute(filters) {
735
- return await this.services.resolveExistsQuery().execute(filters);
658
+ get bucket() {
659
+ return this.services.getRootServices().resolveBucketProvider();
736
660
  }
737
661
  }
738
662
 
739
- class EntitiesExportAction {
740
- constructor(services) {
663
+ class EntitiesSampleDownloadCommand {
664
+ constructor(services, settings) {
741
665
  this.services = services;
742
- this.logger = backendCore.Log.getLogger(`${services.getEntityName()} -> Export`);
666
+ this.settings = settings;
743
667
  }
744
668
  async execute(input) {
745
- this.logger.debug("Export action started", { input });
746
- const result = await this.services.resolveExportCommand().execute(input);
747
- this.logger.debug("Export action completed", { input });
748
- return result;
669
+ const sample = await this.services
670
+ .resolveSerializer()
671
+ .createSample(input.format);
672
+ const downloadUrl = await this.uploadSampleFile(sample);
673
+ return {
674
+ file: {
675
+ content: sample.content,
676
+ contentType: sample.contentType,
677
+ name: sample.fileName,
678
+ },
679
+ downloadUrl,
680
+ };
749
681
  }
750
- }
751
-
752
- class EntityGetAction {
753
- constructor(services) {
754
- this.services = services;
682
+ async uploadSampleFile(file) {
683
+ await this.bucket.fileUpload({
684
+ bucket: this.settings.exportBucket.bucket,
685
+ filePath: this.buildAbsoluteBucketPath(file.fileName),
686
+ content: file.content,
687
+ contentType: file.contentType,
688
+ });
689
+ return await this.bucket.filePublicUrlCreate({
690
+ bucket: this.settings.exportBucket.bucket,
691
+ expirationMinutes: this.settings.exportBucket.publicLinksExpirationMinutes,
692
+ filePath: this.buildAbsoluteBucketPath(file.fileName),
693
+ });
755
694
  }
756
- async execute(id) {
757
- const entity = await this.services.resolveGetQuery().execute(id);
758
- const converter = this.services.resolveConverter();
759
- return entity
760
- ? converter?.toEntityDto(entity) ?? entity
761
- : undefined;
695
+ buildAbsoluteBucketPath(relativePath) {
696
+ return `${this.settings.exportBucket.rootFolderPath ?? ""}/samples/${createDayPath(new Date())}/${relativePath}`;
697
+ }
698
+ get bucket() {
699
+ return this.services.getRootServices().resolveBucketProvider();
762
700
  }
763
701
  }
764
702
 
765
- class EntitiesImportAction {
703
+ class EntityUpdateCommand {
766
704
  constructor(services) {
767
705
  this.services = services;
768
- this.logger = backendCore.Log.getLogger(`${services.getEntityName()} -> Import`);
769
- }
770
- async execute(input) {
771
- this.logger.debug("Import action started", { input });
772
- const result = await this.services.resolveImportCommand().execute(input);
773
- this.logger.debug("Import action completed", { input });
774
- return result;
775
- }
776
- }
777
-
778
- class EntitiesSampleDownloadAction {
779
- constructor(services) {
780
- this.services = services;
781
- this.logger = backendCore.Log.getLogger(`${services.getEntityName()} -> Import`);
782
- }
783
- async execute(input) {
784
- this.logger.debug("Sample download action started", { input });
785
- const result = await this.services
786
- .resolveSampleDownloadCommand()
787
- .execute(input);
788
- this.logger.debug("Sample download action completed", { input });
789
- return result;
790
- }
791
- }
792
-
793
- class EntitiesSearchAction {
794
- constructor(services) {
795
- this.services = services;
796
- }
797
- async execute(request) {
798
- const results = await this.services
799
- .resolveSearchQuery()
800
- .execute(request);
801
- const converter = this.services.resolveConverter();
802
- return {
803
- facets: results.facets,
804
- paging: results.paging,
805
- request: results.request,
806
- items: results.items.map((x) => (converter?.toListItemDto(x) ?? x)),
807
- };
808
- }
809
- }
810
-
811
- class EntityUpdateAction {
812
- constructor(services) {
813
- this.services = services;
814
- this.logger = backendCore.Log.getLogger(`${services.getEntityName()} -> Update`);
815
- }
816
- async execute(id, input) {
817
- this.logger.debug("Update action started", { id, input });
818
- const converter = this.services.resolveConverter();
819
- const updateInput = converter?.updateDtoToEntity(input) ?? input;
820
- const entity = await this.services
821
- .resolveUpdateCommand()
822
- .execute(id, updateInput);
823
- const result = converter?.toEntityDto(entity) ?? entity;
824
- this.logger.debug("Update action started", { id, input, result });
825
- return result;
826
- }
827
- }
828
-
829
- class EntityUpsertAction {
830
- constructor(services) {
831
- this.services = services;
832
- this.logger = backendCore.Log.getLogger(`${services.getEntityName()} -> Upsert`);
833
706
  }
834
707
  async execute(id, input) {
835
- this.logger.debug("Upsert action started", { id, input });
836
- const converter = this.services.resolveConverter();
837
- const updateInput = converter?.updateDtoToEntity(input) ?? input;
838
- const entity = await this.services
839
- .resolveUpsertCommand()
840
- .execute(id, updateInput);
841
- const result = converter?.toEntityDto(entity) ?? entity;
842
- this.logger.debug("Upsert action started", { id, input, result });
843
- return result;
844
- }
845
- }
846
-
847
- class EntityCreateCommand {
848
- constructor(services) {
849
- this.services = services;
850
- }
851
- async execute(input) {
852
- var entity = this.adaptEntity(input);
853
- await this.authorize(entity);
854
- var createdItem = await this.services.resolveRepository().create(entity);
708
+ const entity = this.adaptEntity(input);
709
+ await this.authorize(id);
710
+ const updatedEntity = await this.services
711
+ .resolveRepository()
712
+ .update(id, entity);
855
713
  await this.services
856
714
  .resolveEventsManager()
857
- .processEntityCreatedEvent(createdItem);
858
- return createdItem;
715
+ .processEntityUpdatedEvent(updatedEntity);
716
+ return updatedEntity;
859
717
  }
860
718
  adaptEntity(input) {
861
719
  const adapter = this.services.resolveAdapter();
862
720
  return adapter
863
- ? adapter.createDataToEntity(input)
721
+ ? adapter.updateDataToEntity(input)
864
722
  : input;
865
723
  }
866
- async authorize(entity) {
724
+ async authorize(id) {
867
725
  const authorization = this.services.resolveAuthorizationMiddleware();
868
726
  if (!authorization) {
869
727
  return;
870
728
  }
729
+ const currentEntity = await this.services.resolveRepository().get(id);
730
+ if (currentEntity == null) {
731
+ throw new EntityNotFoundException();
732
+ }
871
733
  const contextService = this.services.resolveAuthenticationContextProvider();
872
734
  const context = await contextService?.getContext();
873
735
  if (!context) {
874
736
  return;
875
737
  }
876
- const authorizationResult = await authorization.canCreate(entity, context);
738
+ const authorizationResult = await authorization.canUpdate(currentEntity, context);
877
739
  if (!authorizationResult.isAuthorized)
878
- throw new EntityOperationUnauthorizedException(exports.EntityOperationType.Create, this.services.getEntityName(), entity);
740
+ throw new EntityOperationUnauthorizedException(exports.EntityOperationType.Create, this.services.getEntityName(), currentEntity);
879
741
  }
880
742
  }
881
743
 
882
- class EntityDeleteCommand {
744
+ class EntityUpsertCommand {
883
745
  constructor(services) {
884
746
  this.services = services;
885
747
  }
886
- async execute(id) {
887
- if (backendCore.isNullOrUndefined(id)) {
888
- throw new MissingEntityIdError();
889
- }
890
- await this.authorize(id);
891
- await this.services.resolveRepository().delete(id);
892
- await this.services.resolveEventsManager().processEntityDeletedEvent(id);
748
+ async execute(id, data) {
749
+ const entity = this.adaptEntity(data);
750
+ await this.authorize(id, entity);
751
+ const updatedEntity = await this.upsertEntity(id, entity);
752
+ await this.services
753
+ .resolveEventsManager()
754
+ .processEntityUpdatedEvent(updatedEntity);
755
+ return updatedEntity;
893
756
  }
894
- async authorize(id) {
757
+ async upsertEntity(id, entity) {
758
+ return await this.services.resolveRepository().upsert(id, entity);
759
+ }
760
+ adaptEntity(input) {
761
+ const adapter = this.services.resolveAdapter();
762
+ return adapter
763
+ ? adapter.updateDataToEntity(input)
764
+ : input;
765
+ }
766
+ async authorize(id, entity) {
895
767
  const authorization = this.services.resolveAuthorizationMiddleware();
896
768
  if (!authorization) {
897
769
  return;
898
770
  }
899
- const entity = await this.services.resolveRepository().get(id);
900
- if (entity == null) {
901
- throw new EntityNotFoundException(id);
902
- }
771
+ const currentEntity = await this.services.resolveRepository().get(id);
903
772
  const contextService = this.services.resolveAuthenticationContextProvider();
904
773
  const context = await contextService?.getContext();
905
774
  if (!context) {
906
775
  return;
907
776
  }
908
- const authorizationResult = await authorization.canDelete(entity, context);
777
+ if (currentEntity) {
778
+ const updateResult = await authorization.canUpdate(currentEntity, context);
779
+ if (!updateResult.isAuthorized)
780
+ throw new EntityOperationUnauthorizedException(exports.EntityOperationType.Update, this.services.getEntityName(), currentEntity);
781
+ return;
782
+ }
783
+ const authorizationResult = await authorization.canCreate(entity, context);
909
784
  if (!authorizationResult.isAuthorized)
910
- throw new EntityOperationUnauthorizedException(exports.EntityOperationType.Delete, this.services.getEntityName(), entity);
785
+ throw new EntityOperationUnauthorizedException(exports.EntityOperationType.Create, this.services.getEntityName(), entity);
911
786
  }
912
787
  }
913
788
 
914
- class EntitiesDeleteCommand {
789
+ class EntityManager {
915
790
  constructor(services) {
916
791
  this.services = services;
917
792
  }
918
- async execute(params) {
919
- await this.authorize();
920
- const context = await this.getContext();
921
- const deleteResult = await this.services
922
- .resolveQueryBuilder()
923
- .delete(params.filters, context);
924
- // todo: add entities deleted event
925
- return deleteResult;
793
+ get exists() {
794
+ return this.services.resolveExistsQuery();
926
795
  }
927
- async getContext() {
928
- const authorization = this.services.resolveAuthorizationMiddleware();
929
- if (!authorization) {
930
- return undefined;
931
- }
932
- const contextService = this.services.resolveAuthenticationContextProvider();
933
- return await contextService.getContext();
796
+ get count() {
797
+ return this.services.resolveCountQuery();
934
798
  }
935
- async authorize() {
936
- const authorization = this.services.resolveAuthorizationMiddleware();
937
- if (!authorization) {
938
- return;
939
- }
940
- const contextService = this.services.resolveAuthenticationContextProvider();
941
- const context = await contextService?.getContext();
942
- if (!context) {
943
- return;
944
- }
945
- const authorizationResult = await authorization.canDeleteItems(context);
946
- if (!authorizationResult.isAuthorized)
947
- throw new EntityOperationUnauthorizedException(exports.EntityOperationType.Delete, this.services.getEntityName());
799
+ get deleteItems() {
800
+ return this.services.resolveDeleteItemsCommand();
948
801
  }
949
- }
950
-
951
- const createDayPath = (d) => `${d.getFullYear()}/${(d.getMonth() + 1).toString().padStart(2, "0")}/${d
952
- .getDate()
953
- .toString()
954
- .padStart(2, "0")}`;
955
- class EntitiesExportCommand {
956
- constructor(services, settings) {
957
- this.services = services;
958
- this.settings = settings;
802
+ get get() {
803
+ return this.services.resolveGetQuery();
959
804
  }
960
- async execute(input) {
961
- const exportEntities = await this.getExportEntities(input.filter);
962
- const outputFile = await this.buildExportFile(exportEntities.items, input.options.format);
963
- const downloadUrl = await this.uploadExportFile(outputFile);
964
- return {
965
- downloadUrl,
966
- file: {
967
- content: outputFile.content,
968
- contentType: outputFile.contentType,
969
- name: outputFile.fileName,
970
- },
971
- };
805
+ get search() {
806
+ return this.services.resolveSearchQuery();
972
807
  }
973
- async buildExportFile(data, format) {
974
- return await this.services.resolveSerializer().serialize(data, format);
808
+ get create() {
809
+ return this.services.resolveCreateCommand();
975
810
  }
976
- async uploadExportFile(file) {
977
- await this.bucket.fileUpload({
978
- bucket: this.settings.exportBucket.bucket,
979
- filePath: this.buildAbsoluteBucketPath(file.fileName),
980
- content: file.content,
981
- contentType: file.contentType,
982
- });
983
- return await this.bucket.filePublicUrlCreate({
984
- bucket: this.settings.exportBucket.bucket,
985
- expirationMinutes: this.settings.exportBucket.publicLinksExpirationMinutes,
986
- filePath: this.buildAbsoluteBucketPath(file.fileName),
987
- });
811
+ get update() {
812
+ return this.services.resolveUpdateCommand();
988
813
  }
989
- buildAbsoluteBucketPath(relativePath) {
990
- return `${this.settings.exportBucket.rootFolderPath ?? ""}/exports/${createDayPath(new Date())}/${relativePath}`;
814
+ get upsert() {
815
+ return this.services.resolveUpsertCommand();
991
816
  }
992
- async getExportEntities(filters) {
993
- return this.services.resolveSearchQuery().execute(filters ?? {});
817
+ get delete() {
818
+ return this.services.resolveDeleteCommand();
994
819
  }
995
- get bucket() {
996
- return this.services.getRootServices().resolveBucketProvider();
820
+ get export() {
821
+ return this.services.resolveExportCommand();
822
+ }
823
+ get import() {
824
+ return this.services.resolveImportCommand();
825
+ }
826
+ get sampleDownload() {
827
+ return this.services.resolveSampleDownloadCommand();
997
828
  }
998
829
  }
999
-
1000
- class EntitiesImportCommand {
1001
- constructor(services, settings) {
1002
- this.services = services;
1003
- this.settings = settings;
1004
- }
1005
- async execute(input) {
1006
- await this.uploadImportFile({
1007
- content: input.file.content,
1008
- contentType: input.file.contentType,
1009
- fileName: input.file.fileName,
1010
- });
1011
- const importEntities = await this.parseImportFile(input.file.content, input.format);
1012
- for (const entry of importEntities) {
1013
- await this.importEntity(entry);
1014
- }
1015
- return {
1016
- statistics: {
1017
- importedCount: importEntities.length,
1018
- createdCount: 0,
1019
- unchangedCount: 0,
1020
- updatedCount: 0,
1021
- },
1022
- };
1023
- }
1024
- async importEntity(entry) {
1025
- try {
1026
- if (!entry.id) {
1027
- return this.services.resolveCreateCommand().execute(entry.item);
1028
- }
1029
- return this.services.resolveUpsertCommand().execute(entry.id, entry.item);
1030
- }
1031
- catch (error) {
1032
- throw new Error(`Error importing entry with id ${entry.id}`);
1033
- }
1034
- }
1035
- async parseImportFile(content, format) {
1036
- return await this.services.resolveSerializer().parse(content, format);
1037
- }
1038
- async uploadImportFile(file) {
1039
- await this.bucket.fileUpload({
1040
- bucket: this.settings.exportBucket.bucket,
1041
- filePath: this.buildAbsoluteBucketPath(file.fileName),
1042
- content: file.content,
1043
- contentType: file.contentType,
1044
- });
1045
- }
1046
- buildAbsoluteBucketPath(relativePath) {
1047
- return `${this.settings.exportBucket.rootFolderPath ?? ""}/imports/${createDayPath(new Date())}/${relativePath}`;
1048
- }
1049
- get bucket() {
1050
- return this.services.getRootServices().resolveBucketProvider();
1051
- }
1052
- }
1053
-
1054
- class EntitiesSampleDownloadCommand {
1055
- constructor(services, settings) {
1056
- this.services = services;
1057
- this.settings = settings;
1058
- }
1059
- async execute(input) {
1060
- const sample = await this.services
1061
- .resolveSerializer()
1062
- .createSample(input.format);
1063
- const downloadUrl = await this.uploadSampleFile(sample);
1064
- return {
1065
- file: {
1066
- content: sample.content,
1067
- contentType: sample.contentType,
1068
- name: sample.fileName,
1069
- },
1070
- downloadUrl,
1071
- };
1072
- }
1073
- async uploadSampleFile(file) {
1074
- await this.bucket.fileUpload({
1075
- bucket: this.settings.exportBucket.bucket,
1076
- filePath: this.buildAbsoluteBucketPath(file.fileName),
1077
- content: file.content,
1078
- contentType: file.contentType,
1079
- });
1080
- return await this.bucket.filePublicUrlCreate({
1081
- bucket: this.settings.exportBucket.bucket,
1082
- expirationMinutes: this.settings.exportBucket.publicLinksExpirationMinutes,
1083
- filePath: this.buildAbsoluteBucketPath(file.fileName),
1084
- });
1085
- }
1086
- buildAbsoluteBucketPath(relativePath) {
1087
- return `${this.settings.exportBucket.rootFolderPath ?? ""}/samples/${createDayPath(new Date())}/${relativePath}`;
1088
- }
1089
- get bucket() {
1090
- return this.services.getRootServices().resolveBucketProvider();
1091
- }
1092
- }
1093
-
1094
- class EntityUpdateCommand {
1095
- constructor(services) {
1096
- this.services = services;
1097
- }
1098
- async execute(id, input) {
1099
- const entity = this.adaptEntity(input);
1100
- await this.authorize(id);
1101
- const updatedEntity = await this.services
1102
- .resolveRepository()
1103
- .update(id, entity);
1104
- await this.services
1105
- .resolveEventsManager()
1106
- .processEntityUpdatedEvent(updatedEntity);
1107
- return updatedEntity;
1108
- }
1109
- adaptEntity(input) {
1110
- const adapter = this.services.resolveAdapter();
1111
- return adapter
1112
- ? adapter.updateDataToEntity(input)
1113
- : input;
1114
- }
1115
- async authorize(id) {
1116
- const authorization = this.services.resolveAuthorizationMiddleware();
1117
- if (!authorization) {
1118
- return;
1119
- }
1120
- const currentEntity = await this.services.resolveRepository().get(id);
1121
- if (currentEntity == null) {
1122
- throw new EntityNotFoundException();
1123
- }
1124
- const contextService = this.services.resolveAuthenticationContextProvider();
1125
- const context = await contextService?.getContext();
1126
- if (!context) {
1127
- return;
1128
- }
1129
- const authorizationResult = await authorization.canUpdate(currentEntity, context);
1130
- if (!authorizationResult.isAuthorized)
1131
- throw new EntityOperationUnauthorizedException(exports.EntityOperationType.Create, this.services.getEntityName(), currentEntity);
1132
- }
1133
- }
1134
-
1135
- class EntityUpsertCommand {
1136
- constructor(services) {
1137
- this.services = services;
1138
- }
1139
- async execute(id, data) {
1140
- const entity = this.adaptEntity(data);
1141
- await this.authorize(id, entity);
1142
- const updatedEntity = await this.upsertEntity(id, entity);
1143
- await this.services
1144
- .resolveEventsManager()
1145
- .processEntityUpdatedEvent(updatedEntity);
1146
- return updatedEntity;
1147
- }
1148
- async upsertEntity(id, entity) {
1149
- return await this.services.resolveRepository().upsert(id, entity);
1150
- }
1151
- adaptEntity(input) {
1152
- const adapter = this.services.resolveAdapter();
1153
- return adapter
1154
- ? adapter.updateDataToEntity(input)
1155
- : input;
1156
- }
1157
- async authorize(id, entity) {
1158
- const authorization = this.services.resolveAuthorizationMiddleware();
1159
- if (!authorization) {
1160
- return;
1161
- }
1162
- const currentEntity = await this.services.resolveRepository().get(id);
1163
- const contextService = this.services.resolveAuthenticationContextProvider();
1164
- const context = await contextService?.getContext();
1165
- if (!context) {
1166
- return;
1167
- }
1168
- if (currentEntity) {
1169
- const updateResult = await authorization.canUpdate(currentEntity, context);
1170
- if (!updateResult.isAuthorized)
1171
- throw new EntityOperationUnauthorizedException(exports.EntityOperationType.Update, this.services.getEntityName(), currentEntity);
1172
- return;
1173
- }
1174
- const authorizationResult = await authorization.canCreate(entity, context);
1175
- if (!authorizationResult.isAuthorized)
1176
- throw new EntityOperationUnauthorizedException(exports.EntityOperationType.Create, this.services.getEntityName(), entity);
1177
- }
1178
- }
1179
-
1180
- class EntityManager {
1181
- constructor(services) {
1182
- this.services = services;
1183
- }
1184
- get exists() {
1185
- return this.services.resolveExistsQuery();
1186
- }
1187
- get count() {
1188
- return this.services.resolveCountQuery();
1189
- }
1190
- get deleteItems() {
1191
- return this.services.resolveDeleteItemsCommand();
1192
- }
1193
- get get() {
1194
- return this.services.resolveGetQuery();
1195
- }
1196
- get search() {
1197
- return this.services.resolveSearchQuery();
1198
- }
1199
- get create() {
1200
- return this.services.resolveCreateCommand();
1201
- }
1202
- get update() {
1203
- return this.services.resolveUpdateCommand();
1204
- }
1205
- get upsert() {
1206
- return this.services.resolveUpsertCommand();
1207
- }
1208
- get delete() {
1209
- return this.services.resolveDeleteCommand();
1210
- }
1211
- get export() {
1212
- return this.services.resolveExportCommand();
1213
- }
1214
- get import() {
1215
- return this.services.resolveImportCommand();
1216
- }
1217
- get sampleDownload() {
1218
- return this.services.resolveSampleDownloadCommand();
1219
- }
1220
- }
1221
- class EntityActions {
1222
- constructor(services) {
830
+ class EntityActions {
831
+ constructor(services) {
1223
832
  this.services = services;
1224
833
  }
1225
834
  get exists() {
@@ -2146,139 +1755,539 @@ class ReplicasConfiguration {
2146
1755
  }
2147
1756
  }
2148
1757
 
2149
- class EntityManagerServiceRoot {
2150
- constructor() {
2151
- this.services = new ServiceLocator();
2152
- }
2153
- get locator() {
2154
- return this.services;
2155
- }
2156
- getEntitiesServicesLocator() {
2157
- return new EntitiesServiceLocator(this.services);
2158
- }
2159
- getEntityServicesLocator(entityName) {
2160
- return new EntityServiceLocator(this.getEntitiesServicesLocator(), entityName);
2161
- }
2162
- addAuthentication({ provider }) {
2163
- this.getEntitiesServicesLocator().registerAuthenticationContextProvider(provider);
2164
- }
2165
- registerEntity(entityName, repository) {
2166
- const collection = new EntityManagerServiceCollection(entityName, this.getEntitiesServicesLocator());
2167
- const services = this.getEntityServicesLocator(entityName);
2168
- collection.locator.registerEntityManager(entityName, new EntityManager(services));
2169
- collection.locator.registerEntityActions(entityName, new EntityActions(services));
2170
- collection.locator.registerRepository(entityName, repository);
2171
- const replicaManager = new EntityReplicaManager(services);
2172
- collection.locator.registerReplicaSyncManager(entityName, replicaManager);
2173
- collection.locator.registerReplicaDeleteManager(entityName, replicaManager);
2174
- collection.locator.registerReplicaConfiguration(entityName, new ReplicasConfiguration());
2175
- const connectorsManager = new EntityConnectorsManager(services);
2176
- collection.locator.registerConnectorSyncManager(entityName, connectorsManager);
2177
- collection.locator.registerConnectorDeleteManager(entityName, connectorsManager);
2178
- collection.locator.registerConnectorsConfiguration(entityName, new ConnectorsConfiguration());
2179
- collection.locator.registerEventsManager(entityName, new EntityEventsManager(entityName, services));
2180
- return collection;
1758
+ class EntityManagerServiceRoot {
1759
+ constructor() {
1760
+ this.services = new ServiceLocator();
1761
+ }
1762
+ get locator() {
1763
+ return this.services;
1764
+ }
1765
+ getEntitiesServicesLocator() {
1766
+ return new EntitiesServiceLocator(this.services);
1767
+ }
1768
+ getEntityServicesLocator(entityName) {
1769
+ return new EntityServiceLocator(this.getEntitiesServicesLocator(), entityName);
1770
+ }
1771
+ addAuthentication({ provider }) {
1772
+ this.getEntitiesServicesLocator().registerAuthenticationContextProvider(provider);
1773
+ }
1774
+ registerEntity(entityName, repository) {
1775
+ const collection = new EntityManagerServiceCollection(entityName, this.getEntitiesServicesLocator());
1776
+ const services = this.getEntityServicesLocator(entityName);
1777
+ collection.locator.registerEntityManager(entityName, new EntityManager(services));
1778
+ collection.locator.registerEntityActions(entityName, new EntityActions(services));
1779
+ collection.locator.registerRepository(entityName, repository);
1780
+ const replicaManager = new EntityReplicaManager(services);
1781
+ collection.locator.registerReplicaSyncManager(entityName, replicaManager);
1782
+ collection.locator.registerReplicaDeleteManager(entityName, replicaManager);
1783
+ collection.locator.registerReplicaConfiguration(entityName, new ReplicasConfiguration());
1784
+ const connectorsManager = new EntityConnectorsManager(services);
1785
+ collection.locator.registerConnectorSyncManager(entityName, connectorsManager);
1786
+ collection.locator.registerConnectorDeleteManager(entityName, connectorsManager);
1787
+ collection.locator.registerConnectorsConfiguration(entityName, new ConnectorsConfiguration());
1788
+ collection.locator.registerEventsManager(entityName, new EntityEventsManager(entityName, services));
1789
+ return collection;
1790
+ }
1791
+ }
1792
+ class EntityManagerServiceCollection {
1793
+ constructor(entityName, locator) {
1794
+ this.entityName = entityName;
1795
+ this.locator = locator;
1796
+ this.replicas = new ReplicasConfiguration();
1797
+ this.connectors = new ConnectorsConfiguration();
1798
+ this.resolver = new EntityServiceLocator(locator, entityName);
1799
+ }
1800
+ getServiceLocator() {
1801
+ return this.resolver;
1802
+ }
1803
+ mapCrudOperations({ queryBuilder, settings, }) {
1804
+ this.mapGet();
1805
+ this.mapCount();
1806
+ this.mapExists();
1807
+ this.mapSearch({
1808
+ queryBuilder,
1809
+ });
1810
+ this.mapCreate();
1811
+ this.mapUpdate();
1812
+ this.mapDelete();
1813
+ this.mapImportExport(settings.importExport);
1814
+ return this;
1815
+ }
1816
+ mapGet() {
1817
+ this.locator.registerGetQuery(this.entityName, new EntityGetQuery(this.resolver));
1818
+ this.locator.registerGetAction(this.entityName, new EntityGetAction(this.resolver));
1819
+ return this;
1820
+ }
1821
+ mapCount() {
1822
+ this.locator.registerCountQuery(this.entityName, new EntitiesCountQuery(this.resolver));
1823
+ this.locator.registerCountAction(this.entityName, new EntitiesCountAction(this.resolver));
1824
+ return this;
1825
+ }
1826
+ mapExists() {
1827
+ this.locator.registerExistsQuery(this.entityName, new EntityExistsQuery(this.resolver));
1828
+ this.locator.registerExistsAction(this.entityName, new EntityExistsAction(this.resolver));
1829
+ return this;
1830
+ }
1831
+ mapSearch({ queryBuilder, }) {
1832
+ this.locator.registerSearchQuery(this.entityName, new EntitiesSearchQuery(this.resolver));
1833
+ this.locator.registerSearchAction(this.entityName, new EntitiesSearchAction(this.resolver));
1834
+ this.locator.registerQueryBuilder(this.entityName, queryBuilder);
1835
+ return this;
1836
+ }
1837
+ mapCreate() {
1838
+ this.locator.registerCreateCommand(this.entityName, new EntityCreateCommand(this.resolver));
1839
+ this.locator.registerCreateAction(this.entityName, new EntityCreateAction(this.resolver));
1840
+ return this;
1841
+ }
1842
+ mapImportExport(settings) {
1843
+ this.locator.registerExportCommand(this.entityName, new EntitiesExportCommand(this.resolver, settings));
1844
+ this.locator.registerExportAction(this.entityName, new EntitiesExportAction(this.resolver));
1845
+ this.locator.registerImportCommand(this.entityName, new EntitiesImportCommand(this.resolver, settings));
1846
+ this.locator.registerImportAction(this.entityName, new EntitiesImportAction(this.resolver));
1847
+ this.locator.registerSampleDownloadCommand(this.entityName, new EntitiesSampleDownloadCommand(this.resolver, settings));
1848
+ this.locator.registerSampleDownloadAction(this.entityName, new EntitiesSampleDownloadAction(this.resolver));
1849
+ return this;
1850
+ }
1851
+ mapUpdate() {
1852
+ this.locator.registerUpsertCommand(this.entityName, new EntityUpsertCommand(this.resolver));
1853
+ this.locator.registerUpsertAction(this.entityName, new EntityUpsertAction(this.resolver));
1854
+ this.locator.registerUpdateCommand(this.entityName, new EntityUpdateCommand(this.resolver));
1855
+ this.locator.registerUpdateAction(this.entityName, new EntityUpdateAction(this.resolver));
1856
+ return this;
1857
+ }
1858
+ mapDelete() {
1859
+ this.locator.registerDeleteCommand(this.entityName, new EntityDeleteCommand(this.resolver));
1860
+ this.locator.registerDeleteAction(this.entityName, new EntityDeleteAction(this.resolver));
1861
+ this.locator.registerDeleteItemsCommand(this.entityName, new EntitiesDeleteCommand(this.resolver));
1862
+ this.locator.registerDeleteItemsAction(this.entityName, new EntitiesDeleteAction(this.resolver));
1863
+ return this;
1864
+ }
1865
+ addAdapter(adapter) {
1866
+ this.locator.registerAdapter(this.entityName, adapter);
1867
+ return this;
1868
+ }
1869
+ addSerializer(serializer) {
1870
+ this.locator.registerSerializer(this.entityName, serializer);
1871
+ return this;
1872
+ }
1873
+ addConverter(converter) {
1874
+ this.locator.registerConverter(this.entityName, converter);
1875
+ return this;
1876
+ }
1877
+ addAuthorization({ middleware, }) {
1878
+ this.locator.registerAuthorizationMiddleware(this.entityName, middleware);
1879
+ return this;
1880
+ }
1881
+ withReplica({ name, options, repository, }) {
1882
+ this.replicas.configureReplica(name, options, repository);
1883
+ return this;
1884
+ }
1885
+ withSynchronization({ name, options, connector, mapper, }) {
1886
+ this.connectors.configureConnector(name, options, connector, mapper);
1887
+ return this;
1888
+ }
1889
+ }
1890
+ const createContainer = () => new EntityManagerServiceRoot();
1891
+
1892
+ const toEntitiesImportInput = (request) => ({
1893
+ format: request.format,
1894
+ file: {
1895
+ content: request.file.buffer,
1896
+ contentType: request.file.mimetype,
1897
+ fileName: request.file.originalname,
1898
+ },
1899
+ });
1900
+
1901
+ const PLATFORM_EVENT_NAMESPACE = "platform";
1902
+ const PlatformEvents = {
1903
+ Messaging: {
1904
+ EmailSent: `${PLATFORM_EVENT_NAMESPACE}:messaging.emailSent`,
1905
+ },
1906
+ };
1907
+
1908
+ class NestEntityAuthorizationMiddleware {
1909
+ }
1910
+
1911
+ class NestEntityActions {
1912
+ // todo: resolve entity name from decorator
1913
+ constructor(entityName, registry) {
1914
+ this.services = registry.resolveEntityServicesCollection(entityName);
1915
+ }
1916
+ get manager() {
1917
+ if (!this.actionsInstance) {
1918
+ this.actionsInstance =
1919
+ this.services.resolveEntityActions();
1920
+ }
1921
+ return this.actionsInstance;
1922
+ }
1923
+ }
1924
+
1925
+ class NestEntityManager {
1926
+ // todo: resolve entity name from decorator
1927
+ constructor(entityName, registry) {
1928
+ this.services = registry.resolveEntityServicesCollection(entityName);
1929
+ }
1930
+ get manager() {
1931
+ if (!this.managerInstance) {
1932
+ this.managerInstance =
1933
+ this.services.resolveEntityManager();
1934
+ }
1935
+ return this.managerInstance;
1936
+ }
1937
+ }
1938
+
1939
+ class NestEntitySerializer extends EntitySerializer {
1940
+ constructor(entityName, registry) {
1941
+ super(entityName);
1942
+ // this.services = registry.resolveEntityServicesCollection(entityName)
1943
+ }
1944
+ }
1945
+
1946
+ const EntityManagerSymbols = {
1947
+ AppInitializer: Symbol.for("WP:APP_INITIALIZER"),
1948
+ EventsTracker: Symbol.for("WP:EVENTS_TRACKER"),
1949
+ Entity: Symbol.for("WP:ENTITY"),
1950
+ EntityActions: Symbol.for("WP:ENTITY_ACTIONS"),
1951
+ EntityAdapter: Symbol.for("WP:ENTITY_ADAPTER"),
1952
+ EntityAuthMiddleware: Symbol.for("WP:ENTITY_AUTH_MIDDLEWARE"),
1953
+ EntityRepository: Symbol.for("WP:ENTITY_REPOSITORY"),
1954
+ EntityConnector: Symbol.for("WP:ENTITY_CONNECTOR"),
1955
+ EntityConverter: Symbol.for("WP:ENTITY_CONVERTER"),
1956
+ EntitySerializer: Symbol.for("WP:ENTITY_SERIALIZER"),
1957
+ EntityManager: Symbol.for("WP:ENTITY_MANAGER"),
1958
+ EntityQueryBuilder: Symbol.for("WP:ENTITY_QUERY_BUILDER"),
1959
+ EntitySeeder: Symbol.for("WP:ENTITY_SEEDER"),
1960
+ EmailProvider: Symbol.for("WP:EMAIL_PROVIDER"),
1961
+ EmailTemplate: Symbol.for("WP:EMAIL_TEMPLATE"),
1962
+ BucketProvider: Symbol.for("WP:BUCKET_PROVIDER"),
1963
+ PipelineTemplate: Symbol.for("WP:PIPELINE_TEMPLATE"),
1964
+ };
1965
+
1966
+ const WpEntityAuthMiddleware = (entityName, props = {}) => common.applyDecorators(common.Injectable(), common.SetMetadata(EntityManagerSymbols.EntityAuthMiddleware, {
1967
+ entityName,
1968
+ ...props,
1969
+ }));
1970
+
1971
+ const WpBucketProvider = (providerId) => common.applyDecorators(common.Injectable(), common.SetMetadata(EntityManagerSymbols.BucketProvider, {
1972
+ providerId,
1973
+ }));
1974
+
1975
+ const WpEntityActions = (entityName, props = {}) => common.applyDecorators(common.Injectable(), common.SetMetadata(EntityManagerSymbols.EntityActions, {
1976
+ entityName,
1977
+ ...props,
1978
+ }));
1979
+
1980
+ const WpEntityAdapter = (entityName, props = {}) => common.applyDecorators(common.Injectable(), common.SetMetadata(EntityManagerSymbols.EntityAdapter, {
1981
+ entityName,
1982
+ ...props,
1983
+ }));
1984
+
1985
+ const WpEntityConnector = (entityName, props = {}) => common.applyDecorators(common.Injectable(), common.SetMetadata(EntityManagerSymbols.EntityConnector, {
1986
+ entityName,
1987
+ ...props,
1988
+ }));
1989
+
1990
+ const WpEntityConverter = (entityName, props = {}) => common.applyDecorators(common.Injectable(), common.SetMetadata(EntityManagerSymbols.EntityConverter, {
1991
+ entityName,
1992
+ ...props,
1993
+ }));
1994
+
1995
+ const WpEmailTemplate = (templateId) => common.applyDecorators(common.Injectable(), common.SetMetadata(EntityManagerSymbols.EmailTemplate, {
1996
+ templateId,
1997
+ }));
1998
+ const WpEmailProvider = (providerId) => common.applyDecorators(common.Injectable(), common.SetMetadata(EntityManagerSymbols.EmailProvider, {
1999
+ providerId,
2000
+ }));
2001
+
2002
+ const WpEntity = (name, props = {}) => common.applyDecorators(common.SetMetadata(EntityManagerSymbols.Entity, {
2003
+ name,
2004
+ ...props,
2005
+ }));
2006
+
2007
+ const WpAppInitializer = (props = {}) => common.applyDecorators(common.Injectable(), common.SetMetadata(EntityManagerSymbols.AppInitializer, props));
2008
+
2009
+ const WpEntityRepository = (entityName, props = {}) => common.applyDecorators(common.Injectable(), common.SetMetadata(EntityManagerSymbols.EntityRepository, {
2010
+ entityName,
2011
+ ...props,
2012
+ }));
2013
+
2014
+ const WpEntityManager = (entityName, props = {}) => common.applyDecorators(common.Injectable(), common.SetMetadata(EntityManagerSymbols.EntityManager, {
2015
+ entityName,
2016
+ ...props,
2017
+ }));
2018
+
2019
+ const WpEntityQueryBuilder = (entityName, props = {}) => common.applyDecorators(common.Injectable(), common.SetMetadata(EntityManagerSymbols.EntityQueryBuilder, {
2020
+ entityName,
2021
+ ...props,
2022
+ }));
2023
+
2024
+ const WpPipeline = (name, props = {}) => common.applyDecorators(common.Injectable(), common.SetMetadata(EntityManagerSymbols.PipelineTemplate, {
2025
+ name,
2026
+ ...props,
2027
+ }));
2028
+
2029
+ const WpEntitySeeder = (entityName, props = {}) => common.applyDecorators(common.Injectable(), common.SetMetadata(EntityManagerSymbols.EntitySeeder, {
2030
+ entityName,
2031
+ ...props,
2032
+ }));
2033
+
2034
+ const WpEntitySerializer = (entityName, props = {}) => common.applyDecorators(common.Injectable(), common.SetMetadata(EntityManagerSymbols.EntitySerializer, {
2035
+ entityName,
2036
+ ...props,
2037
+ }));
2038
+
2039
+ const WpEventsTracker = (props = {}) => common.applyDecorators(common.Injectable(), common.SetMetadata(EntityManagerSymbols.EventsTracker, {
2040
+ ...props,
2041
+ }));
2042
+
2043
+ /******************************************************************************
2044
+ Copyright (c) Microsoft Corporation.
2045
+
2046
+ Permission to use, copy, modify, and/or distribute this software for any
2047
+ purpose with or without fee is hereby granted.
2048
+
2049
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
2050
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
2051
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
2052
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
2053
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
2054
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
2055
+ PERFORMANCE OF THIS SOFTWARE.
2056
+ ***************************************************************************** */
2057
+
2058
+ function __decorate(decorators, target, key, desc) {
2059
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2060
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
2061
+ 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;
2062
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
2063
+ }
2064
+
2065
+ function __metadata(metadataKey, metadataValue) {
2066
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
2067
+ }
2068
+
2069
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
2070
+ var e = new Error(message);
2071
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
2072
+ };
2073
+
2074
+ class NumericFacetItem {
2075
+ }
2076
+ __decorate([
2077
+ swagger.ApiProperty(),
2078
+ __metadata("design:type", Number)
2079
+ ], NumericFacetItem.prototype, "value", void 0);
2080
+ __decorate([
2081
+ swagger.ApiProperty({ required: false }),
2082
+ __metadata("design:type", String)
2083
+ ], NumericFacetItem.prototype, "name", void 0);
2084
+ __decorate([
2085
+ swagger.ApiProperty({ required: false }),
2086
+ __metadata("design:type", Number)
2087
+ ], NumericFacetItem.prototype, "count", void 0);
2088
+ class NumericFacet {
2089
+ }
2090
+ __decorate([
2091
+ swagger.ApiProperty({ type: [NumericFacetItem] }),
2092
+ __metadata("design:type", Array)
2093
+ ], NumericFacet.prototype, "items", void 0);
2094
+ class BooleanFacetItem {
2095
+ }
2096
+ __decorate([
2097
+ swagger.ApiProperty(),
2098
+ __metadata("design:type", Boolean)
2099
+ ], BooleanFacetItem.prototype, "value", void 0);
2100
+ __decorate([
2101
+ swagger.ApiProperty({ required: false }),
2102
+ __metadata("design:type", String)
2103
+ ], BooleanFacetItem.prototype, "name", void 0);
2104
+ __decorate([
2105
+ swagger.ApiProperty({ required: false }),
2106
+ __metadata("design:type", Number)
2107
+ ], BooleanFacetItem.prototype, "count", void 0);
2108
+ class BooleanFacet {
2109
+ }
2110
+ __decorate([
2111
+ swagger.ApiProperty({ type: [BooleanFacetItem] }),
2112
+ __metadata("design:type", Array)
2113
+ ], BooleanFacet.prototype, "items", void 0);
2114
+ class StringFacetItem {
2115
+ }
2116
+ __decorate([
2117
+ swagger.ApiProperty(),
2118
+ __metadata("design:type", String)
2119
+ ], StringFacetItem.prototype, "value", void 0);
2120
+ __decorate([
2121
+ swagger.ApiProperty({ required: false }),
2122
+ __metadata("design:type", String)
2123
+ ], StringFacetItem.prototype, "name", void 0);
2124
+ __decorate([
2125
+ swagger.ApiProperty({ required: false }),
2126
+ __metadata("design:type", Number)
2127
+ ], StringFacetItem.prototype, "count", void 0);
2128
+ class StringFacet {
2129
+ }
2130
+ __decorate([
2131
+ swagger.ApiProperty({ type: [StringFacetItem] }),
2132
+ __metadata("design:type", Array)
2133
+ ], StringFacet.prototype, "items", void 0);
2134
+
2135
+ const AuthenticationExtensionSymbols = {
2136
+ UserService: Symbol.for("WP.EXT:AUTHENTICATION.USER_SERVICE"),
2137
+ RolesService: Symbol.for("WP.EXT:AUTHENTICATION.ROLES_SERVICE"),
2138
+ UserRolesService: Symbol.for("WP.EXT:AUTHENTICATION.USER_ROLES_SERVICE"),
2139
+ };
2140
+ const AuthenticationGuardsSymbols = {
2141
+ Authenticated: "guard:authenticated",
2142
+ Public: "guard:public",
2143
+ Roles: "guard:roles",
2144
+ MemberOf: "guard:memberOf",
2145
+ };
2146
+
2147
+ const Public = () => common.SetMetadata(AuthenticationGuardsSymbols.Public, true);
2148
+ const Authenticated = () => common.SetMetadata(AuthenticationGuardsSymbols.Authenticated, true);
2149
+ const Roles = (...roles) => common.SetMetadata(AuthenticationGuardsSymbols.Roles, roles);
2150
+ const MemberOf = (...groups) => common.SetMetadata(AuthenticationGuardsSymbols.MemberOf, groups);
2151
+ const buildRolesGuard = ({ mainRole, inheritedRoles, }, options) => Roles(mainRole.uid, ...(options?.inheritRoles && inheritedRoles
2152
+ ? inheritedRoles.map((role) => role.uid)
2153
+ : []));
2154
+
2155
+ const WpRolesService = () => common.applyDecorators(common.Injectable(), common.SetMetadata(AuthenticationExtensionSymbols.RolesService, true));
2156
+
2157
+ const WpUserService = () => common.applyDecorators(common.Injectable(), common.SetMetadata(AuthenticationExtensionSymbols.UserService, true));
2158
+
2159
+ const WpUserRolesService = () => common.applyDecorators(common.Injectable(), common.SetMetadata(AuthenticationExtensionSymbols.UserRolesService, true));
2160
+
2161
+ const AuthenticationEmailTemplates = {
2162
+ Registration: "registration",
2163
+ PasswordReset: "passwordReset",
2164
+ EmailVerify: "emailVerify",
2165
+ };
2166
+
2167
+ class AuthenticationError extends Error {
2168
+ constructor(message) {
2169
+ super(message);
2170
+ this.name = "AuthenticationError";
2181
2171
  }
2182
2172
  }
2183
- class EntityManagerServiceCollection {
2184
- constructor(entityName, locator) {
2185
- this.entityName = entityName;
2186
- this.locator = locator;
2187
- this.replicas = new ReplicasConfiguration();
2188
- this.connectors = new ConnectorsConfiguration();
2189
- this.resolver = new EntityServiceLocator(locator, entityName);
2173
+ class InvalidCredentialsError extends AuthenticationError {
2174
+ constructor(message) {
2175
+ super(message);
2176
+ this.name = "InvalidCredentialsError";
2190
2177
  }
2191
- getServiceLocator() {
2192
- return this.resolver;
2178
+ }
2179
+ class OperationTokenMismatchError extends AuthenticationError {
2180
+ constructor(message) {
2181
+ super(message);
2182
+ this.name = "OperationTokenMismatchError";
2193
2183
  }
2194
- mapCrudOperations({ queryBuilder, settings, }) {
2195
- this.mapGet();
2196
- this.mapCount();
2197
- this.mapExists();
2198
- this.mapSearch({
2199
- queryBuilder,
2200
- });
2201
- this.mapCreate();
2202
- this.mapUpdate();
2203
- this.mapDelete();
2204
- this.mapImportExport(settings.importExport);
2205
- return this;
2184
+ }
2185
+
2186
+ const AUTHENTICATION_EVENTS_NAMESPACE = "authentication";
2187
+ const AuthenticationEvents = {
2188
+ UserLogin: `${AUTHENTICATION_EVENTS_NAMESPACE}:user.login`,
2189
+ UserRegistrationStarted: `${AUTHENTICATION_EVENTS_NAMESPACE}:user.registrationStarted`,
2190
+ UserRegistrationCompleted: `${AUTHENTICATION_EVENTS_NAMESPACE}:user.registrationCompleted`,
2191
+ UserPasswordResetStarted: `${AUTHENTICATION_EVENTS_NAMESPACE}:user.passwordResetStarted`,
2192
+ UserPasswordResetCompleted: `${AUTHENTICATION_EVENTS_NAMESPACE}:user.passwordResetCompleted`,
2193
+ };
2194
+
2195
+ exports.AuthGuard = class AuthGuard {
2196
+ constructor(reflector) {
2197
+ this.reflector = reflector;
2206
2198
  }
2207
- mapGet() {
2208
- this.locator.registerGetQuery(this.entityName, new EntityGetQuery(this.resolver));
2209
- this.locator.registerGetAction(this.entityName, new EntityGetAction(this.resolver));
2210
- return this;
2199
+ canActivate(context) {
2200
+ const isPublic = this.getIsPublic(context);
2201
+ if (isPublic) {
2202
+ return true;
2203
+ }
2204
+ const auth = this.getCurrentAuth(context);
2205
+ const allowedRoles = this.getAllowedRoles(context);
2206
+ if (allowedRoles) {
2207
+ return this.isRoleMatching(allowedRoles, auth?.roles ?? []);
2208
+ }
2209
+ const isForAllAuthenticated = this.getIsForAllAuthenticated(context);
2210
+ if (isForAllAuthenticated) {
2211
+ return !!auth?.user;
2212
+ }
2213
+ return false;
2211
2214
  }
2212
- mapCount() {
2213
- this.locator.registerCountQuery(this.entityName, new EntitiesCountQuery(this.resolver));
2214
- this.locator.registerCountAction(this.entityName, new EntitiesCountAction(this.resolver));
2215
- return this;
2215
+ isRoleMatching(allowedRoles, userRoles) {
2216
+ return userRoles.some((role) => allowedRoles.includes(role.uid));
2216
2217
  }
2217
- mapExists() {
2218
- this.locator.registerExistsQuery(this.entityName, new EntityExistsQuery(this.resolver));
2219
- this.locator.registerExistsAction(this.entityName, new EntityExistsAction(this.resolver));
2220
- return this;
2218
+ getIsForAllAuthenticated(context) {
2219
+ return this.getMetadata(AuthenticationGuardsSymbols.Authenticated, context);
2221
2220
  }
2222
- mapSearch({ queryBuilder, }) {
2223
- this.locator.registerSearchQuery(this.entityName, new EntitiesSearchQuery(this.resolver));
2224
- this.locator.registerSearchAction(this.entityName, new EntitiesSearchAction(this.resolver));
2225
- this.locator.registerQueryBuilder(this.entityName, queryBuilder);
2226
- return this;
2221
+ getIsPublic(context) {
2222
+ return this.getMetadata(AuthenticationGuardsSymbols.Public, context);
2227
2223
  }
2228
- mapCreate() {
2229
- this.locator.registerCreateCommand(this.entityName, new EntityCreateCommand(this.resolver));
2230
- this.locator.registerCreateAction(this.entityName, new EntityCreateAction(this.resolver));
2231
- return this;
2224
+ getAllowedRoles(context) {
2225
+ return this.getMetadata(AuthenticationGuardsSymbols.Roles, context);
2232
2226
  }
2233
- mapImportExport(settings) {
2234
- this.locator.registerExportCommand(this.entityName, new EntitiesExportCommand(this.resolver, settings));
2235
- this.locator.registerExportAction(this.entityName, new EntitiesExportAction(this.resolver));
2236
- this.locator.registerImportCommand(this.entityName, new EntitiesImportCommand(this.resolver, settings));
2237
- this.locator.registerImportAction(this.entityName, new EntitiesImportAction(this.resolver));
2238
- this.locator.registerSampleDownloadCommand(this.entityName, new EntitiesSampleDownloadCommand(this.resolver, settings));
2239
- this.locator.registerSampleDownloadAction(this.entityName, new EntitiesSampleDownloadAction(this.resolver));
2240
- return this;
2227
+ getCurrentAuth(context) {
2228
+ const request = context.switchToHttp()?.getRequest();
2229
+ return request?.auth?.user
2230
+ ? {
2231
+ user: request.auth.user,
2232
+ roles: request.auth.roles,
2233
+ }
2234
+ : undefined;
2241
2235
  }
2242
- mapUpdate() {
2243
- this.locator.registerUpsertCommand(this.entityName, new EntityUpsertCommand(this.resolver));
2244
- this.locator.registerUpsertAction(this.entityName, new EntityUpsertAction(this.resolver));
2245
- this.locator.registerUpdateCommand(this.entityName, new EntityUpdateCommand(this.resolver));
2246
- this.locator.registerUpdateAction(this.entityName, new EntityUpdateAction(this.resolver));
2247
- return this;
2236
+ getMetadata(symbol, context) {
2237
+ return this.reflector.getAllAndOverride(symbol, [
2238
+ context.getHandler(),
2239
+ context.getClass(),
2240
+ ]);
2248
2241
  }
2249
- mapDelete() {
2250
- this.locator.registerDeleteCommand(this.entityName, new EntityDeleteCommand(this.resolver));
2251
- this.locator.registerDeleteAction(this.entityName, new EntityDeleteAction(this.resolver));
2252
- this.locator.registerDeleteItemsCommand(this.entityName, new EntitiesDeleteCommand(this.resolver));
2253
- this.locator.registerDeleteItemsAction(this.entityName, new EntitiesDeleteAction(this.resolver));
2254
- return this;
2242
+ };
2243
+ exports.AuthGuard = __decorate([
2244
+ common.Injectable(),
2245
+ __metadata("design:paramtypes", [core.Reflector])
2246
+ ], exports.AuthGuard);
2247
+
2248
+ exports.UserCreationError = void 0;
2249
+ (function (UserCreationError) {
2250
+ UserCreationError["UserAlreadyExists"] = "userAlreadyExists";
2251
+ })(exports.UserCreationError || (exports.UserCreationError = {}));
2252
+
2253
+ const sessionStorage = new async_hooks.AsyncLocalStorage();
2254
+
2255
+ exports.AppSessionService = class AppSessionService {
2256
+ getValue(key) {
2257
+ return this.getSession().get(key);
2255
2258
  }
2256
- addAdapter(adapter) {
2257
- this.locator.registerAdapter(this.entityName, adapter);
2258
- return this;
2259
+ setValue(key, value) {
2260
+ this.getSession().set(key, value);
2259
2261
  }
2260
- addSerializer(serializer) {
2261
- this.locator.registerSerializer(this.entityName, serializer);
2262
- return this;
2262
+ clearValue(key) {
2263
+ this.getSession().set(key, undefined);
2263
2264
  }
2264
- addConverter(converter) {
2265
- this.locator.registerConverter(this.entityName, converter);
2266
- return this;
2265
+ getRequest() {
2266
+ return this.getSession().request;
2267
2267
  }
2268
- addAuthorization({ middleware, }) {
2269
- this.locator.registerAuthorizationMiddleware(this.entityName, middleware);
2270
- return this;
2268
+ getSession() {
2269
+ const store = sessionStorage.getStore();
2270
+ if (!store) {
2271
+ throw new Error("No active context found");
2272
+ }
2273
+ return store;
2271
2274
  }
2272
- withReplica({ name, options, repository, }) {
2273
- this.replicas.configureReplica(name, options, repository);
2274
- return this;
2275
+ };
2276
+ exports.AppSessionService = __decorate([
2277
+ common.Injectable()
2278
+ ], exports.AppSessionService);
2279
+
2280
+ exports.AppHashingService = class AppHashingService {
2281
+ async hash(value, salt) {
2282
+ return await bcrypt.hash(value, salt);
2275
2283
  }
2276
- withSynchronization({ name, options, connector, mapper, }) {
2277
- this.connectors.configureConnector(name, options, connector, mapper);
2278
- return this;
2284
+ async compare(hash, value, salt) {
2285
+ return (await this.hash(value, salt)) === hash;
2279
2286
  }
2280
- }
2281
- const createContainer = () => new EntityManagerServiceRoot();
2287
+ };
2288
+ exports.AppHashingService = __decorate([
2289
+ common.Injectable()
2290
+ ], exports.AppHashingService);
2282
2291
 
2283
2292
  exports.EntityManagerRegistry = class EntityManagerRegistry {
2284
2293
  constructor() {
@@ -27352,8 +27361,10 @@ exports.WpSendgridEmailTemplate = WpSendgridEmailTemplate;
27352
27361
  exports.WpUserRolesService = WpUserRolesService;
27353
27362
  exports.WpUserService = WpUserService;
27354
27363
  exports.buildRolesGuard = buildRolesGuard;
27364
+ exports.createContainer = createContainer;
27355
27365
  exports.createExpressFileResponse = createExpressFileResponse;
27356
27366
  exports.getLocalizedText = getLocalizedText;
27357
27367
  exports.newUuid = newUuid;
27358
27368
  exports.renderHandlebarsTemplate = renderHandlebarsTemplate;
27369
+ exports.toEntitiesImportInput = toEntitiesImportInput;
27359
27370
  //# sourceMappingURL=index.js.map