@punks/backend-entity-manager 0.0.259 → 0.0.261

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.
Files changed (40) hide show
  1. package/dist/cjs/index.js +310 -9
  2. package/dist/cjs/index.js.map +1 -1
  3. package/dist/cjs/types/abstractions/index.d.ts +1 -0
  4. package/dist/cjs/types/abstractions/operations.d.ts +23 -0
  5. package/dist/cjs/types/platforms/nest/__test__/server/database/core/entities/appOperationLockItem.entity.d.ts +7 -0
  6. package/dist/cjs/types/platforms/nest/__test__/server/database/core/index.d.ts +4 -0
  7. package/dist/cjs/types/platforms/nest/__test__/server/database/core/repositories/appOperationLock.repository.d.ts +6 -0
  8. package/dist/cjs/types/platforms/nest/__test__/server/database/core/repositories.d.ts +2 -1
  9. package/dist/cjs/types/platforms/nest/ioc/index.d.ts +1 -0
  10. package/dist/cjs/types/platforms/nest/ioc/tokens/builder.d.ts +1 -0
  11. package/dist/cjs/types/platforms/nest/ioc/tokens/index.d.ts +2 -0
  12. package/dist/cjs/types/platforms/nest/ioc/tokens/symbols.d.ts +4 -0
  13. package/dist/cjs/types/platforms/nest/services/index.d.ts +1 -0
  14. package/dist/cjs/types/platforms/nest/services/operations/index.d.ts +2 -0
  15. package/dist/cjs/types/platforms/nest/services/operations/operation-lock.repository.d.ts +16 -0
  16. package/dist/cjs/types/platforms/nest/services/operations/operation-lock.service.d.ts +9 -0
  17. package/dist/cjs/types/platforms/nest/services/operations/operation-lock.service.spec.d.ts +1 -0
  18. package/dist/cjs/types/platforms/nest/services/operations/types.d.ts +12 -0
  19. package/dist/cjs/types/platforms/nest/services/providers.d.ts +2 -1
  20. package/dist/esm/index.js +310 -12
  21. package/dist/esm/index.js.map +1 -1
  22. package/dist/esm/types/abstractions/index.d.ts +1 -0
  23. package/dist/esm/types/abstractions/operations.d.ts +23 -0
  24. package/dist/esm/types/platforms/nest/__test__/server/database/core/entities/appOperationLockItem.entity.d.ts +7 -0
  25. package/dist/esm/types/platforms/nest/__test__/server/database/core/index.d.ts +4 -0
  26. package/dist/esm/types/platforms/nest/__test__/server/database/core/repositories/appOperationLock.repository.d.ts +6 -0
  27. package/dist/esm/types/platforms/nest/__test__/server/database/core/repositories.d.ts +2 -1
  28. package/dist/esm/types/platforms/nest/ioc/index.d.ts +1 -0
  29. package/dist/esm/types/platforms/nest/ioc/tokens/builder.d.ts +1 -0
  30. package/dist/esm/types/platforms/nest/ioc/tokens/index.d.ts +2 -0
  31. package/dist/esm/types/platforms/nest/ioc/tokens/symbols.d.ts +4 -0
  32. package/dist/esm/types/platforms/nest/services/index.d.ts +1 -0
  33. package/dist/esm/types/platforms/nest/services/operations/index.d.ts +2 -0
  34. package/dist/esm/types/platforms/nest/services/operations/operation-lock.repository.d.ts +16 -0
  35. package/dist/esm/types/platforms/nest/services/operations/operation-lock.service.d.ts +9 -0
  36. package/dist/esm/types/platforms/nest/services/operations/operation-lock.service.spec.d.ts +1 -0
  37. package/dist/esm/types/platforms/nest/services/operations/types.d.ts +12 -0
  38. package/dist/esm/types/platforms/nest/services/providers.d.ts +2 -1
  39. package/dist/index.d.ts +65 -2
  40. package/package.json +2 -2
package/dist/cjs/index.js CHANGED
@@ -126,6 +126,9 @@ class MissingEntityIdError extends EntityManagerException {
126
126
  }
127
127
  }
128
128
 
129
+ class LockNotFoundError extends Error {
130
+ }
131
+
129
132
  exports.ReplicationMode = void 0;
