@timardex/cluemart-server-shared 4.0.6 → 4.0.7

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.
@@ -102,15 +102,47 @@ declare function getSubscriptionRewardPeriodBounds(now?: Date): {
102
102
  /**
103
103
  * Connect to MongoDB using Mongoose.
104
104
  * Supports both local MongoDB (via MONGODB_URI) and MongoDB Atlas (via individual env vars).
105
+ *
106
+ * Unless `ensureIndexes` is false, every index declared on the registered
107
+ * schemas is (re)built in the background after connecting — see
108
+ * {@link ensureDatabaseIndexes} for why the implicit Mongoose build is not
109
+ * enough. It is not awaited so a large first build cannot delay startup.
105
110
  */
106
- declare const connectToDatabase: ({ appName, dbName, dbPassword, dbUser, mongodbUri, }: {
111
+ declare const connectToDatabase: ({ appName, dbName, dbPassword, dbUser, ensureIndexes, mongodbUri, }: {
107
112
  appName: string;
108
113
  dbName: string;
109
114
  dbPassword: string;
110
115
  dbUser: string;
116
+ ensureIndexes?: boolean;
111
117
  mongodbUri: string;
112
118
  }) => Promise<void>;
113
119
 
120
+ /** Minimal model surface needed to build indexes (kept structural for tests). */
121
+ interface IndexableModel {
122
+ createIndexes: () => Promise<unknown>;
123
+ modelName: string;
124
+ }
125
+ interface IndexBuildFailure {
126
+ error: unknown;
127
+ model: string;
128
+ }
129
+ /**
130
+ * Builds every index declared on the registered schemas.
131
+ *
132
+ * Mongoose only builds them implicitly at connect time, where a failed build is
133
+ * reported through a background event nobody listens to. A collection that
134
+ * predates an index — or whose build failed once — then silently keeps
135
+ * rejecting `$text` queries with "text index required for $text query", which
136
+ * is exactly how `eventsSearch` loses every result. Running the same builds
137
+ * explicitly repairs such a collection on the next boot and turns a failure
138
+ * into a log line naming the model.
139
+ *
140
+ * Additive only: `createIndexes` never drops an existing index, so indexes
141
+ * created outside the schemas are left alone. Failures are collected instead of
142
+ * thrown so one broken collection cannot stop the application from starting.
143
+ */
144
+ declare function ensureDatabaseIndexes(models?: IndexableModel[]): Promise<IndexBuildFailure[]>;
145
+
114
146
  /** Matches partial unique indexes for promo/affiliate codes on active documents. */
115
147
  declare const ACTIVE_NOT_DELETED_FILTER: {
116
148
  readonly active: true;
@@ -602,4 +634,4 @@ declare function checkOwnerHasLicence({ userId, resourceType, }: {
602
634
  resourceType: EnumResourceType;
603
635
  }): Promise<void>;
604
636
 
605
- export { ACTIVE_NOT_DELETED_FILTER, type AwardAffiliateVendorSubscriptionRewardsResult, LicenceCategory, type NotificationPubSub, REMINDER_WINDOW_MAX_HOURS, REMINDER_WINDOW_MIN_HOURS, SUBSCRIPTION_REWARD_TIMEZONE, activeAffiliateCodeExists, awardAffiliateVendorSubscriptionRewards, buildLicenceExpiryPipeline, buildUserHasEnoughPointsFilter, buildUserPointAwardEntry, buildUserPointCreditFilter, buildUserPointDebitPipeline, buildUserPointEntryRemovalPipeline, checkOwnerHasLicence, connectToDatabase, convertObjectIdsToStrings, createLicenceObject, dedupeArchivedSlotsByStartDateTime, didRemoveAnyEventDates, didRemoveAnyStartedDates, downgradeVendorProFeatures, ensureUserLicenseCompliance, ensureUserLicenseComplianceForUser, eventLicences, findAffiliateByPromoCode, findEventOrImportedMarketById, getEventResourceInfo, getHighestLicenceForCategory, getLicenceCategory, getLicenceExpiryMode, getPartnerResourceInfo, getPayingEventStripeSubscriptionPlan, getPayingStripeSubscriptionPlan, getPayingVendorStripeSubscriptionPlan, getSubscriptionRewardPeriodBounds, getVendorResourceInfo, handleEventLicenceCompliance, handlePartnerLicenceCompliance, handleVendorLicenceCompliance, hasValidLicence, isStandardLicence, isValidObjectId, licenceCategoryMapping, licencePriority, mapVendorLicenceToSubscriptionRewardType, normalizeAffiliatePromoCodes, normalizePromoCode, notifyUsers, partnerLicences, persistArchivedEventDates, processLicenseReminder, processUserCompliance, processUserLicenseReminders, publishNotificationEvents, remindUsersAboutLicenseExpiration, replaceUserLicenceWithObject, restoreVendorProFeatures, saveNotificationsInDb, sendDeactivationNotification, sendLicenseReminder, sendPushNotifications, sendReminderSafely, splitEventDatesForArchive, syncUserLicencesAfterExpiry, updateAdStatuses, updateAllEventDateTimeStatuses, updateRelationDatesToCanceled, upgradeUserToLicence, vendorOwnerHasProLicence };
637
+ export { ACTIVE_NOT_DELETED_FILTER, type AwardAffiliateVendorSubscriptionRewardsResult, type IndexBuildFailure, type IndexableModel, LicenceCategory, type NotificationPubSub, REMINDER_WINDOW_MAX_HOURS, REMINDER_WINDOW_MIN_HOURS, SUBSCRIPTION_REWARD_TIMEZONE, activeAffiliateCodeExists, awardAffiliateVendorSubscriptionRewards, buildLicenceExpiryPipeline, buildUserHasEnoughPointsFilter, buildUserPointAwardEntry, buildUserPointCreditFilter, buildUserPointDebitPipeline, buildUserPointEntryRemovalPipeline, checkOwnerHasLicence, connectToDatabase, convertObjectIdsToStrings, createLicenceObject, dedupeArchivedSlotsByStartDateTime, didRemoveAnyEventDates, didRemoveAnyStartedDates, downgradeVendorProFeatures, ensureDatabaseIndexes, ensureUserLicenseCompliance, ensureUserLicenseComplianceForUser, eventLicences, findAffiliateByPromoCode, findEventOrImportedMarketById, getEventResourceInfo, getHighestLicenceForCategory, getLicenceCategory, getLicenceExpiryMode, getPartnerResourceInfo, getPayingEventStripeSubscriptionPlan, getPayingStripeSubscriptionPlan, getPayingVendorStripeSubscriptionPlan, getSubscriptionRewardPeriodBounds, getVendorResourceInfo, handleEventLicenceCompliance, handlePartnerLicenceCompliance, handleVendorLicenceCompliance, hasValidLicence, isStandardLicence, isValidObjectId, licenceCategoryMapping, licencePriority, mapVendorLicenceToSubscriptionRewardType, normalizeAffiliatePromoCodes, normalizePromoCode, notifyUsers, partnerLicences, persistArchivedEventDates, processLicenseReminder, processUserCompliance, processUserLicenseReminders, publishNotificationEvents, remindUsersAboutLicenseExpiration, replaceUserLicenceWithObject, restoreVendorProFeatures, saveNotificationsInDb, sendDeactivationNotification, sendLicenseReminder, sendPushNotifications, sendReminderSafely, splitEventDatesForArchive, syncUserLicencesAfterExpiry, updateAdStatuses, updateAllEventDateTimeStatuses, updateRelationDatesToCanceled, upgradeUserToLicence, vendorOwnerHasProLicence };
@@ -102,15 +102,47 @@ declare function getSubscriptionRewardPeriodBounds(now?: Date): {
102
102
  /**
103
103
  * Connect to MongoDB using Mongoose.
104
104
  * Supports both local MongoDB (via MONGODB_URI) and MongoDB Atlas (via individual env vars).
105
+ *
106
+ * Unless `ensureIndexes` is false, every index declared on the registered
107
+ * schemas is (re)built in the background after connecting — see
108
+ * {@link ensureDatabaseIndexes} for why the implicit Mongoose build is not
109
+ * enough. It is not awaited so a large first build cannot delay startup.
105
110
  */
106
- declare const connectToDatabase: ({ appName, dbName, dbPassword, dbUser, mongodbUri, }: {
111
+ declare const connectToDatabase: ({ appName, dbName, dbPassword, dbUser, ensureIndexes, mongodbUri, }: {
107
112
  appName: string;
108
113
  dbName: string;
109
114
  dbPassword: string;
110
115
  dbUser: string;
116
+ ensureIndexes?: boolean;
111
117
  mongodbUri: string;
112
118
  }) => Promise<void>;
113
119
 
120
+ /** Minimal model surface needed to build indexes (kept structural for tests). */
121
+ interface IndexableModel {
122
+ createIndexes: () => Promise<unknown>;
123
+ modelName: string;
124
+ }
125
+ interface IndexBuildFailure {
126
+ error: unknown;
127
+ model: string;
128
+ }
129
+ /**
130
+ * Builds every index declared on the registered schemas.
131
+ *
132
+ * Mongoose only builds them implicitly at connect time, where a failed build is
133
+ * reported through a background event nobody listens to. A collection that
134
+ * predates an index — or whose build failed once — then silently keeps
135
+ * rejecting `$text` queries with "text index required for $text query", which
136
+ * is exactly how `eventsSearch` loses every result. Running the same builds
137
+ * explicitly repairs such a collection on the next boot and turns a failure
138
+ * into a log line naming the model.
139
+ *
140
+ * Additive only: `createIndexes` never drops an existing index, so indexes
141
+ * created outside the schemas are left alone. Failures are collected instead of
142
+ * thrown so one broken collection cannot stop the application from starting.
143
+ */
144
+ declare function ensureDatabaseIndexes(models?: IndexableModel[]): Promise<IndexBuildFailure[]>;
145
+
114
146
  /** Matches partial unique indexes for promo/affiliate codes on active documents. */
115
147
  declare const ACTIVE_NOT_DELETED_FILTER: {
116
148
  readonly active: true;
@@ -602,4 +634,4 @@ declare function checkOwnerHasLicence({ userId, resourceType, }: {
602
634
  resourceType: EnumResourceType;
603
635
  }): Promise<void>;
604
636
 
605
- export { ACTIVE_NOT_DELETED_FILTER, type AwardAffiliateVendorSubscriptionRewardsResult, LicenceCategory, type NotificationPubSub, REMINDER_WINDOW_MAX_HOURS, REMINDER_WINDOW_MIN_HOURS, SUBSCRIPTION_REWARD_TIMEZONE, activeAffiliateCodeExists, awardAffiliateVendorSubscriptionRewards, buildLicenceExpiryPipeline, buildUserHasEnoughPointsFilter, buildUserPointAwardEntry, buildUserPointCreditFilter, buildUserPointDebitPipeline, buildUserPointEntryRemovalPipeline, checkOwnerHasLicence, connectToDatabase, convertObjectIdsToStrings, createLicenceObject, dedupeArchivedSlotsByStartDateTime, didRemoveAnyEventDates, didRemoveAnyStartedDates, downgradeVendorProFeatures, ensureUserLicenseCompliance, ensureUserLicenseComplianceForUser, eventLicences, findAffiliateByPromoCode, findEventOrImportedMarketById, getEventResourceInfo, getHighestLicenceForCategory, getLicenceCategory, getLicenceExpiryMode, getPartnerResourceInfo, getPayingEventStripeSubscriptionPlan, getPayingStripeSubscriptionPlan, getPayingVendorStripeSubscriptionPlan, getSubscriptionRewardPeriodBounds, getVendorResourceInfo, handleEventLicenceCompliance, handlePartnerLicenceCompliance, handleVendorLicenceCompliance, hasValidLicence, isStandardLicence, isValidObjectId, licenceCategoryMapping, licencePriority, mapVendorLicenceToSubscriptionRewardType, normalizeAffiliatePromoCodes, normalizePromoCode, notifyUsers, partnerLicences, persistArchivedEventDates, processLicenseReminder, processUserCompliance, processUserLicenseReminders, publishNotificationEvents, remindUsersAboutLicenseExpiration, replaceUserLicenceWithObject, restoreVendorProFeatures, saveNotificationsInDb, sendDeactivationNotification, sendLicenseReminder, sendPushNotifications, sendReminderSafely, splitEventDatesForArchive, syncUserLicencesAfterExpiry, updateAdStatuses, updateAllEventDateTimeStatuses, updateRelationDatesToCanceled, upgradeUserToLicence, vendorOwnerHasProLicence };
637
+ export { ACTIVE_NOT_DELETED_FILTER, type AwardAffiliateVendorSubscriptionRewardsResult, type IndexBuildFailure, type IndexableModel, LicenceCategory, type NotificationPubSub, REMINDER_WINDOW_MAX_HOURS, REMINDER_WINDOW_MIN_HOURS, SUBSCRIPTION_REWARD_TIMEZONE, activeAffiliateCodeExists, awardAffiliateVendorSubscriptionRewards, buildLicenceExpiryPipeline, buildUserHasEnoughPointsFilter, buildUserPointAwardEntry, buildUserPointCreditFilter, buildUserPointDebitPipeline, buildUserPointEntryRemovalPipeline, checkOwnerHasLicence, connectToDatabase, convertObjectIdsToStrings, createLicenceObject, dedupeArchivedSlotsByStartDateTime, didRemoveAnyEventDates, didRemoveAnyStartedDates, downgradeVendorProFeatures, ensureDatabaseIndexes, ensureUserLicenseCompliance, ensureUserLicenseComplianceForUser, eventLicences, findAffiliateByPromoCode, findEventOrImportedMarketById, getEventResourceInfo, getHighestLicenceForCategory, getLicenceCategory, getLicenceExpiryMode, getPartnerResourceInfo, getPayingEventStripeSubscriptionPlan, getPayingStripeSubscriptionPlan, getPayingVendorStripeSubscriptionPlan, getSubscriptionRewardPeriodBounds, getVendorResourceInfo, handleEventLicenceCompliance, handlePartnerLicenceCompliance, handleVendorLicenceCompliance, hasValidLicence, isStandardLicence, isValidObjectId, licenceCategoryMapping, licencePriority, mapVendorLicenceToSubscriptionRewardType, normalizeAffiliatePromoCodes, normalizePromoCode, notifyUsers, partnerLicences, persistArchivedEventDates, processLicenseReminder, processUserCompliance, processUserLicenseReminders, publishNotificationEvents, remindUsersAboutLicenseExpiration, replaceUserLicenceWithObject, restoreVendorProFeatures, saveNotificationsInDb, sendDeactivationNotification, sendLicenseReminder, sendPushNotifications, sendReminderSafely, splitEventDatesForArchive, syncUserLicencesAfterExpiry, updateAdStatuses, updateAllEventDateTimeStatuses, updateRelationDatesToCanceled, upgradeUserToLicence, vendorOwnerHasProLicence };
@@ -453,12 +453,47 @@ function normalizeAffiliatePromoCodes(promoCodes) {
453
453
  }
454
454
 
455
455
  // src/service/database.ts
456
+ import mongoose2 from "mongoose";
457
+
458
+ // src/service/indexes.ts
456
459
  import mongoose from "mongoose";
460
+ function registeredModels() {
461
+ return mongoose.modelNames().map((modelName) => {
462
+ const model = mongoose.model(modelName);
463
+ return { createIndexes: () => model.createIndexes(), modelName };
464
+ });
465
+ }
466
+ async function ensureDatabaseIndexes(models = registeredModels()) {
467
+ const failures = [];
468
+ await Promise.all(
469
+ models.map(async ({ createIndexes, modelName }) => {
470
+ try {
471
+ await createIndexes();
472
+ } catch (error) {
473
+ failures.push({ error, model: modelName });
474
+ console.error(
475
+ `[db] Failed to build indexes for ${modelName}: ${error instanceof Error ? error.message : String(error)}`
476
+ );
477
+ }
478
+ })
479
+ );
480
+ if (failures.length > 0) {
481
+ console.error(
482
+ `[db] ${failures.length} model(s) are missing schema indexes: ${failures.map((failure) => failure.model).join(", ")}`
483
+ );
484
+ } else {
485
+ console.log("[db] Schema indexes verified.");
486
+ }
487
+ return failures;
488
+ }
489
+
490
+ // src/service/database.ts
457
491
  var connectToDatabase = async ({
458
492
  appName,
459
493
  dbName,
460
494
  dbPassword,
461
495
  dbUser,
496
+ ensureIndexes = true,
462
497
  mongodbUri
463
498
  }) => {
464
499
  try {
@@ -466,11 +501,14 @@ var connectToDatabase = async ({
466
501
  // Fallback to MongoDB Atlas connection string
467
502
  `mongodb+srv://${dbUser}:${dbPassword}@${dbName}.mongodb.net/?retryWrites=true&w=majority&appName=${appName}`
468
503
  );
469
- await mongoose.connect(mongoUri);
504
+ await mongoose2.connect(mongoUri);
470
505
  const connectionType = mongodbUri ? "Local MongoDB" : "MongoDB Atlas";
471
506
  console.log(
472
507
  `${connectionType} connected from server/src/service/database.ts`
473
508
  );
509
+ if (ensureIndexes) {
510
+ void ensureDatabaseIndexes();
511
+ }
474
512
  } catch (err) {
475
513
  console.error("Error connecting to MongoDB:", err);
476
514
  throw err;
@@ -590,15 +628,15 @@ async function updateAdStatuses() {
590
628
  }
591
629
 
592
630
  // src/service/objectIdToString.ts
593
- import mongoose2 from "mongoose";
631
+ import mongoose3 from "mongoose";
594
632
  function isValidObjectId(value) {
595
- return mongoose2.Types.ObjectId.isValid(value);
633
+ return mongoose3.Types.ObjectId.isValid(value);
596
634
  }
597
635
  function convertObjectIdsToStrings(obj) {
598
636
  if (obj === null || obj === void 0) {
599
637
  return obj;
600
638
  }
601
- if (obj instanceof mongoose2.Types.ObjectId) {
639
+ if (obj instanceof mongoose3.Types.ObjectId) {
602
640
  return obj.toString();
603
641
  }
604
642
  if (obj instanceof Date) {
@@ -2256,6 +2294,7 @@ export {
2256
2294
  didRemoveAnyEventDates,
2257
2295
  didRemoveAnyStartedDates,
2258
2296
  downgradeVendorProFeatures,
2297
+ ensureDatabaseIndexes,
2259
2298
  ensureUserLicenseCompliance,
2260
2299
  ensureUserLicenseComplianceForUser,
2261
2300
  eventLicences,