130
133
  (function (ReplicationMode) {
131
134
  ReplicationMode[ReplicationMode["Sync"] = 0] = "Sync";
@@ -3804,6 +3807,10 @@ function __decorate(decorators, target, key, desc) {
3804
3807
  return c > 3 && r && Object.defineProperty(target, key, r), r;
3805
3808
  }
3806
3809
 
3810
+ function __param(paramIndex, decorator) {
3811
+ return function (target, key) { decorator(target, key, paramIndex); }
3812
+ }
3813
+
3807
3814
  function __metadata(metadataKey, metadataValue) {
3808
3815
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
3809
3816
  }
@@ -21544,6 +21551,15 @@ exports.CustomDiscoveryModule = __decorate([
21544
21551
  })
21545
21552
  ], exports.CustomDiscoveryModule);
21546
21553
 
21554
+ const LIB_DI_TOKEN_NAMESPACE = "WP";
21555
+ const buildProviderToken = (name) => `${LIB_DI_TOKEN_NAMESPACE}.PROVIDER.${name}`;
21556
+
21557
+ const EntityManagerProviderToken = {
21558
+ OperationsLockRepository: {},
21559
+ };
21560
+ const toSnakeUpperCase = (str) => lodash.exports.trimStart(str.replace(/([A-Z])/g, (match) => `_${match}`).toUpperCase(), "_");
21561
+ const getEntityManagerProviderToken = (name) => buildProviderToken(toSnakeUpperCase(name));
21562
+
21547
21563
  exports.EntityManagerService = class EntityManagerService {
21548
21564
  constructor(registry) {
21549
21565
  this.registry = registry;
@@ -21685,6 +21701,271 @@ exports.MediaLibraryService = __decorate([
21685
21701
  __metadata("design:paramtypes", [exports.EntityManagerRegistry])
21686
21702
  ], exports.MediaLibraryService);
21687
21703
 
21704
+ function _typeof(obj) {
21705
+ "@babel/helpers - typeof";
21706
+
21707
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
21708
+ return typeof obj;
21709
+ } : function (obj) {
21710
+ return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
21711
+ }, _typeof(obj);
21712
+ }
21713
+
21714
+ function requiredArgs(required, args) {
21715
+ if (args.length < required) {
21716
+ throw new TypeError(required + ' argument' + (required > 1 ? 's' : '') + ' required, but only ' + args.length + ' present');
21717
+ }
21718
+ }
21719
+
21720
+ /**
21721
+ * @name toDate
21722
+ * @category Common Helpers
21723
+ * @summary Convert the given argument to an instance of Date.
21724
+ *
21725
+ * @description
21726
+ * Convert the given argument to an instance of Date.
21727
+ *
21728
+ * If the argument is an instance of Date, the function returns its clone.
21729
+ *
21730
+ * If the argument is a number, it is treated as a timestamp.
21731
+ *
21732
+ * If the argument is none of the above, the function returns Invalid Date.
21733
+ *
21734
+ * **Note**: *all* Date arguments passed to any *date-fns* function is processed by `toDate`.
21735
+ *
21736
+ * @param {Date|Number} argument - the value to convert
21737
+ * @returns {Date} the parsed date in the local time zone
21738
+ * @throws {TypeError} 1 argument required
21739
+ *
21740
+ * @example
21741
+ * // Clone the date:
21742
+ * const result = toDate(new Date(2014, 1, 11, 11, 30, 30))
21743
+ * //=> Tue Feb 11 2014 11:30:30
21744
+ *
21745
+ * @example
21746
+ * // Convert the timestamp to date:
21747
+ * const result = toDate(1392098430000)
21748
+ * //=> Tue Feb 11 2014 11:30:30
21749
+ */
21750
+ function toDate(argument) {
21751
+ requiredArgs(1, arguments);
21752
+ var argStr = Object.prototype.toString.call(argument);
21753
+
21754
+ // Clone the date
21755
+ if (argument instanceof Date || _typeof(argument) === 'object' && argStr === '[object Date]') {
21756
+ // Prevent the date to lose the milliseconds when passed to new Date() in IE10
21757
+ return new Date(argument.getTime());
21758
+ } else if (typeof argument === 'number' || argStr === '[object Number]') {
21759
+ return new Date(argument);
21760
+ } else {
21761
+ if ((typeof argument === 'string' || argStr === '[object String]') && typeof console !== 'undefined') {
21762
+ // eslint-disable-next-line no-console
21763
+ console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use `parseISO` to parse strings. See: https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#string-arguments");
21764
+ // eslint-disable-next-line no-console
21765
+ console.warn(new Error().stack);
21766
+ }
21767
+ return new Date(NaN);
21768
+ }
21769
+ }
21770
+
21771
+ /**
21772
+ * Days in 1 week.
21773
+ *
21774
+ * @name daysInWeek
21775
+ * @constant
21776
+ * @type {number}
21777
+ * @default
21778
+ */
21779
+
21780
+ /**
21781
+ * Milliseconds in 1 minute
21782
+ *
21783
+ * @name millisecondsInMinute
21784
+ * @constant
21785
+ * @type {number}
21786
+ * @default
21787
+ */
21788
+ var millisecondsInMinute = 60000;
21789
+
21790
+ /**
21791
+ * @name differenceInMilliseconds
21792
+ * @category Millisecond Helpers
21793
+ * @summary Get the number of milliseconds between the given dates.
21794
+ *
21795
+ * @description
21796
+ * Get the number of milliseconds between the given dates.
21797
+ *
21798
+ * @param {Date|Number} dateLeft - the later date
21799
+ * @param {Date|Number} dateRight - the earlier date
21800
+ * @returns {Number} the number of milliseconds
21801
+ * @throws {TypeError} 2 arguments required
21802
+ *
21803
+ * @example
21804
+ * // How many milliseconds are between
21805
+ * // 2 July 2014 12:30:20.600 and 2 July 2014 12:30:21.700?
21806
+ * const result = differenceInMilliseconds(
21807
+ * new Date(2014, 6, 2, 12, 30, 21, 700),
21808
+ * new Date(2014, 6, 2, 12, 30, 20, 600)
21809
+ * )
21810
+ * //=> 1100
21811
+ */
21812
+ function differenceInMilliseconds(dateLeft, dateRight) {
21813
+ requiredArgs(2, arguments);
21814
+ return toDate(dateLeft).getTime() - toDate(dateRight).getTime();
21815
+ }
21816
+
21817
+ var roundingMap = {
21818
+ ceil: Math.ceil,
21819
+ round: Math.round,
21820
+ floor: Math.floor,
21821
+ trunc: function trunc(value) {
21822
+ return value < 0 ? Math.ceil(value) : Math.floor(value);
21823
+ } // Math.trunc is not supported by IE
21824
+ };
21825
+
21826
+ var defaultRoundingMethod = 'trunc';
21827
+ function getRoundingMethod(method) {
21828
+ return method ? roundingMap[method] : roundingMap[defaultRoundingMethod];
21829
+ }
21830
+
21831
+ /**
21832
+ * @name differenceInMinutes
21833
+ * @category Minute Helpers
21834
+ * @summary Get the number of minutes between the given dates.
21835
+ *
21836
+ * @description
21837
+ * Get the signed number of full (rounded towards 0) minutes between the given dates.
21838
+ *
21839
+ * @param {Date|Number} dateLeft - the later date
21840
+ * @param {Date|Number} dateRight - the earlier date
21841
+ * @param {Object} [options] - an object with options.
21842
+ * @param {String} [options.roundingMethod='trunc'] - a rounding method (`ceil`, `floor`, `round` or `trunc`)
21843
+ * @returns {Number} the number of minutes
21844
+ * @throws {TypeError} 2 arguments required
21845
+ *
21846
+ * @example
21847
+ * // How many minutes are between 2 July 2014 12:07:59 and 2 July 2014 12:20:00?
21848
+ * const result = differenceInMinutes(
21849
+ * new Date(2014, 6, 2, 12, 20, 0),
21850
+ * new Date(2014, 6, 2, 12, 7, 59)
21851
+ * )
21852
+ * //=> 12
21853
+ *
21854
+ * @example
21855
+ * // How many minutes are between 10:01:59 and 10:00:00
21856
+ * const result = differenceInMinutes(
21857
+ * new Date(2000, 0, 1, 10, 0, 0),
21858
+ * new Date(2000, 0, 1, 10, 1, 59)
21859
+ * )
21860
+ * //=> -1
21861
+ */
21862
+ function differenceInMinutes(dateLeft, dateRight, options) {
21863
+ requiredArgs(2, arguments);
21864
+ var diff = differenceInMilliseconds(dateLeft, dateRight) / millisecondsInMinute;
21865
+ return getRoundingMethod(options === null || options === void 0 ? void 0 : options.roundingMethod)(diff);
21866
+ }
21867
+
21868
+ exports.OperationLockService = class OperationLockService {
21869
+ constructor(operations) {
21870
+ this.operations = operations;
21871
+ this.executeExclusive = async (input) => {
21872
+ const lock = await this.operations.acquire({
21873
+ lockUid: input.lockUid,
21874
+ requestedBy: input.requestedBy,
21875
+ });
21876
+ if (!lock.available &&
21877
+ input.lockTimeout &&
21878
+ this.isLockExpired(lock.lockItem, new Date(), input.lockTimeout)) {
21879
+ await this.operations.release({
21880
+ lockUid: input.lockUid,
21881
+ });
21882
+ return await this.executeExclusive(input);
21883
+ }
21884
+ if (!lock.available) {
21885
+ return {
21886
+ skipped: true,
21887
+ result: undefined,
21888
+ };
21889
+ }
21890
+ try {
21891
+ return {
21892
+ skipped: false,
21893
+ result: await this.executeOperation(input),
21894
+ };
21895
+ }
21896
+ finally {
21897
+ await this.operations.release({
21898
+ lockUid: input.lockUid,
21899
+ });
21900
+ }
21901
+ };
21902
+ this.executeOperation = async (input) => {
21903
+ return await input.operation();
21904
+ };
21905
+ this.isLockExpired = (item, refDate, timeoutMinutes) => {
21906
+ return differenceInMinutes(refDate, item.createdOn) > timeoutMinutes;
21907
+ };
21908
+ }
21909
+ };
21910
+ exports.OperationLockService = __decorate([
21911
+ common.Injectable(),
21912
+ __param(0, common.Optional()),
21913
+ __param(0, common.Inject(getEntityManagerProviderToken("OperationsLockRepository"))),
21914
+ __metadata("design:paramtypes", [Object])
21915
+ ], exports.OperationLockService);
21916
+
21917
+ exports.TypeormOperationLockRepository = class TypeormOperationLockRepository {
21918
+ constructor(repo, entityClass) {
21919
+ this.repo = repo;
21920
+ this.entityClass = entityClass;
21921
+ // todo: fix typing (and remove as any)
21922
+ this.get = async (lockUid) => (await this.repo.findOne({
21923
+ where: {
21924
+ uid: lockUid,
21925
+ },
21926
+ })) ?? undefined;
21927
+ this.acquire = async (input) => {
21928
+ return await this.repo.manager.transaction(async (manager) => {
21929
+ const currentLock = await manager.findOne(this.entityClass, {
21930
+ where: [
21931
+ {
21932
+ uid: input.lockUid,
21933
+ },
21934
+ ],
21935
+ });
21936
+ if (currentLock) {
21937
+ return {
21938
+ available: false,
21939
+ lockItem: currentLock,
21940
+ };
21941
+ }
21942
+ const newLock = manager.create(this.entityClass, {
21943
+ id: backendCore.newUuid(),
21944
+ uid: input.lockUid,
21945
+ lockedBy: input.requestedBy,
21946
+ });
21947
+ await manager.save([newLock]);
21948
+ return {
21949
+ available: true,
21950
+ lockItem: newLock,
21951
+ };
21952
+ });
21953
+ };
21954
+ this.release = async (input) => {
21955
+ const result = await this.repo.delete({
21956
+ uid: input.lockUid,
21957
+ });
21958
+ if (result.affected === 0) {
21959
+ throw new LockNotFoundError(`Lock ${input.lockUid} was not found`);
21960
+ }
21961
+ };
21962
+ }
21963
+ };
21964
+ exports.TypeormOperationLockRepository = __decorate([
21965
+ common.Injectable(),
21966
+ __metadata("design:paramtypes", [typeorm.Repository, Object])
21967
+ ], exports.TypeormOperationLockRepository);
21968
+
21688
21969
  exports.EmailService = class EmailService {
21689
21970
  constructor(registry) {
21690
21971
  this.registry = registry;
@@ -22648,6 +22929,7 @@ const Services$1 = [
22648
22929
  exports.MediaLibraryService,
22649
22930
  exports.SecretsService,
22650
22931
  exports.TrackingService,
22932
+ exports.OperationLockService,
22651
22933
  ];
22652
22934
 
22653
22935
  const IoC = [exports.EntityManagerRegistry];
@@ -23222,10 +23504,32 @@ const getIoCContext = () => {
23222
23504
  return _context;
23223
23505
  };
23224
23506
 
23507
+ const ModuleData$7 = {
23508
+ imports: [exports.CustomDiscoveryModule, eventEmitter.EventEmitterModule],
23509
+ providers: [
23510
+ ...IoC,
23511
+ ...Providers,
23512
+ ...Processors,
23513
+ ...Services$1,
23514
+ ...PipelineProviders,
23515
+ ],
23516
+ exports: [exports.EntityManagerRegistry, ...Services$1],
23517
+ };
23225
23518
  exports.EntityManagerModule = class EntityManagerModule {
23226
23519
  constructor(registry) {
23227
23520
  this.registry = registry;
23228
23521
  }
23522
+ // static forRoot(input: {
23523
+ // imports?: ModuleMetadata["imports"]
23524
+ // providers?: ModuleMetadata["providers"]
23525
+ // }): DynamicModule {
23526
+ // return {
23527
+ // module: EntityManagerModule,
23528
+ // imports: ModuleData.imports,
23529
+ // providers: [...ModuleData.providers, ...(input.providers ?? [])],
23530
+ // exports: ModuleData.exports,
23531
+ // }
23532
+ // }
23229
23533
  onModuleInit() {
23230
23534
  initializeIoCContext({
23231
23535
  registry: this.registry,
@@ -23234,15 +23538,9 @@ exports.EntityManagerModule = class EntityManagerModule {
23234
23538
  };
23235
23539
  exports.EntityManagerModule = __decorate([
23236
23540
  common.Module({
23237
- imports: [exports.CustomDiscoveryModule, eventEmitter.EventEmitterModule],
23238
- providers: [
23239
- ...IoC,
23240
- ...Providers,
23241
- ...Processors,
23242
- ...Services$1,
23243
- ...PipelineProviders,
23244
- ],
23245
- exports: [exports.EntityManagerRegistry, ...Services$1],
23541
+ imports: ModuleData$7.imports,
23542
+ providers: ModuleData$7.providers,
23543
+ exports: ModuleData$7.exports,
23246
23544
  }),
23247
23545
  __metadata("design:paramtypes", [exports.EntityManagerRegistry])
23248
23546
  ], exports.EntityManagerModule);
@@ -32698,6 +32996,7 @@ exports.AwsSesEmailTemplate = AwsSesEmailTemplate;
32698
32996
  exports.CurrentUser = CurrentUser;
32699
32997
  exports.EntityManagerConfigurationError = EntityManagerConfigurationError;
32700
32998
  exports.EntityManagerException = EntityManagerException;
32999
+ exports.EntityManagerProviderToken = EntityManagerProviderToken;
32701
33000
  exports.EntityManagerSymbols = EntityManagerSymbols;
32702
33001
  exports.EntityManagerUnauthorizedException = EntityManagerUnauthorizedException;
32703
33002
  exports.EntityNotFoundException = EntityNotFoundException;
@@ -32707,6 +33006,7 @@ exports.EntitySerializer = EntitySerializer;
32707
33006
  exports.EntitySnapshotService = EntitySnapshotService;
32708
33007
  exports.IEntityVersionsCursor = IEntityVersionsCursor;
32709
33008
  exports.InvalidCredentialsError = InvalidCredentialsError;
33009
+ exports.LockNotFoundError = LockNotFoundError;
32710
33010
  exports.MemberOf = MemberOf;
32711
33011
  exports.MissingEntityIdError = MissingEntityIdError;
32712
33012
  exports.MultipleEntitiesFoundException = MultipleEntitiesFoundException;
@@ -32769,6 +33069,7 @@ exports.WpSendgridEmailTemplate = WpSendgridEmailTemplate;
32769
33069
  exports.WpUserRolesService = WpUserRolesService;
32770
33070
  exports.WpUserService = WpUserService;
32771
33071
  exports.buildPermissionsGuard = buildPermissionsGuard;
33072
+ exports.buildProviderToken = buildProviderToken;
32772
33073
  exports.buildRolesGuard = buildRolesGuard;
32773
33074
  exports.createContainer = createContainer;
32774
33075
  exports.createExpressFileResponse = createExpressFileResponse;