@lyxa.ai/core 1.0.8 → 1.0.9

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/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"/","sources":["index.ts"],"names":[],"mappings":";;;;;;AAwBA,sCAqBC;AAED,8CAwDC;AAED,oCAEC;AA3GD,2CAA2C;AAC3C,mCAAiC;AACjC,wDAAgC;AAChC,6DAAqF;AACrF,+GAA0G;AAC1G,+CAA8C;AAC9C,6CAA+C;AAC/C,6CAAuD;AACvD,iDAAyD;AACzD,uDAA8D;AAC9D,+CAAiD;AACjD,mDAAqD;AACrD,6CAAiE;AACjE,0FAAqF;AAIrF,6GAA4G;AAAnG,4IAAA,4BAA4B,OAAA;AACrC,2CAI2B;AAHvB,6GAAA,oBAAoB,OAAA;AACpB,0GAAA,iBAAiB,OAAA;AACjB,uHAAA,8BAA8B,OAAA;AAG3B,KAAK,UAAU,aAAa,CAAC,OAA8B;IAC9D,IAAI,CAAC;QACD,MAAM,iBAAiB,CAAC,OAAO,CAAC,CAAC;QAEjC,YAAY,EAAE,CAAC,SAAS,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,sCAAsC,CAAC,CAAC;QAE/E,MAAM,gBAAgB,GAAG,KAAK,IAAI,EAAE;YAChC,YAAY,EAAE,CAAC,SAAS,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,uDAAuD,CAAC,CAAC;QACpG,CAAC,CAAC;QAEF,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,gBAAgB,CAAC,CAAC;QACxC,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,gBAAgB,CAAC,CAAC;QACvC,OAAO,CAAC,EAAE,CAAC,mBAAmB,EAAE,CAAC,GAAG,EAAE,EAAE;YACpC,YAAY,EAAE,CAAC,SAAS,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,sCAAsC,EAAE,GAAG,CAAC,C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,GAAG,CAAC,0BAAc,CAAC,CAAA;AACxC,CAAC","sourcesContent":["import {LibraryManager} from \"./libraries\";\r\nimport {Container} from \"typedi\";\r\nimport mongoose from \"mongoose\";\r\nimport {ConfigurationOptions, ConfigurationService} from \"./libraries/configuration\";\r\nimport {EnvironmentConfigurationType} from \"./libraries/configuration/types/EnvironmentConfigurationType\";\r\nimport {LyxaLogger} from \"./libraries/logger\";\r\nimport {RedisService} from \"./libraries/redis\";\r\nimport {initGlobalConnection} from \"./libraries/mongo\";\r\nimport {SecretManagerService} from \"./libraries/secrets\";\r\nimport {MicroServiceDispatcher} from \"./libraries/dispatcher\";\r\nimport {TwilioService} from \"./libraries/twilio\";\r\nimport {FirebaseService} from \"./libraries/firebase\";\r\nimport {initEventBus, subscribeToEvent} from \"./libraries/event\";\r\nimport {SubscriptionRegistry} from \"./libraries/event/registry/SubscriptionRegistry\";\r\nimport {AuthEntityType, signToken} from \"./libraries/auth\";\r\n\r\nexport { ConfigurationOptions } from \"./libraries/configuration\";\r\nexport { EnvironmentConfigurationType } from \"./libraries/configuration/types/EnvironmentConfigurationType\";\r\nexport {\r\n initGlobalConnection,\r\n createGlobalModel,\r\n createGlobalDiscriminatorModel\r\n} from './libraries/mongo';\r\n\r\nexport async function bootstrapCore(options?: ConfigurationOptions) {\r\n try {\r\n await registerLibraries(options);\r\n\r\n getLibraries().getLogger().logger.info(\"Successfully bootstrapped lyxa-core.\");\r\n\r\n const gracefulShutdown = async () => {\r\n getLibraries().getLogger().logger.info('Received shutdown signal, shutting down gracefully...');\r\n };\r\n\r\n process.on('SIGTERM', gracefulShutdown);\r\n process.on('SIGINT', gracefulShutdown);\r\n process.on('uncaughtException', (err) => {\r\n getLibraries().getLogger().logger.error('Uncaught exception, shutting down...', err);\r\n gracefulShutdown();\r\n });\r\n\r\n console.log(\"Created hooks.\");\r\n } catch (e) {\r\n console.error(e);\r\n }\r\n}\r\n\r\nexport async function registerLibraries(options?: ConfigurationOptions) {\r\n // Setup configuration.\r\n const configurationInstance = new ConfigurationService(options);\r\n Container.set(ConfigurationService, configurationInstance);\r\n\r\n // Setup redis.\r\n const redisInstance = new RedisService(configurationInstance.options.redisURL!);\r\n Container.set(RedisService, redisInstance);\r\n\r\n // Setup secret\r\n const secretInstance = new SecretManagerService(configurationInstance, redisInstance);\r\n Container.set(SecretManagerService, secretInstance);\r\n\r\n const mongoUrl = await getLibraries().getSecretsService()\r\n .getKey(\"MONGO_URL\");\r\n\r\n await mongoose.connect(mongoUrl!, { dbName: `lyxa-${options!.environment}-${options!.tenet}` });\r\n mongoose.set('debug', getLibraries().getConfigurationService().options.environment == EnvironmentConfigurationType.DEV);\r\n\r\n await initGlobalConnection(mongoUrl!, options!.environment);\r\n\r\n // Setup logger\r\n const loggerInstance = new LyxaLogger(options!.instanceType!, mongoUrl!);\r\n Container.set(LyxaLogger, loggerInstance);\r\n\r\n // Setup firebase\r\n const firebaseInstance = new FirebaseService(configurationInstance!);\r\n Container.set(FirebaseService, firebaseInstance);\r\n\r\n // Setup microservice dispatcher\r\n const microserviceDispatcherInstance = new MicroServiceDispatcher(secretInstance);\r\n Container.set(MicroServiceDispatcher, microserviceDispatcherInstance);\r\n\r\n\r\n // Setup twilio\r\n const twilioServiceInstance = new TwilioService();\r\n Container.set(TwilioService, twilioServiceInstance);\r\n\r\n console.log(\"Initialized everything\");\r\n\r\n await initEventBus(\"amqps://vgyuplrd:wto6vUYnb4zeBI5lntKT4gj7rT8n1vwg@dog.lmq.cloudamqp.com/vgyuplrd\");\r\n const allSubscriptions = SubscriptionRegistry.getAllSubscriptions();\r\n\r\n const instantiatedServices = new Map<Function, any>();\r\n\r\n for (const { eventId, targetConstructor, methodName } of allSubscriptions) {\r\n let instance = instantiatedServices.get(targetConstructor);\r\n if (!instance) {\r\n instance = Container.get(targetConstructor as any);\r\n instantiatedServices.set(targetConstructor, instance);\r\n }\r\n\r\n await subscribeToEvent(eventId, async (payload) => {\r\n return instance[methodName](payload);\r\n });\r\n }\r\n}\r\n\r\nexport function getLibraries(): LibraryManager {\r\n return Container.get(LibraryManager)\r\n}\r\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"/","sources":["index.ts"],"names":[],"mappings":";;;;;;AAuBA,sCAqBC;AAED,8CAwDC;AAED,oCAEC;AA1GD,2CAA2C;AAC3C,mCAAiC;AACjC,wDAAgC;AAChC,6DAAqF;AACrF,+GAA0G;AAC1G,+CAA8C;AAC9C,6CAA+C;AAC/C,6CAAuD;AACvD,iDAAyD;AACzD,uDAA8D;AAC9D,+CAAiD;AACjD,mDAAqD;AACrD,6CAAiE;AACjE,0FAAqF;AAGrF,6GAA4G;AAAnG,4IAAA,4BAA4B,OAAA;AACrC,2CAI2B;AAHvB,6GAAA,oBAAoB,OAAA;AACpB,0GAAA,iBAAiB,OAAA;AACjB,uHAAA,8BAA8B,OAAA;AAG3B,KAAK,UAAU,aAAa,CAAC,OAA8B;IAC9D,IAAI,CAAC;QACD,MAAM,iBAAiB,CAAC,OAAO,CAAC,CAAC;QAEjC,YAAY,EAAE,CAAC,SAAS,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,sCAAsC,CAAC,CAAC;QAE/E,MAAM,gBAAgB,GAAG,KAAK,IAAI,EAAE;YAChC,YAAY,EAAE,CAAC,SAAS,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,uDAAuD,CAAC,CAAC;QACpG,CAAC,CAAC;QAEF,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,gBAAgB,CAAC,CAAC;QACxC,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,gBAAgB,CAAC,CAAC;QACvC,OAAO,CAAC,EAAE,CAAC,mBAAmB,EAAE,CAAC,GAAG,EAAE,EAAE;YACpC,YAAY,EAAE,CAAC,SAAS,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,sCAAsC,EAAE,GAAG,CAAC,CAAC;YACrF,gBAAgB,EAAE,CAAC;QACvB,CAAC,CAAC,CAAC;QAEH,OAAO,CAAC,GAAG,CAAC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Container} from \"typedi\";\r\nimport mongoose from \"mongoose\";\r\nimport {ConfigurationOptions, ConfigurationService} from \"./libraries/configuration\";\r\nimport {EnvironmentConfigurationType} from \"./libraries/configuration/types/EnvironmentConfigurationType\";\r\nimport {LyxaLogger} from \"./libraries/logger\";\r\nimport {RedisService} from \"./libraries/redis\";\r\nimport {initGlobalConnection} from \"./libraries/mongo\";\r\nimport {SecretManagerService} from \"./libraries/secrets\";\r\nimport {MicroServiceDispatcher} from \"./libraries/dispatcher\";\r\nimport {TwilioService} from \"./libraries/twilio\";\r\nimport {FirebaseService} from \"./libraries/firebase\";\r\nimport {initEventBus, subscribeToEvent} from \"./libraries/event\";\r\nimport {SubscriptionRegistry} from \"./libraries/event/registry/SubscriptionRegistry\";\r\n\r\nexport { ConfigurationOptions } from \"./libraries/configuration\";\r\nexport { EnvironmentConfigurationType } from \"./libraries/configuration/types/EnvironmentConfigurationType\";\r\nexport {\r\n initGlobalConnection,\r\n createGlobalModel,\r\n createGlobalDiscriminatorModel\r\n} from './libraries/mongo';\r\n\r\nexport async function bootstrapCore(options?: ConfigurationOptions) {\r\n try {\r\n await registerLibraries(options);\r\n\r\n getLibraries().getLogger().logger.info(\"Successfully bootstrapped lyxa-core.\");\r\n\r\n const gracefulShutdown = async () => {\r\n getLibraries().getLogger().logger.info('Received shutdown signal, shutting down gracefully...');\r\n };\r\n\r\n process.on('SIGTERM', gracefulShutdown);\r\n process.on('SIGINT', gracefulShutdown);\r\n process.on('uncaughtException', (err) => {\r\n getLibraries().getLogger().logger.error('Uncaught exception, shutting down...', err);\r\n gracefulShutdown();\r\n });\r\n\r\n console.log(\"Created hooks.\");\r\n } catch (e) {\r\n console.error(e);\r\n }\r\n}\r\n\r\nexport async function registerLibraries(options?: ConfigurationOptions) {\r\n // Setup configuration.\r\n const configurationInstance = new ConfigurationService(options);\r\n Container.set(ConfigurationService, configurationInstance);\r\n\r\n // Setup redis.\r\n const redisInstance = new RedisService(configurationInstance.options.redisURL!);\r\n Container.set(RedisService, redisInstance);\r\n\r\n // Setup secret\r\n const secretInstance = new SecretManagerService(configurationInstance, redisInstance);\r\n Container.set(SecretManagerService, secretInstance);\r\n\r\n const mongoUrl = await getLibraries().getSecretsService()\r\n .getKey(\"MONGO_URL\");\r\n\r\n await mongoose.connect(mongoUrl!, { dbName: `lyxa-${options!.environment}-${options!.tenet}` });\r\n mongoose.set('debug', getLibraries().getConfigurationService().options.environment == EnvironmentConfigurationType.DEV);\r\n\r\n await initGlobalConnection(mongoUrl!, options!.environment);\r\n\r\n // Setup logger\r\n const loggerInstance = new LyxaLogger(options!.instanceType!, mongoUrl!);\r\n Container.set(LyxaLogger, loggerInstance);\r\n\r\n // Setup firebase\r\n const firebaseInstance = new FirebaseService(configurationInstance!);\r\n Container.set(FirebaseService, firebaseInstance);\r\n\r\n // Setup microservice dispatcher\r\n const microserviceDispatcherInstance = new MicroServiceDispatcher(secretInstance);\r\n Container.set(MicroServiceDispatcher, microserviceDispatcherInstance);\r\n\r\n\r\n // Setup twilio\r\n const twilioServiceInstance = new TwilioService();\r\n Container.set(TwilioService, twilioServiceInstance);\r\n\r\n console.log(\"Initialized everything\");\r\n\r\n await initEventBus(\"amqps://vgyuplrd:wto6vUYnb4zeBI5lntKT4gj7rT8n1vwg@dog.lmq.cloudamqp.com/vgyuplrd\");\r\n const allSubscriptions = SubscriptionRegistry.getAllSubscriptions();\r\n\r\n const instantiatedServices = new Map<Function, any>();\r\n\r\n for (const { eventId, targetConstructor, methodName } of allSubscriptions) {\r\n let instance = instantiatedServices.get(targetConstructor);\r\n if (!instance) {\r\n instance = Container.get(targetConstructor as any);\r\n instantiatedServices.set(targetConstructor, instance);\r\n }\r\n\r\n await subscribeToEvent(eventId, async (payload) => {\r\n return instance[methodName](payload);\r\n });\r\n }\r\n}\r\n\r\nexport function getLibraries(): LibraryManager {\r\n return Container.get(LibraryManager)\r\n}\r\n"]}
@@ -23,7 +23,7 @@ async function signToken(entity, options) {
23
23
  .getSecretsService()
24
24
  .getKey(`${entity.type.toUpperCase()}_JWT_TOKEN`);
25
25
  if (!secret) {
26
- throw new Error(`No secret found for entity type: ${entity.type}`);
26
+ throw new Error(`No secret found for entity type ${entity.type}`);
27
27
  }
28
28
  const payload = {
29
29
  id: entity.id,
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"/","sources":["libraries/auth/index.ts"],"names":[],"mappings":";;;;;;AAeA,8BAuBC;AAED,kCASC;AAjDD,gEAA8C;AAC9C,uCAAyC;AAGzC,IAAY,cAKX;AALD,WAAY,cAAc;IACtB,+BAAa,CAAA;IACb,mCAAiB,CAAA;IACjB,+CAA6B,CAAA;IAC7B,6BAAW,CAAA;AACf,CAAC,EALW,cAAc,8BAAd,cAAc,QAKzB;AAMM,KAAK,UAAU,SAAS,CAC3B,MAAiF,EACjF,OAAqB;IAErB,IAAI,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC;QAChB,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;IAC7D,CAAC;IAED,MAAM,MAAM,GAAG,MAAM,IAAA,oBAAY,GAAE;SAC9B,iBAAiB,EAAE;SACnB,MAAM,CAAC,GAAG,MAAM,CAAC,IAAI,CAAC,WAAW,EAAE,YAAY,CAAC,CAAC;IAEtD,IAAI,CAAC,MAAM,EAAE,CAAC;QACV,MAAM,IAAI,KAAK,CAAC,oCAAoC,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC;IACvE,CAAC;IAED,MAAM,OAAO,GAAG;QACZ,EAAE,EAAE,MAAM,CAAC,EAAE;QACb,IAAI,EAAE,MAAM,CAAC,IAAI;QACjB,UAAU,EAAE,MAAM,CAAC,UAAU;KAChC,CAAC;IAEF,OAAO,sBAAG,CAAC,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;AAC9C,CAAC;AAEM,KAAK,UAAU,WAAW,CAAC,WAA6B,EAAE,KAAa;IAC1E,KAAI,MAAM,UAAU,IAAI,WAAW,EAAE,CAAC;QAClC,MAAM,MAAM,GAAG,MAAM,IAAA,oBAAY,GAAE,CAAC,iBAAiB,EAAE,CAAC,MAAM,CAAC,UAAU,CAAC,WAAW,EAAE,GAAG,YAAY,CAAC,CAAC;QAExG,IAAI,CAAC;YACD,OAAO,sBAAG,CAAC,MAAM,CAAC,KAAK,EAAE,MAAO,CAAkB,CAAC;QACvD,CAAC;QAAC,OAAM,GAAG,EAAE,CAAC;QACd,CAAC;IACL,CAAC;AACL,CAAC","sourcesContent":["import jwt, {SignOptions} from \"jsonwebtoken\";\r\nimport {getLibraries} from \"../../index\";\r\nimport {EntityContext} from \"../trpc/context\";\r\n\r\nexport enum AuthEntityType {\r\n USER = \"USER\",\r\n SELLER = \"SELLER\",\r\n DELIVERY_BOY = \"DELIVERY_BOY\",\r\n CRM = \"CRM\"\r\n}\r\n\r\n/**\r\n * Sign a JWT for the given entity (id + type).\r\n * It will fetch the secret for that entity type and create a token.\r\n */\r\nexport async function signToken(\r\n entity: { id: string; type: AuthEntityType, parameters: Record<string, unknown> },\r\n options?: SignOptions\r\n): Promise<string> {\r\n if (!entity?.type) {\r\n throw new Error('Entity type is required to sign token');\r\n }\r\n\r\n const secret = await getLibraries()\r\n .getSecretsService()\r\n .getKey(`${entity.type.toUpperCase()}_JWT_TOKEN`);\r\n\r\n if (!secret) {\r\n throw new Error(`No secret found for entity type: ${entity.type}`);\r\n }\r\n\r\n const payload = {\r\n id: entity.id,\r\n type: entity.type,\r\n parameters: entity.parameters,\r\n };\r\n\r\n return jwt.sign(payload, secret, options);\r\n}\r\n\r\nexport async function verifyToken(entityTypes: AuthEntityType[], token: string): Promise<EntityContext | undefined> {\r\n for(const entityType of entityTypes) {\r\n const secret = await getLibraries().getSecretsService().getKey(entityType.toUpperCase() + \"_JWT_TOKEN\");\r\n\r\n try {\r\n return jwt.verify(token, secret!) as EntityContext;\r\n } catch(err) {\r\n }\r\n }\r\n}\r\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"/","sources":["libraries/auth/index.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,CAAC;QAAC,OAAM,GAAG,EAAE,CAAC;QACd,CAAC;IACL,CAAC;AACL,CAAC","sourcesContent":["import jwt, {SignOptions} from \"jsonwebtoken\";\r\nimport {getLibraries} from \"../../index\";\r\nimport {EntityContext} from \"../trpc/context\";\r\n\r\nexport enum AuthEntityType {\r\n USER = \"USER\",\r\n SELLER = \"SELLER\",\r\n DELIVERY_BOY = \"DELIVERY_BOY\",\r\n CRM = \"CRM\"\r\n}\r\n\r\n/**\r\n * Sign a JWT for the given entity (id + type).\r\n * It will fetch the secret for that entity type and create a token.\r\n */\r\nexport async function signToken(\r\n entity: { id: string; type: AuthEntityType, parameters: Record<string, unknown> },\r\n options?: SignOptions\r\n): Promise<string> {\r\n if (!entity?.type) {\r\n throw new Error('Entity type is required to sign token');\r\n }\r\n\r\n const secret = await getLibraries()\r\n .getSecretsService()\r\n .getKey(`${entity.type.toUpperCase()}_JWT_TOKEN`);\r\n\r\n if (!secret) {\r\n throw new Error(`No secret found for entity type ${entity.type}`);\r\n }\r\n\r\n const payload = {\r\n id: entity.id,\r\n type: entity.type,\r\n parameters: entity.parameters,\r\n };\r\n\r\n return jwt.sign(payload, secret, options);\r\n}\r\n\r\nexport async function verifyToken(entityTypes: AuthEntityType[], token: string): Promise<EntityContext | undefined> {\r\n for(const entityType of entityTypes) {\r\n const secret = await getLibraries().getSecretsService().getKey(entityType.toUpperCase() + \"_JWT_TOKEN\");\r\n\r\n try {\r\n return jwt.verify(token, secret!) as EntityContext;\r\n } catch(err) {\r\n }\r\n }\r\n}\r\n"]}
@@ -5,6 +5,8 @@ exports.createGlobalModel = createGlobalModel;
5
5
  exports.createGlobalDiscriminatorModel = createGlobalDiscriminatorModel;
6
6
  const mongoose_1 = require("mongoose");
7
7
  const typegoose_1 = require("@typegoose/typegoose");
8
+ const soft_delete_plugin_1 = require("./plugins/soft-delete-plugin");
9
+ (0, soft_delete_plugin_1.applySoftDeletePlugin)();
8
10
  let globalConnection;
9
11
  async function initGlobalConnection(uri, environment) {
10
12
  if (!globalConnection) {
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"/","sources":["libraries/mongo/index.ts"],"names":[],"mappings":";;AAMA,oDAOC;AAKD,8CASC;AAWD,wEAmBC;AAzDD,uCAAwD;AACxD,oDAAsG;AAGtG,IAAI,gBAAwC,CAAC;AAEtC,KAAK,UAAU,oBAAoB,CAAC,GAAW,EAAE,WAAmB;IACvE,IAAI,CAAC,gBAAgB,EAAE,CAAC;QACpB,gBAAgB,GAAG,IAAA,2BAAgB,EAAC,GAAG,EAAE;YACrC,MAAM,EAAE,QAAQ,WAAW,SAAS;SACvC,CAAC,CAAC;IACP,CAAC;IACD,OAAO,gBAAgB,CAAC;AAC5B,CAAC;AAKD,SAAgB,iBAAiB,CAC7B,KAAQ;IAER,IAAI,CAAC,gBAAgB,EAAE,CAAC;QACpB,MAAM,IAAI,KAAK,CACX,0EAA0E,CAC7E,CAAC;IACN,CAAC;IACD,OAAO,IAAA,4BAAgB,EAAC,KAAK,EAAE,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,CAAC,CAAC;AAC7E,CAAC;AAWD,SAAgB,8BAA8B,CAI1C,SAAgC,EAChC,QAAa,EACb,iBAA0B,EAC1B,OAAuB;IAEvB,IAAI,CAAC,gBAAgB,EAAE,CAAC;QACpB,MAAM,IAAI,KAAK,CACX,0EAA0E,CAC7E,CAAC;IACN,CAAC;IAED,OAAO,IAAA,yCAA6B,EAAC,SAAS,EAAE,QAAQ,EAAE,iBAAiB,EAAE;QACzE,kBAAkB,EAAE,gBAAgB;QACpC,GAAG,OAAO;KACb,CAAC,CAAC;AACP,CAAC","sourcesContent":["import { Connection, createConnection } from 'mongoose';\r\nimport {getDiscriminatorModelForClass, getModelForClass, ReturnModelType} from '@typegoose/typegoose';\r\nimport {AnyParamConstructor, IModelOptions} from \"@typegoose/typegoose/lib/types\";\r\n\r\nlet globalConnection: Connection | undefined;\r\n\r\nexport async function initGlobalConnection(uri: string, environment: string) {\r\n if (!globalConnection) {\r\n globalConnection = createConnection(uri, {\r\n dbName: `lyxa-${environment}-global`,\r\n });\r\n }\r\n return globalConnection;\r\n}\r\n\r\n/**\r\n * Creates a Typegoose model from a class (with a single, global connection).\r\n */\r\nexport function createGlobalModel<T extends AnyParamConstructor<any>>(\r\n Class: T\r\n): ReturnModelType<T> {\r\n if (!globalConnection) {\r\n throw new Error(\r\n 'Global connection not initialized. Call initGlobalConnection(...) first.'\r\n );\r\n }\r\n return getModelForClass(Class, { existingConnection: globalConnection });\r\n}\r\n\r\n/**\r\n * Creates a Typegoose *discriminator* model from a base model,\r\n * using a derived sub-class & optional discriminator value.\r\n *\r\n * @param baseModel The ReturnModelType (model) for the base class\r\n * @param subClass The derived class constructor\r\n * @param discriminatorName A string to label this sub-class (e.g. \"DOG\")\r\n * @param options Additional model options\r\n */\r\nexport function createGlobalDiscriminatorModel<\r\n Base extends AnyParamConstructor<any>,\r\n Sub extends AnyParamConstructor<any>,\r\n>(\r\n baseModel: ReturnModelType<Base>,\r\n subClass: Sub,\r\n discriminatorName?: string,\r\n options?: IModelOptions,\r\n): ReturnModelType<Sub> {\r\n if (!globalConnection) {\r\n throw new Error(\r\n 'Global connection not initialized. Call initGlobalConnection(...) first.',\r\n );\r\n }\r\n\r\n return getDiscriminatorModelForClass(baseModel, subClass, discriminatorName, {\r\n existingConnection: globalConnection,\r\n ...options,\r\n });\r\n}\r\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"/","sources":["libraries/mongo/index.ts"],"names":[],"mappings":";;AAUA,oDAOC;AAKD,8CASC;AAWD,wEAmBC;AA7DD,uCAAwD;AACxD,oDAAsG;AAGtG,qEAAqE;AAGrE,IAAA,0CAAqB,GAAE,CAAC;AACxB,IAAI,gBAAwC,CAAC;AAEtC,KAAK,UAAU,oBAAoB,CAAC,GAAW,EAAE,WAAmB;IACvE,IAAI,CAAC,gBAAgB,EAAE,CAAC;QACpB,gBAAgB,GAAG,IAAA,2BAAgB,EAAC,GAAG,EAAE;YACrC,MAAM,EAAE,QAAQ,WAAW,SAAS;SACvC,CAAC,CAAC;IACP,CAAC;IACD,OAAO,gBAAgB,CAAC;AAC5B,CAAC;AAKD,SAAgB,iBAAiB,CAC7B,KAAQ;IAER,IAAI,CAAC,gBAAgB,EAAE,CAAC;QACpB,MAAM,IAAI,KAAK,CACX,0EAA0E,CAC7E,CAAC;IACN,CAAC;IACD,OAAO,IAAA,4BAAgB,EAAC,KAAK,EAAE,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,CAAC,CAAC;AAC7E,CAAC;AAWD,SAAgB,8BAA8B,CAI1C,SAAgC,EAChC,QAAa,EACb,iBAA0B,EAC1B,OAAuB;IAEvB,IAAI,CAAC,gBAAgB,EAAE,CAAC;QACpB,MAAM,IAAI,KAAK,CACX,0EAA0E,CAC7E,CAAC;IACN,CAAC;IAED,OAAO,IAAA,yCAA6B,EAAC,SAAS,EAAE,QAAQ,EAAE,iBAAiB,EAAE;QACzE,kBAAkB,EAAE,gBAAgB;QACpC,GAAG,OAAO;KACb,CAAC,CAAC;AACP,CAAC","sourcesContent":["import { Connection, createConnection } from 'mongoose';\r\nimport {getDiscriminatorModelForClass, getModelForClass, ReturnModelType} from '@typegoose/typegoose';\r\nimport {AnyParamConstructor, IModelOptions} from \"@typegoose/typegoose/lib/types\";\r\n\r\nimport { applySoftDeletePlugin } from './plugins/soft-delete-plugin';\r\n\r\n// Apply the soft delete plugin globally before any connections or models\r\napplySoftDeletePlugin();\r\nlet globalConnection: Connection | undefined;\r\n\r\nexport async function initGlobalConnection(uri: string, environment: string) {\r\n if (!globalConnection) {\r\n globalConnection = createConnection(uri, {\r\n dbName: `lyxa-${environment}-global`,\r\n });\r\n }\r\n return globalConnection;\r\n}\r\n\r\n/**\r\n * Creates a Typegoose model from a class (with a single, global connection).\r\n */\r\nexport function createGlobalModel<T extends AnyParamConstructor<any>>(\r\n Class: T\r\n): ReturnModelType<T> {\r\n if (!globalConnection) {\r\n throw new Error(\r\n 'Global connection not initialized. Call initGlobalConnection(...) first.'\r\n );\r\n }\r\n return getModelForClass(Class, { existingConnection: globalConnection });\r\n}\r\n\r\n/**\r\n * Creates a Typegoose *discriminator* model from a base model,\r\n * using a derived sub-class & optional discriminator value.\r\n *\r\n * @param baseModel The ReturnModelType (model) for the base class\r\n * @param subClass The derived class constructor\r\n * @param discriminatorName A string to label this sub-class (e.g. \"DOG\")\r\n * @param options Additional model options\r\n */\r\nexport function createGlobalDiscriminatorModel<\r\n Base extends AnyParamConstructor<any>,\r\n Sub extends AnyParamConstructor<any>,\r\n>(\r\n baseModel: ReturnModelType<Base>,\r\n subClass: Sub,\r\n discriminatorName?: string,\r\n options?: IModelOptions,\r\n): ReturnModelType<Sub> {\r\n if (!globalConnection) {\r\n throw new Error(\r\n 'Global connection not initialized. Call initGlobalConnection(...) first.',\r\n );\r\n }\r\n\r\n return getDiscriminatorModelForClass(baseModel, subClass, discriminatorName, {\r\n existingConnection: globalConnection,\r\n ...options,\r\n });\r\n}\r\n"]}
@@ -14,7 +14,7 @@ export declare class HolidayHour {
14
14
  status: HolidayWorkStatus;
15
15
  closingHour?: StartEndTime[];
16
16
  }
17
- export declare class WrokHourSetting {
17
+ export declare class WorkHourSetting {
18
18
  normalHours?: NormalHour[];
19
19
  holidayHours?: HolidayHour[];
20
20
  }
@@ -9,7 +9,7 @@ var __metadata = (this && this.__metadata) || function (k, v) {
9
9
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.WrokHourSetting = exports.HolidayHour = exports.NormalHour = void 0;
12
+ exports.WorkHourSetting = exports.HolidayHour = exports.NormalHour = void 0;
13
13
  const typegoose_1 = require("@typegoose/typegoose");
14
14
  const enum_1 = require("../../../utilities/enum");
15
15
  class StartEndTime {
@@ -60,17 +60,17 @@ __decorate([
60
60
  (0, typegoose_1.prop)({ type: StartEndTime }),
61
61
  __metadata("design:type", Array)
62
62
  ], HolidayHour.prototype, "closingHour", void 0);
63
- class WrokHourSetting {
63
+ class WorkHourSetting {
64
64
  normalHours;
65
65
  holidayHours;
66
66
  }
67
- exports.WrokHourSetting = WrokHourSetting;
67
+ exports.WorkHourSetting = WorkHourSetting;
68
68
  __decorate([
69
69
  (0, typegoose_1.prop)({ type: () => [NormalHour], default: [] }),
70
70
  __metadata("design:type", Array)
71
- ], WrokHourSetting.prototype, "normalHours", void 0);
71
+ ], WorkHourSetting.prototype, "normalHours", void 0);
72
72
  __decorate([
73
73
  (0, typegoose_1.prop)({ type: () => [HolidayHour], default: [] }),
74
74
  __metadata("design:type", Array)
75
- ], WrokHourSetting.prototype, "holidayHours", void 0);
75
+ ], WorkHourSetting.prototype, "holidayHours", void 0);
76
76
  //# sourceMappingURL=work-hour.model.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"work-hour.model.js","sourceRoot":"/","sources":["libraries/mongo/models/work-hour.model.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,oDAA4C;AAC5C,kDAA8D;AAE9D,MAAM,YAAY;IAEV,KAAK,CAAU;IAGf,GAAG,CAAU;CACpB;AAJO;IADN,IAAA,gBAAI,EAAC,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;;2CACD;AAGf;IADN,IAAA,gBAAI,EAAC,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;;yCACH;AAGrB,MAAa,UAAU;IAEf,GAAG,CAAW;IAGd,MAAM,CAAc;IAGpB,YAAY,CAAkB;CACrC;AATD,gCASC;AAPO;IADN,IAAA,gBAAI,EAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,cAAO,EAAE,CAAC;;uCAC/C;AAGd;IADN,IAAA,gBAAI,EAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,iBAAU,EAAE,CAAC;;0CAC9B;AAGpB;IADN,IAAA,gBAAI,EAAC,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC,CAAC,YAAY,CAAC,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC;;gDACb;AAKtC,MAAa,WAAW;IAEhB,IAAI,CAAQ;IAGZ,MAAM,CAAqB;IAG3B,WAAW,CAAkB;CACpC;AATD,kCASC;AAPO;IADN,IAAA,gBAAI,EAAC,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;8BACP,IAAI;yCAAC;AAGZ;IADN,IAAA,gBAAI,EAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,iBAAU,CAAC,MAAM,EAAE,iBAAU,CAAC,QAAQ,CAAC,EAAE,CAAC;;2CACrD;AAG3B;IADN,IAAA,gBAAI,EAAC,EAAE,IAAI,EAAE,YAAY,EAAE,CAAC;;gDACO;AAGrC,MAAa,eAAe;IAEpB,WAAW,CAAgB;IAG3B,YAAY,CAAiB;CACpC;AAND,0CAMC;AAJO;IADN,IAAA,gBAAI,EAAC,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC,CAAC,UAAU,CAAC,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC;;oDACd;AAG3B;IADN,IAAA,gBAAI,EAAC,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC,CAAC,WAAW,CAAC,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC;;qDACb","sourcesContent":["import { prop } from \"@typegoose/typegoose\";\r\nimport { WeekDay, WorkStatus } from \"../../../utilities/enum\";\r\n\r\nclass StartEndTime {\r\n\t@prop({ type: String })\r\n\tpublic start?: string;\r\n\r\n\t@prop({ type: String })\r\n\tpublic end?: string;\r\n}\r\n\r\nexport class NormalHour {\r\n\t@prop({ required: true, unique: true, type: Number, enum: WeekDay })\r\n\tpublic day!: WeekDay;\r\n\r\n\t@prop({ required: true, type: String, enum: WorkStatus })\r\n\tpublic status!: WorkStatus;\r\n\r\n\t@prop({ type: () => [StartEndTime], default: [] })\r\n\tpublic openingHours?: StartEndTime[];\r\n}\r\n\r\ntype HolidayWorkStatus = Exclude<WorkStatus, WorkStatus.OPEN>;\r\n\r\nexport class HolidayHour {\r\n\t@prop({ type: Date })\r\n\tpublic date?: Date;\r\n\r\n\t@prop({ required: true, type: String, enum: [WorkStatus.CLOSED, WorkStatus.FULL_DAY] })\r\n\tpublic status!: HolidayWorkStatus;\r\n\r\n\t@prop({ type: StartEndTime })\r\n\tpublic closingHour?: StartEndTime[];\r\n}\r\n\r\nexport class WrokHourSetting {\r\n\t@prop({ type: () => [NormalHour], default: [] })\r\n\tpublic normalHours?: NormalHour[];\r\n\r\n\t@prop({ type: () => [HolidayHour], default: [] })\r\n\tpublic holidayHours?: HolidayHour[];\r\n}"]}
1
+ {"version":3,"file":"work-hour.model.js","sourceRoot":"/","sources":["libraries/mongo/models/work-hour.model.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,oDAA4C;AAC5C,kDAA8D;AAE9D,MAAM,YAAY;IAEV,KAAK,CAAU;IAGf,GAAG,CAAU;CACpB;AAJO;IADN,IAAA,gBAAI,EAAC,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;;2CACD;AAGf;IADN,IAAA,gBAAI,EAAC,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;;yCACH;AAGrB,MAAa,UAAU;IAEf,GAAG,CAAW;IAGd,MAAM,CAAc;IAGpB,YAAY,CAAkB;CACrC;AATD,gCASC;AAPO;IADN,IAAA,gBAAI,EAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,cAAO,EAAE,CAAC;;uCAC/C;AAGd;IADN,IAAA,gBAAI,EAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,iBAAU,EAAE,CAAC;;0CAC9B;AAGpB;IADN,IAAA,gBAAI,EAAC,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC,CAAC,YAAY,CAAC,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC;;gDACb;AAKtC,MAAa,WAAW;IAEhB,IAAI,CAAQ;IAGZ,MAAM,CAAqB;IAG3B,WAAW,CAAkB;CACpC;AATD,kCASC;AAPO;IADN,IAAA,gBAAI,EAAC,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;8BACP,IAAI;yCAAC;AAGZ;IADN,IAAA,gBAAI,EAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,iBAAU,CAAC,MAAM,EAAE,iBAAU,CAAC,QAAQ,CAAC,EAAE,CAAC;;2CACrD;AAG3B;IADN,IAAA,gBAAI,EAAC,EAAE,IAAI,EAAE,YAAY,EAAE,CAAC;;gDACO;AAGrC,MAAa,eAAe;IAEpB,WAAW,CAAgB;IAG3B,YAAY,CAAiB;CACpC;AAND,0CAMC;AAJO;IADN,IAAA,gBAAI,EAAC,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC,CAAC,UAAU,CAAC,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC;;oDACd;AAG3B;IADN,IAAA,gBAAI,EAAC,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC,CAAC,WAAW,CAAC,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC;;qDACb","sourcesContent":["import { prop } from \"@typegoose/typegoose\";\r\nimport { WeekDay, WorkStatus } from \"../../../utilities/enum\";\r\n\r\nclass StartEndTime {\r\n\t@prop({ type: String })\r\n\tpublic start?: string;\r\n\r\n\t@prop({ type: String })\r\n\tpublic end?: string;\r\n}\r\n\r\nexport class NormalHour {\r\n\t@prop({ required: true, unique: true, type: Number, enum: WeekDay })\r\n\tpublic day!: WeekDay;\r\n\r\n\t@prop({ required: true, type: String, enum: WorkStatus })\r\n\tpublic status!: WorkStatus;\r\n\r\n\t@prop({ type: () => [StartEndTime], default: [] })\r\n\tpublic openingHours?: StartEndTime[];\r\n}\r\n\r\ntype HolidayWorkStatus = Exclude<WorkStatus, WorkStatus.OPEN>;\r\n\r\nexport class HolidayHour {\r\n\t@prop({ type: Date })\r\n\tpublic date?: Date;\r\n\r\n\t@prop({ required: true, type: String, enum: [WorkStatus.CLOSED, WorkStatus.FULL_DAY] })\r\n\tpublic status!: HolidayWorkStatus;\r\n\r\n\t@prop({ type: StartEndTime })\r\n\tpublic closingHour?: StartEndTime[];\r\n}\r\n\r\nexport class WorkHourSetting {\r\n\t@prop({ type: () => [NormalHour], default: [] })\r\n\tpublic normalHours?: NormalHour[];\r\n\r\n\t@prop({ type: () => [HolidayHour], default: [] })\r\n\tpublic holidayHours?: HolidayHour[];\r\n}\r\n"]}
@@ -0,0 +1,25 @@
1
+ import { Schema, Model } from 'mongoose';
2
+ import { ReturnModelType } from '@typegoose/typegoose';
3
+ import { AnyParamConstructor } from '@typegoose/typegoose/lib/types';
4
+ export interface SoftDeleteModel<T> extends Model<T> {
5
+ softDelete(id: string): Promise<any>;
6
+ softDeleteMany(filter?: any): Promise<any>;
7
+ restore(id: string): Promise<any>;
8
+ restoreMany(filter?: any): Promise<any>;
9
+ findWithDeleted(filter?: any): any;
10
+ findDeleted(filter?: any): any;
11
+ }
12
+ export declare class SoftDeleteBase {
13
+ deletedAt?: Date | null;
14
+ }
15
+ export declare class SoftDelete {
16
+ static applyToSchema(schema: Schema): void;
17
+ static applyGlobally(): void;
18
+ static createModel<T extends SoftDeleteBase>(modelClass: AnyParamConstructor<T>): SoftDeleteModel<T> & ReturnModelType<AnyParamConstructor<T>>;
19
+ private static addQueryMiddleware;
20
+ private static addInstanceMethods;
21
+ private static addStaticMethods;
22
+ }
23
+ export declare const softDeletePlugin: (schema: Schema) => void;
24
+ export declare const applySoftDeletePlugin: () => void;
25
+ export declare const createSoftDeleteModel: <T extends SoftDeleteBase>(modelClass: AnyParamConstructor<T>) => SoftDeleteModel<T> & ReturnModelType<AnyParamConstructor<T>>;
@@ -0,0 +1,90 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createSoftDeleteModel = exports.applySoftDeletePlugin = exports.softDeletePlugin = exports.SoftDelete = exports.SoftDeleteBase = void 0;
4
+ const typegoose_1 = require("@typegoose/typegoose");
5
+ class SoftDeleteBase {
6
+ deletedAt;
7
+ }
8
+ exports.SoftDeleteBase = SoftDeleteBase;
9
+ class SoftDelete {
10
+ static applyToSchema(schema) {
11
+ if (!schema.path('deletedAt')) {
12
+ schema.add({
13
+ deletedAt: {
14
+ type: Date,
15
+ default: null,
16
+ index: true,
17
+ },
18
+ });
19
+ }
20
+ this.addQueryMiddleware(schema);
21
+ this.addInstanceMethods(schema);
22
+ this.addStaticMethods(schema);
23
+ }
24
+ static applyGlobally() {
25
+ const mongoose = require('mongoose');
26
+ mongoose.plugin((schema) => this.applyToSchema(schema));
27
+ }
28
+ static createModel(modelClass) {
29
+ const model = (0, typegoose_1.getModelForClass)(modelClass);
30
+ return model;
31
+ }
32
+ static addQueryMiddleware(schema) {
33
+ const queryMiddleware = function () {
34
+ if (!this.getQuery().deletedAt) {
35
+ this.where({ deletedAt: null });
36
+ }
37
+ };
38
+ schema.pre('find', queryMiddleware);
39
+ schema.pre('findOne', queryMiddleware);
40
+ schema.pre('findOneAndUpdate', queryMiddleware);
41
+ schema.pre('findOneAndDelete', queryMiddleware);
42
+ schema.pre('findOneAndReplace', queryMiddleware);
43
+ schema.pre('updateOne', queryMiddleware);
44
+ schema.pre('updateMany', queryMiddleware);
45
+ schema.pre('count', queryMiddleware);
46
+ schema.pre('countDocuments', queryMiddleware);
47
+ schema.statics.findById = function (id, projection, options) {
48
+ return this.findOne({ _id: id, deletedAt: null }, projection, options);
49
+ };
50
+ }
51
+ static addInstanceMethods(schema) {
52
+ schema.methods.softDelete = function () {
53
+ this.deletedAt = new Date();
54
+ return this.save();
55
+ };
56
+ schema.methods.restore = function () {
57
+ this.deletedAt = null;
58
+ return this.save();
59
+ };
60
+ }
61
+ static addStaticMethods(schema) {
62
+ schema.statics.softDelete = async function (id) {
63
+ const result = await this.updateOne({ _id: id }, { deletedAt: new Date() });
64
+ return result.modifiedCount > 0;
65
+ };
66
+ schema.statics.softDeleteMany = function (filter = {}) {
67
+ return this.updateMany(filter, { deletedAt: new Date() });
68
+ };
69
+ schema.statics.restore = function (id) {
70
+ return this.updateOne({ _id: id }, { deletedAt: null });
71
+ };
72
+ schema.statics.restoreMany = function (filter = {}) {
73
+ return this.updateMany(filter, { deletedAt: null });
74
+ };
75
+ schema.statics.findWithDeleted = function (filter = {}) {
76
+ return this.find(filter);
77
+ };
78
+ schema.statics.findDeleted = function (filter = {}) {
79
+ return this.find({ ...filter, deletedAt: { $ne: null } });
80
+ };
81
+ }
82
+ }
83
+ exports.SoftDelete = SoftDelete;
84
+ const softDeletePlugin = (schema) => SoftDelete.applyToSchema(schema);
85
+ exports.softDeletePlugin = softDeletePlugin;
86
+ const applySoftDeletePlugin = () => SoftDelete.applyGlobally();
87
+ exports.applySoftDeletePlugin = applySoftDeletePlugin;
88
+ const createSoftDeleteModel = (modelClass) => SoftDelete.createModel(modelClass);
89
+ exports.createSoftDeleteModel = createSoftDeleteModel;
90
+ //# sourceMappingURL=soft-delete-plugin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"soft-delete-plugin.js","sourceRoot":"/","sources":["libraries/mongo/plugins/soft-delete-plugin.ts"],"names":[],"mappings":";;;AACA,oDAAyE;AAkBzE,MAAa,cAAc;IACzB,SAAS,CAAe;CACzB;AAFD,wCAEC;AAKD,MAAa,UAAU;IAKd,MAAM,CAAC,aAAa,CAAC,MAAc;QAExC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC;YAC9B,MAAM,CAAC,GAAG,CAAC;gBACT,SAAS,EAAE;oBACT,IAAI,EAAE,IAAI;oBACV,OAAO,EAAE,IAAI;oBACb,KAAK,EAAE,IAAI;iBACZ;aACF,CAAC,CAAC;QACL,CAAC;QAGD,IAAI,CAAC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E,GAAG,EAAE,EAAE,EAAE,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;QAC1D,CAAC,CAAC;QAEF,MAAM,CAAC,OAAO,CAAC,WAAW,GAAG,UAAS,MAAM,GAAG,EAAE;YAC/C,OAAO,IAAI,CAAC,UAAU,CAAC,MAAM,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;QACtD,CAAC,CAAC;QAEF,MAAM,CAAC,OAAO,CAAC,eAAe,GAAG,UAAS,MAAM,GAAG,EAAE;YACnD,OAAO,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QAC3B,CAAC,CAAC;QAEF,MAAM,CAAC,OAAO,CAAC,WAAW,GAAG,UAAS,MAAM,GAAG,EAAE;YAC/C,OAAO,IAAI,CAAC,IAAI,CAAC,EAAE,GAAG,MAAM,EAAE,SAAS,EAAE,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,CAAC,CAAC;QAC5D,CAAC,CAAC;IACJ,CAAC;CACF;AA3HD,gCA2HC;AAGM,MAAM,gBAAgB,GAAG,CAAC,MAAc,EAAQ,EAAE,CAAC,UAAU,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC;AAA9E,QAAA,gBAAgB,oBAA8D;AACpF,MAAM,qBAAqB,GAAG,GAAS,EAAE,CAAC,UAAU,CAAC,aAAa,EAAE,CAAC;AAA/D,QAAA,qBAAqB,yBAA0C;AACrE,MAAM,qBAAqB,GAAG,CACnC,UAAkC,EAC4B,EAAE,CAAC,UAAU,CAAC,WAAW,CAAC,UAAU,CAAC,CAAC;AAFzF,QAAA,qBAAqB,yBAEoE","sourcesContent":["import { Schema, Query, Model } from 'mongoose';\r\nimport { getModelForClass, ReturnModelType } from '@typegoose/typegoose';\r\nimport { AnyParamConstructor } from '@typegoose/typegoose/lib/types';\r\n\r\n/**\r\n * Interface for models with soft delete capabilities\r\n */\r\nexport interface SoftDeleteModel<T> extends Model<T> {\r\n softDelete(id: string): Promise<any>;\r\n softDeleteMany(filter?: any): Promise<any>;\r\n restore(id: string): Promise<any>;\r\n restoreMany(filter?: any): Promise<any>;\r\n findWithDeleted(filter?: any): any;\r\n findDeleted(filter?: any): any;\r\n}\r\n\r\n/**\r\n * Base class for models with soft delete functionality\r\n */\r\nexport class SoftDeleteBase {\r\n deletedAt?: Date | null;\r\n}\r\n\r\n/**\r\n * SoftDelete class providing soft deletion functionality for mongoose models\r\n */\r\nexport class SoftDelete {\r\n /**\r\n * Apply soft delete plugin to a specific schema\r\n * @param schema Mongoose schema to enhance with soft delete functionality\r\n */\r\n public static applyToSchema(schema: Schema): void {\r\n // Add deletedAt field if it doesn't exist\r\n if (!schema.path('deletedAt')) {\r\n schema.add({\r\n deletedAt: {\r\n type: Date,\r\n default: null,\r\n index: true,\r\n },\r\n });\r\n }\r\n\r\n // Add schema middleware\r\n this.addQueryMiddleware(schema);\r\n \r\n // Add instance methods\r\n this.addInstanceMethods(schema);\r\n \r\n // Add static methods\r\n this.addStaticMethods(schema);\r\n }\r\n\r\n /**\r\n * Apply soft delete plugin globally to all mongoose schemas\r\n */\r\n public static applyGlobally(): void {\r\n const mongoose = require('mongoose');\r\n mongoose.plugin((schema: Schema) => this.applyToSchema(schema));\r\n }\r\n\r\n /**\r\n * Create a model with soft delete capabilities and proper TypeScript types\r\n * @param modelClass The class to create a model from\r\n * @returns A model with soft delete functionality\r\n */\r\n public static createModel<T extends SoftDeleteBase>(\r\n modelClass: AnyParamConstructor<T>\r\n ): SoftDeleteModel<T> & ReturnModelType<AnyParamConstructor<T>> {\r\n const model = getModelForClass(modelClass);\r\n return model as any; // The plugin adds the methods, we just need to tell TypeScript they exist\r\n }\r\n\r\n /**\r\n * Add query middleware to filter out soft-deleted documents\r\n * @param schema Schema to add middleware to\r\n */\r\n private static addQueryMiddleware(schema: Schema): void {\r\n const queryMiddleware = function(this: Query<any, any>) {\r\n if (!this.getQuery().deletedAt) {\r\n this.where({ deletedAt: null });\r\n }\r\n };\r\n\r\n // Apply middleware to relevant query methods\r\n schema.pre('find', queryMiddleware);\r\n schema.pre('findOne', queryMiddleware);\r\n schema.pre('findOneAndUpdate', queryMiddleware);\r\n schema.pre('findOneAndDelete', queryMiddleware);\r\n schema.pre('findOneAndReplace', queryMiddleware);\r\n schema.pre('updateOne', queryMiddleware);\r\n schema.pre('updateMany', queryMiddleware);\r\n // TypeScript workaround for count hook\r\n (schema as any).pre('count', queryMiddleware);\r\n schema.pre('countDocuments', queryMiddleware);\r\n\r\n // Override findById to respect soft delete\r\n schema.statics.findById = function(id: any, projection?: any, options?: any) {\r\n return this.findOne({ _id: id, deletedAt: null }, projection, options);\r\n };\r\n }\r\n\r\n /**\r\n * Add instance methods for soft delete operations\r\n * @param schema Schema to add methods to\r\n */\r\n private static addInstanceMethods(schema: Schema): void {\r\n schema.methods.softDelete = function() {\r\n this.deletedAt = new Date();\r\n return this.save();\r\n };\r\n\r\n schema.methods.restore = function() {\r\n this.deletedAt = null;\r\n return this.save();\r\n };\r\n }\r\n\r\n /**\r\n * Add static methods for soft delete operations\r\n * @param schema Schema to add methods to\r\n */\r\n private static addStaticMethods(schema: Schema): void {\r\n schema.statics.softDelete = async function(id: string) {\r\n \r\n const result = await this.updateOne({ _id: id }, { deletedAt: new Date() });\r\n return result.modifiedCount > 0;\r\n };\r\n\r\n schema.statics.softDeleteMany = function(filter = {}) {\r\n return this.updateMany(filter, { deletedAt: new Date() });\r\n };\r\n\r\n schema.statics.restore = function(id: string) {\r\n return this.updateOne({ _id: id }, { deletedAt: null });\r\n };\r\n\r\n schema.statics.restoreMany = function(filter = {}) {\r\n return this.updateMany(filter, { deletedAt: null });\r\n };\r\n\r\n schema.statics.findWithDeleted = function(filter = {}) {\r\n return this.find(filter);\r\n };\r\n\r\n schema.statics.findDeleted = function(filter = {}) {\r\n return this.find({ ...filter, deletedAt: { $ne: null } });\r\n };\r\n }\r\n}\r\n\r\n// Export convenience functions with the same names as before for backward compatibility\r\nexport const softDeletePlugin = (schema: Schema): void => SoftDelete.applyToSchema(schema);\r\nexport const applySoftDeletePlugin = (): void => SoftDelete.applyGlobally();\r\nexport const createSoftDeleteModel = <T extends SoftDeleteBase>(\r\n modelClass: AnyParamConstructor<T>\r\n): SoftDeleteModel<T> & ReturnModelType<AnyParamConstructor<T>> => SoftDelete.createModel(modelClass);"]}
@@ -19,7 +19,7 @@ let RedisService = class RedisService {
19
19
  _redisClient;
20
20
  constructor(redisURL) {
21
21
  this._redisClient = new ioredis_1.default(redisURL);
22
- this._redisClient.connect(() => console.error(""));
22
+ this._redisClient.connect().then(r => console.log("Connected to Redis")).catch(e => console.log("Error whilst connecting to redis: " + e));
23
23
  }
24
24
  get redisClient() {
25
25
  return this._redisClient;
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"/","sources":["libraries/redis/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,sDAA2B;AAC3B,mCAA+B;AAGxB,IAAM,YAAY,GAAlB,MAAM,YAAY;IACb,YAAY,CAAS;IAE7B,YAAY,QAAgB;QACxB,IAAI,CAAC,YAAY,GAAG,IAAI,iBAAK,CAAC,QAAQ,CAAC,CAAC;QACxC,IAAI,CAAC,YAAY,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,CAAA;IACtD,CAAC;IAED,IAAI,WAAW;QACX,OAAO,IAAI,CAAC,YAAY,CAAC;IAC7B,CAAC;IAEM,KAAK,CAAC,eAAe,CAAI,GAAW;QACvC,MAAM,aAAa,GAAG,MAAM,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,GAAG,CAAC,CAAA;QAEtD,IAAG,aAAa,IAAI,SAAS,EAAE,CAAC;YAC5B,OAAO,IAAI,CAAC,KAAK,CAAC,aAAa,CAAM,CAAA;QACzC,CAAC;QAED,OAAO,SAAS,CAAC;IACrB,CAAC;IAEM,KAAK,CAAC,WAAW,CAAI,GAAW,EAAE,MAAS,EAAE,MAAe;QAC/D,MAAM,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G,CAAC,OAAO,CAAC,WAAW,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,WAAW,EAAE,CAAC;IAC3E,CAAC;CACJ,CAAA;AAhEY,oCAAY;uBAAZ,YAAY;IADxB,IAAA,gBAAO,GAAE;;GACG,YAAY,CAgExB","sourcesContent":["import Redis from \"ioredis\"\r\nimport {Service} from \"typedi\";\r\n\r\n@Service()\r\nexport class RedisService {\r\n private _redisClient!: Redis;\r\n\r\n constructor(redisURL: string) {\r\n this._redisClient = new Redis(redisURL);\r\n this._redisClient.connect(() => console.error(\"\"))\r\n }\r\n\r\n get redisClient(): Redis {\r\n return this._redisClient;\r\n }\r\n\r\n public async getCachedObject<T>(key: string): Promise<T | undefined> {\r\n const usageResponse = await this._redisClient.get(key)\r\n\r\n if(usageResponse != undefined) {\r\n return JSON.parse(usageResponse) as T\r\n }\r\n\r\n return undefined;\r\n }\r\n\r\n public async cacheObject<T>(key: string, object: T, expiry?: number): Promise<boolean> {\r\n const stringifiedObject = JSON.stringify(object);\r\n\r\n if(expiry) {\r\n await this._redisClient.setex(key, expiry, stringifiedObject)\r\n } else {\r\n await this._redisClient.set(key, stringifiedObject)\r\n }\r\n\r\n return true;\r\n }\r\n\r\n public async deleteCachedObject(key: string): Promise<boolean> {\r\n await this._redisClient.del(key);\r\n return true;\r\n }\r\n\r\n public async getCachedObjectByGroup<T>(group: string, key: string): Promise<T | undefined> {\r\n const usageResponse = await this._redisClient.hget(group, key)\r\n\r\n if(usageResponse != undefined) {\r\n return JSON.parse(usageResponse) as T\r\n }\r\n\r\n return undefined;\r\n }\r\n\r\n public async setCachedObjectByGroup<T>(group: string, key: string, object: T): Promise<boolean> {\r\n const stringifiedObject = JSON.stringify(object);\r\n await this._redisClient.hset(group, key, stringifiedObject)\r\n\r\n return true;\r\n }\r\n\r\n public async deleteCachedObjectByGroup<T>(group: string, key: string): Promise<boolean> {\r\n await this._redisClient.hdel(group, key)\r\n return true;\r\n }\r\n\r\n public sanitizeKey(key: string) {\r\n return key.replace(/[^\\w\\s]/gi, '').replace(/\\s+/g, '-').toLowerCase();\r\n }\r\n}\r\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"/","sources":["libraries/redis/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,sDAA2B;AAC3B,mCAA+B;AAGxB,IAAM,YAAY,GAAlB,MAAM,YAAY;IACb,YAAY,CAAS;IAE7B,YAAY,QAAgB;QACxB,IAAI,CAAC,YAAY,GAAG,IAAI,iBAAK,CAAC,QAAQ,CAAC,CAAC;QACxC,IAAI,CAAC,YAAY,CAAC,OAAO,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,oBAAoB,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC,GAAG,CAC3F,oCAAoC,GAAG,CAAC,CAC3C,CAAC,CAAA;IACN,CAAC;IAED,IAAI,WAAW;QACX,OAAO,IAAI,CAAC,YAAY,CAAC;IAC7B,CAAC;IAEM,KAAK,CAAC,eAAe,CAAI,GAAW;QACvC,MAAM,aAAa,GAAG,MAAM,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,GAAG,CAAC,CAAA;QAEtD,IAAG,aAAa,IAAI,SAAS,EAAE,CAAC;YAC5B,OAAO,IAAI,CAAC,KAAK,CAAC,aAAa,CAAM,CAAA;QACzC,CAAC;QAED,OAAO,SAAS,CAAC;IACrB,CAAC;IAEM,KAAK,CAAC,WAAW,CAAI,GAAW,EAAE,MAAS,EAAE,MAAe;QAC/D,MAAM,iBAAiB,GAAG,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;QAEjD,IAAG,MAAM,EAAE,CAAC;YACR,MAAM,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,iBAAiB,CAAC,CAAA;QACjE,CAAC;aAAM,CAAC;YACJ,MAAM,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ent":["import Redis from \"ioredis\"\r\nimport {Service} from \"typedi\";\r\n\r\n@Service()\r\nexport class RedisService {\r\n private _redisClient!: Redis;\r\n\r\n constructor(redisURL: string) {\r\n this._redisClient = new Redis(redisURL);\r\n this._redisClient.connect().then(r => console.log(\"Connected to Redis\")).catch(e => console.log(\r\n \"Error whilst connecting to redis: \" + e\r\n ))\r\n }\r\n\r\n get redisClient(): Redis {\r\n return this._redisClient;\r\n }\r\n\r\n public async getCachedObject<T>(key: string): Promise<T | undefined> {\r\n const usageResponse = await this._redisClient.get(key)\r\n\r\n if(usageResponse != undefined) {\r\n return JSON.parse(usageResponse) as T\r\n }\r\n\r\n return undefined;\r\n }\r\n\r\n public async cacheObject<T>(key: string, object: T, expiry?: number): Promise<boolean> {\r\n const stringifiedObject = JSON.stringify(object);\r\n\r\n if(expiry) {\r\n await this._redisClient.setex(key, expiry, stringifiedObject)\r\n } else {\r\n await this._redisClient.set(key, stringifiedObject)\r\n }\r\n\r\n return true;\r\n }\r\n\r\n public async deleteCachedObject(key: string): Promise<boolean> {\r\n await this._redisClient.del(key);\r\n return true;\r\n }\r\n\r\n public async getCachedObjectByGroup<T>(group: string, key: string): Promise<T | undefined> {\r\n const usageResponse = await this._redisClient.hget(group, key)\r\n\r\n if(usageResponse != undefined) {\r\n return JSON.parse(usageResponse) as T\r\n }\r\n\r\n return undefined;\r\n }\r\n\r\n public async setCachedObjectByGroup<T>(group: string, key: string, object: T): Promise<boolean> {\r\n const stringifiedObject = JSON.stringify(object);\r\n await this._redisClient.hset(group, key, stringifiedObject)\r\n\r\n return true;\r\n }\r\n\r\n public async deleteCachedObjectByGroup<T>(group: string, key: string): Promise<boolean> {\r\n await this._redisClient.hdel(group, key)\r\n return true;\r\n }\r\n\r\n public sanitizeKey(key: string) {\r\n return key.replace(/[^\\w\\s]/gi, '').replace(/\\s+/g, '-').toLowerCase();\r\n }\r\n}\r\n"]}
@@ -35,6 +35,7 @@ let SecretManagerService = class SecretManagerService {
35
35
  }
36
36
  async getKey(key) {
37
37
  const environmentTransformedKey = this._configurationService.options.environment + "_" + key;
38
+ console.log("Attempting to fetch the following secret key: " + environmentTransformedKey);
38
39
  try {
39
40
  const data = await this._redisManager.getCachedObjectByGroup(this._configurationService.options.environment + "_KEYS", key);
40
41
  if (data != undefined) {
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"/","sources":["libraries/secrets/index.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,iEAAwE;AACxE,mCAA+B;AAC/B,oCAAsC;AACtC,oDAAsD;AAG/C,IAAM,oBAAoB,GAA1B,MAAM,oBAAoB;IACrB,qBAAqB,CAAwB;IAC7C,aAAa,CAAgB;IAC7B,OAAO,CAA8B;IAE7C,YAAY,oBAA0C,EAAE,YAA0B;QAC9E,IAAI,CAAC,qBAAqB,GAAG,oBAAoB,CAAC;QAClD,IAAI,CAAC,aAAa,GAAG,YAAY,CAAC;QAClC,IAAI,CAAC,OAAO,GAAG,IAAI,2CAA0B,CAAC;YAC1C,WAAW,EAAE;gBACT,SAAS,EAAE,uBAAuB;gBAClC,cAAc,EAAE,0CAA0C;gBAC1D,IAAI,EAAE,iBAAiB;gBACvB,eAAe,EAAE,gBAAgB;gBACjC,SAAS,EAAE,gBAAgB;gBAC3B,WAAW,EAAE,ssDAAssD;gBACntD,YAAY,EAAE,kDAAkD;aACnE;SACJ,CAAC,CAAA;IACN,CAAC;IAEM,KAAK,CAAC,MAAM,CAAC,GAAW;QAC3B,MAAM,yBAAyB,GAAG,IAAI,CAAC,qBAAqB,CAAC,OAAO,CAAC,WAAW,GAAG,GAAG,GAAG,GAAG,CAAC;QAE7F,IAAI,CAAC;YACD,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,aAAa,CAAC,sBAAsB,CAAS,IAAI,CAAC,qBAAqB,CAAC,OAAO,CAAC,WAAW,GAAG,OAAO,EAAE,GAAG,CAAC,CAAA;YAEnI,IAAG,IAAI,IAAI,SAAS,EAAE,CAAC;gBACnB,OAAO,IAAI,CAAA;YACf,CAAC;YAED,MAAM,CAAC,cAAc,CAAC,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,mBAAmB,CAAC;gBAC5D,IAAI,EAAE,gCAAgC,GAAG,yBAAyB,GAAG,kBAAkB;aAC1F,CAAC,CAAA;YAEF,MAAM,GAAG,GAAG,cAAc,CAAC,OAAQ,CAAC,IAAK,CAAC,QAAQ,EAAE,CAAA;YACpD,MAAM,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;YAE5B,OAAO,GAAG,CAAA;QACd,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACT,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;QACrB,CAAC;IACL,CAAC;IAEM,KAAK,CAAC,MAAM,CAAC,GAAW,EAAE,KAAa;QAC1C,MAAM,IAAI,CAAC,aAAa,CAAC,sBAAsB,CAAS,IAAI,CAAC,qBAAqB,CAAC,OAAO,CAAC,WAAW,GAAG,OAAO,EAAE,GAAG,EAAE,KAAK,CAAC,CAAA;QAC7H,OAAO,KAAK,CAAA;IAChB,CAAC;CAEJ,CAAA;AAjDY,oDAAoB;+BAApB,oBAAoB;IADhC,IAAA,gBAAO,GAAE;qCAM4B,oCAAoB,EAAgB,oBAAY;GALzE,oBAAoB,CAiDhC","sourcesContent":["\r\nimport {SecretManagerServiceClient} from \"@google-cloud/secret-manager\";\r\nimport {Service} from \"typedi\";\r\nimport {RedisService} from \"../redis\";\r\nimport {ConfigurationService} from \"../configuration\";\r\n\r\n@Service()\r\nexport class SecretManagerService {\r\n private _configurationService!: ConfigurationService;\r\n private _redisManager!: RedisService;\r\n private _client!: SecretManagerServiceClient;\r\n\r\n constructor(configurationService: ConfigurationService, redisManager: RedisService) {\r\n this._configurationService = configurationService;\r\n this._redisManager = redisManager;\r\n this._client = new SecretManagerServiceClient({\r\n credentials: {\r\n client_id: \"107840895824406590900\",\r\n private_key_id: \"ece1ebdfde57414700f23f1f4014f5e83d4f7644\",\r\n type: \"service_account\",\r\n universe_domain: \"googleapis.com\",\r\n projectId: \"for-poc-325210\",\r\n private_key: \"-----BEGIN PRIVATE KEY-----\\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDPTk9M5nCDYJhC\\nLuyP+gqBXIHPrXegygco5tB50Y7Q9s/f4hm+xp/usYy5UCYyFVNjZ2mdjWQcr3Ta\\nT3GZV9OiHej8ejveY0iyFBi0IlfGNm9blYlOIyQT4i6MoevNul7u4EQL8bid/sp/\\nJ/XPNC+Jnk8Ke2G9FdfDYs+1O6Nf37HuPUmMwLAzcyl+k1v9UzInrgNPj+nactY7\\nEPCVSM6XcZI3UL86n574iQBvUXsMpUt3csYVOxPap1Vd1TBEo1k85jZepMvaXHoK\\nJUwQT7p1F1D0weVKJ1BjwQgmADZWfUKdwRyS8zFPbUGeptlA2XlxyVMasGzCCMi4\\n6jzJGC81AgMBAAECggEAXoaLnDn7Fbym0I7K6T+PKLtAqaykPpnAOAM/DjzijR/t\\nW12idZ3l8RXeX+VO9UlKE6pkuyVsf7P1aVIOL2ifpG1U/kLSJ65HyINnXEPImCXc\\nEvuVdx6I5dQde5ydg9o2TV/PR0756njyZpaW+9sEzhB0ZAgsYeai0oGsyiuebCkm\\nqlOnf5DO/kWlNvf8yZ7GMEa0WBYyan4O7YcVF13c7oM19XZfvw+lliU/geOwVNW5\\nEfSn91UWIEMB60Q5XKHg11LAvbq8mvcHD+6ujeoPMfoZJrHZj5ucBP5auyRNFCUM\\nWE2IILLpgdhDfE5I323xHIyMblMSc1OOkZzjhuNYRQKBgQDuEa/jMqEDu7ZpDo/g\\nf+M4Qmmyh1WIjnORwqbf8INi5oN1NoIv6tcJ++COAWcBpyerW9aknLRMX9FXrNH5\\nAPyRvHQt2IpRCqjdcEr2b3VwZmcjRVbpsISwqE0RBvXSXOnvbDzZ53bC70anL5OY\\n7UYwOotbQXpcEGC57wy8G+VVlwKBgQDe63bcubV1W2+WPbdtzb7tzIS5PPz19U5i\\n5PjVQ4E34FH0ZBnk2v1fjtVxR72mrzCg2xz72rWgdsHJ/1QZAfw+4troJV9LI9SG\\nYRMeh86NSfNObdkY+LmCSH4eiFe83kFLUUzhnYE6DU/17i6T4V+ofawToasu3wag\\nf7LzT2BzEwKBgQDlVD5lktDOQtWtj+yC607bVAZzhrCbUfX8FFEh6ZL3A2zgzXhN\\nZmBtaqfew3URf47UICy894MrCyYi2gSOZCfoz2vu+egLt0QBw/lCOQ4dD1gM/u+B\\nP5wifI14eIb2dLCZBV/83F5n24zo4gjBSNfS/6Jcbs/KvbAfjCptTkX10wKBgDxb\\nwy5WtlRVcqxaf50ilWzr8I/7fH7YceYDG4EbKxTHD0m+BOjbhrlmAlMO2sIUM3WK\\nfpmPCZiuLyCTmuC+kd8xK5ap79h3libgh/2/ReUpvdBhm+PQDOLC4CtCPYdtIn7T\\nP57jN8dRLXJokIIIBw+nH32dS62AQ9oXWYvZ1UKzAoGBAOWOSphZMnPlLeLN54/4\\nwKPI+D6G1JhzqQrUf8Z99J7m3r3ya+0ug5gRGQCoSRfqz9o87+fLCdSdc38L+j4T\\nBnuwIcY6n4LF+3yAPIF1rnrIBFRqzPta7epYPXHtUTvWOkEkKzNmsFVCZKF7nQjS\\ns/ucyyfUssPsTznYW3gXf3To\\n-----END PRIVATE KEY-----\\n\",\r\n client_email: \"lyxa-core@for-poc-325210.iam.gserviceaccount.com\"\r\n }\r\n })\r\n }\r\n\r\n public async getKey(key: string): Promise<string | undefined> {\r\n const environmentTransformedKey = this._configurationService.options.environment + \"_\" + key;\r\n\r\n try {\r\n const data = await this._redisManager.getCachedObjectByGroup<string>(this._configurationService.options.environment + \"_KEYS\", key)\r\n\r\n if(data != undefined) {\r\n return data\r\n }\r\n\r\n const [accessResponse] = await this._client.accessSecretVersion({\r\n name: \"projects/899369746265/secrets/\" + environmentTransformedKey + \"/versions/latest\",\r\n })\r\n\r\n const val = accessResponse.payload!.data!.toString()\r\n await this.setKey(key, val);\r\n\r\n return val\r\n } catch (e) {\r\n console.error(e);\r\n }\r\n }\r\n\r\n public async setKey(key: string, value: string): Promise<string> {\r\n await this._redisManager.setCachedObjectByGroup<string>(this._configurationService.options.environment + \"_KEYS\", key, value)\r\n return value\r\n }\r\n\r\n}\r\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"/","sources":["libraries/secrets/index.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,iEAAwE;AACxE,mCAA+B;AAC/B,oCAAsC;AACtC,oDAAsD;AAG/C,IAAM,oBAAoB,GAA1B,MAAM,oBAAoB;IACrB,qBAAqB,CAAwB;IAC7C,aAAa,CAAgB;IAC7B,OAAO,CAA8B;IAE7C,YAAY,oBAA0C,EAAE,YAA0B;QAC9E,IAAI,CAAC,qBAAqB,GAAG,oBAAoB,CAAC;QAClD,IAAI,CAAC,aAAa,GAAG,YAAY,CAAC;QAClC,IAAI,CAAC,OAAO,GAAG,IAAI,2CAA0B,CAAC;YAC1C,WAAW,EAAE;gBACT,SAAS,EAAE,uBAAuB;gBAClC,cAAc,EAAE,0CAA0C;gBAC1D,IAAI,EAAE,iBAAiB;gBACvB,eAAe,EAAE,gBAAgB;gBACjC,SAAS,EAAE,gBAAgB;gBAC3B,WAAW,EAAE,ssDAAssD;gBACntD,YAAY,EAAE,kDAAkD;aACnE;SACJ,CAAC,CAAA;IACN,CAAC;IAEM,KAAK,CAAC,MAAM,CAAC,GAAW;QAC3B,MAAM,yBAAyB,GAAG,IAAI,CAAC,qBAAqB,CAAC,OAAO,CAAC,WAAW,GAAG,GAAG,GAAG,GAAG,CAAC;QAE7F,OAAO,CAAC,GAAG,CAAC,gDAAgD,GAAG,yBAAyB,CAAC,CAAC;QAE1F,IAAI,CAAC;YACD,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,aAAa,CAAC,sBAAsB,CAAS,IAAI,CAAC,qBAAqB,CAAC,OAAO,CAAC,WAAW,GAAG,OAAO,EAAE,GAAG,CAAC,CAAA;YAEnI,IAAG,IAAI,IAAI,SAAS,EAAE,CAAC;gBACnB,OAAO,IAAI,CAAA;YACf,CAAC;YAED,MAAM,CAAC,cAAc,CAAC,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,mBAAmB,CAAC;gBAC5D,IAAI,EAAE,gCAAgC,GAAG,yBAAyB,GAAG,kBAAkB;aAC1F,CAAC,CAAA;YAEF,MAAM,GAAG,GAAG,cAAc,CAAC,OAAQ,CAAC,IAAK,CAAC,QAAQ,EAAE,CAAA;YACpD,MAAM,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;YAE5B,OAAO,GAAG,CAAA;QACd,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACT,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;QACrB,CAAC;IACL,CAAC;IAEM,KAAK,CAAC,MAAM,CAAC,GAAW,EAAE,KAAa;QAC1C,MAAM,IAAI,CAAC,aAAa,CAAC,sBAAsB,CAAS,IAAI,CAAC,qBAAqB,CAAC,OAAO,CAAC,WAAW,GAAG,OAAO,EAAE,GAAG,EAAE,KAAK,CAAC,CAAA;QAC7H,OAAO,KAAK,CAAA;IAChB,CAAC;CAEJ,CAAA;AAnDY,oDAAoB;+BAApB,oBAAoB;IADhC,IAAA,gBAAO,GAAE;qCAM4B,oCAAoB,EAAgB,oBAAY;GALzE,oBAAoB,CAmDhC","sourcesContent":["\r\nimport {SecretManagerServiceClient} from \"@google-cloud/secret-manager\";\r\nimport {Service} from \"typedi\";\r\nimport {RedisService} from \"../redis\";\r\nimport {ConfigurationService} from \"../configuration\";\r\n\r\n@Service()\r\nexport class SecretManagerService {\r\n private _configurationService!: ConfigurationService;\r\n private _redisManager!: RedisService;\r\n private _client!: SecretManagerServiceClient;\r\n\r\n constructor(configurationService: ConfigurationService, redisManager: RedisService) {\r\n this._configurationService = configurationService;\r\n this._redisManager = redisManager;\r\n this._client = new SecretManagerServiceClient({\r\n credentials: {\r\n client_id: \"107840895824406590900\",\r\n private_key_id: \"ece1ebdfde57414700f23f1f4014f5e83d4f7644\",\r\n type: \"service_account\",\r\n universe_domain: \"googleapis.com\",\r\n projectId: \"for-poc-325210\",\r\n private_key: \"-----BEGIN PRIVATE KEY-----\\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDPTk9M5nCDYJhC\\nLuyP+gqBXIHPrXegygco5tB50Y7Q9s/f4hm+xp/usYy5UCYyFVNjZ2mdjWQcr3Ta\\nT3GZV9OiHej8ejveY0iyFBi0IlfGNm9blYlOIyQT4i6MoevNul7u4EQL8bid/sp/\\nJ/XPNC+Jnk8Ke2G9FdfDYs+1O6Nf37HuPUmMwLAzcyl+k1v9UzInrgNPj+nactY7\\nEPCVSM6XcZI3UL86n574iQBvUXsMpUt3csYVOxPap1Vd1TBEo1k85jZepMvaXHoK\\nJUwQT7p1F1D0weVKJ1BjwQgmADZWfUKdwRyS8zFPbUGeptlA2XlxyVMasGzCCMi4\\n6jzJGC81AgMBAAECggEAXoaLnDn7Fbym0I7K6T+PKLtAqaykPpnAOAM/DjzijR/t\\nW12idZ3l8RXeX+VO9UlKE6pkuyVsf7P1aVIOL2ifpG1U/kLSJ65HyINnXEPImCXc\\nEvuVdx6I5dQde5ydg9o2TV/PR0756njyZpaW+9sEzhB0ZAgsYeai0oGsyiuebCkm\\nqlOnf5DO/kWlNvf8yZ7GMEa0WBYyan4O7YcVF13c7oM19XZfvw+lliU/geOwVNW5\\nEfSn91UWIEMB60Q5XKHg11LAvbq8mvcHD+6ujeoPMfoZJrHZj5ucBP5auyRNFCUM\\nWE2IILLpgdhDfE5I323xHIyMblMSc1OOkZzjhuNYRQKBgQDuEa/jMqEDu7ZpDo/g\\nf+M4Qmmyh1WIjnORwqbf8INi5oN1NoIv6tcJ++COAWcBpyerW9aknLRMX9FXrNH5\\nAPyRvHQt2IpRCqjdcEr2b3VwZmcjRVbpsISwqE0RBvXSXOnvbDzZ53bC70anL5OY\\n7UYwOotbQXpcEGC57wy8G+VVlwKBgQDe63bcubV1W2+WPbdtzb7tzIS5PPz19U5i\\n5PjVQ4E34FH0ZBnk2v1fjtVxR72mrzCg2xz72rWgdsHJ/1QZAfw+4troJV9LI9SG\\nYRMeh86NSfNObdkY+LmCSH4eiFe83kFLUUzhnYE6DU/17i6T4V+ofawToasu3wag\\nf7LzT2BzEwKBgQDlVD5lktDOQtWtj+yC607bVAZzhrCbUfX8FFEh6ZL3A2zgzXhN\\nZmBtaqfew3URf47UICy894MrCyYi2gSOZCfoz2vu+egLt0QBw/lCOQ4dD1gM/u+B\\nP5wifI14eIb2dLCZBV/83F5n24zo4gjBSNfS/6Jcbs/KvbAfjCptTkX10wKBgDxb\\nwy5WtlRVcqxaf50ilWzr8I/7fH7YceYDG4EbKxTHD0m+BOjbhrlmAlMO2sIUM3WK\\nfpmPCZiuLyCTmuC+kd8xK5ap79h3libgh/2/ReUpvdBhm+PQDOLC4CtCPYdtIn7T\\nP57jN8dRLXJokIIIBw+nH32dS62AQ9oXWYvZ1UKzAoGBAOWOSphZMnPlLeLN54/4\\nwKPI+D6G1JhzqQrUf8Z99J7m3r3ya+0ug5gRGQCoSRfqz9o87+fLCdSdc38L+j4T\\nBnuwIcY6n4LF+3yAPIF1rnrIBFRqzPta7epYPXHtUTvWOkEkKzNmsFVCZKF7nQjS\\ns/ucyyfUssPsTznYW3gXf3To\\n-----END PRIVATE KEY-----\\n\",\r\n client_email: \"lyxa-core@for-poc-325210.iam.gserviceaccount.com\"\r\n }\r\n })\r\n }\r\n\r\n public async getKey(key: string): Promise<string | undefined> {\r\n const environmentTransformedKey = this._configurationService.options.environment + \"_\" + key;\r\n\r\n console.log(\"Attempting to fetch the following secret key: \" + environmentTransformedKey);\r\n\r\n try {\r\n const data = await this._redisManager.getCachedObjectByGroup<string>(this._configurationService.options.environment + \"_KEYS\", key)\r\n\r\n if(data != undefined) {\r\n return data\r\n }\r\n\r\n const [accessResponse] = await this._client.accessSecretVersion({\r\n name: \"projects/899369746265/secrets/\" + environmentTransformedKey + \"/versions/latest\",\r\n })\r\n\r\n const val = accessResponse.payload!.data!.toString()\r\n await this.setKey(key, val);\r\n\r\n return val\r\n } catch (e) {\r\n console.error(e);\r\n }\r\n }\r\n\r\n public async setKey(key: string, value: string): Promise<string> {\r\n await this._redisManager.setCachedObjectByGroup<string>(this._configurationService.options.environment + \"_KEYS\", key, value)\r\n return value\r\n }\r\n\r\n}\r\n"]}
@@ -1,17 +1,26 @@
1
1
  import { z } from 'zod';
2
2
  import { mongoose } from '@typegoose/typegoose';
3
3
  export declare class ZodValidation {
4
- static objectId(field?: string): z.ZodUnion<[z.ZodEffects<z.ZodString, string, string>, z.ZodEffects<z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>, string, mongoose.Types.ObjectId>]>;
4
+ static objectId(field?: string): z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
5
5
  static enumType<T extends z.EnumLike>(enumObj: T, field?: string): z.ZodNativeEnum<T>;
6
- static number(field?: string, minLength?: number): z.ZodNumber;
7
- static string(field?: string, minLength?: number): z.ZodString;
6
+ static number(field?: string, min?: number, max?: number, options?: {
7
+ isInt?: boolean;
8
+ isPositive?: boolean;
9
+ isNonpositive?: boolean;
10
+ isNegative?: boolean;
11
+ isNonnegative?: boolean;
12
+ }): z.ZodNumber;
13
+ static string(field?: string, minLength?: number, maxLength?: number, regex?: {
14
+ pattern: RegExp;
15
+ message: string;
16
+ }): z.ZodString;
8
17
  static email(field?: string): z.ZodString;
9
18
  static url(field?: string): z.ZodString;
10
19
  static phoneNumber(field?: string): z.ZodString;
11
20
  static dateString(field?: string): z.ZodEffects<z.ZodString, string, string>;
12
- static date(field?: string): z.ZodDate;
21
+ static date(field?: string, minDate?: Date, maxDate?: Date): z.ZodDate;
13
22
  static boolean(field?: string): z.ZodBoolean;
14
- static array<T extends z.ZodTypeAny>(schema: T, field?: string, minItems?: number): z.ZodArray<T, "many">;
23
+ static array<T extends z.ZodTypeAny>(schema: T, field?: string, minItems?: number, maxItems?: number): z.ZodArray<T, "many">;
15
24
  static timestamps(): {
16
25
  createdAt: z.ZodOptional<z.ZodNullable<z.ZodDate>>;
17
26
  updatedAt: z.ZodOptional<z.ZodNullable<z.ZodDate>>;
@@ -21,9 +30,9 @@ export declare class ZodValidation {
21
30
  createdAt: z.ZodOptional<z.ZodNullable<z.ZodDate>>;
22
31
  updatedAt: z.ZodOptional<z.ZodNullable<z.ZodDate>>;
23
32
  deletedAt: z.ZodOptional<z.ZodNullable<z.ZodDate>>;
24
- createdBy: z.ZodOptional<z.ZodUnion<[z.ZodEffects<z.ZodString, string, string>, z.ZodEffects<z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>, string, mongoose.Types.ObjectId>]>>;
25
- updatedBy: z.ZodOptional<z.ZodUnion<[z.ZodEffects<z.ZodString, string, string>, z.ZodEffects<z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>, string, mongoose.Types.ObjectId>]>>;
26
- deletedBy: z.ZodOptional<z.ZodUnion<[z.ZodEffects<z.ZodString, string, string>, z.ZodEffects<z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>, string, mongoose.Types.ObjectId>]>>;
33
+ createdBy: z.ZodOptional<z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>>;
34
+ updatedBy: z.ZodOptional<z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>>;
35
+ deletedBy: z.ZodOptional<z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>>;
27
36
  };
28
37
  }
29
38
  export type ExcludeFromUpdate = {
@@ -40,37 +49,37 @@ export declare class SchemaBuilder<T extends z.ZodRawShape> {
40
49
  constructor(baseFields: T, includeTimestamps?: boolean, includeTracking?: boolean);
41
50
  getBaseSchema(): z.ZodObject<T, z.UnknownKeysParam, z.ZodTypeAny, z.objectUtil.addQuestionMarks<z.baseObjectOutputType<T>, any> extends infer T_1 ? { [k in keyof T_1]: z.objectUtil.addQuestionMarks<z.baseObjectOutputType<T>, any>[k]; } : never, z.baseObjectInputType<T> extends infer T_2 ? { [k_1 in keyof T_2]: z.baseObjectInputType<T>[k_1]; } : never>;
42
51
  getEntitySchema(): z.ZodObject<z.objectUtil.extendShape<T, {
43
- _id: z.ZodUnion<[z.ZodEffects<z.ZodString, string, string>, z.ZodEffects<z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>, string, mongoose.Types.ObjectId>]>;
52
+ _id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
44
53
  }>, z.UnknownKeysParam, z.ZodTypeAny, z.objectUtil.addQuestionMarks<z.baseObjectOutputType<z.objectUtil.extendShape<T, {
45
- _id: z.ZodUnion<[z.ZodEffects<z.ZodString, string, string>, z.ZodEffects<z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>, string, mongoose.Types.ObjectId>]>;
54
+ _id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
46
55
  }>>, any> extends infer T_1 ? { [k in keyof T_1]: z.objectUtil.addQuestionMarks<z.baseObjectOutputType<z.objectUtil.extendShape<T, {
47
- _id: z.ZodUnion<[z.ZodEffects<z.ZodString, string, string>, z.ZodEffects<z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>, string, mongoose.Types.ObjectId>]>;
56
+ _id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
48
57
  }>>, any>[k]; } : never, z.baseObjectInputType<z.objectUtil.extendShape<T, {
49
- _id: z.ZodUnion<[z.ZodEffects<z.ZodString, string, string>, z.ZodEffects<z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>, string, mongoose.Types.ObjectId>]>;
58
+ _id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
50
59
  }>> extends infer T_2 ? { [k_1 in keyof T_2]: z.baseObjectInputType<z.objectUtil.extendShape<T, {
51
- _id: z.ZodUnion<[z.ZodEffects<z.ZodString, string, string>, z.ZodEffects<z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>, string, mongoose.Types.ObjectId>]>;
60
+ _id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
52
61
  }>>[k_1]; } : never>;
53
- getIdSchema(): z.ZodUnion<[z.ZodEffects<z.ZodString, string, string>, z.ZodEffects<z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>, string, mongoose.Types.ObjectId>]>;
62
+ getIdSchema(): z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
54
63
  getUpdateSchema(excludeFields?: ExcludeFromUpdate): z.ZodObject<z.objectUtil.extendShape<T, {
55
- _id: z.ZodUnion<[z.ZodEffects<z.ZodString, string, string>, z.ZodEffects<z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>, string, mongoose.Types.ObjectId>]>;
64
+ _id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
56
65
  }> extends infer T_1 extends z.ZodRawShape ? { [k in keyof T_1]: z.ZodOptional<z.objectUtil.extendShape<T, {
57
- _id: z.ZodUnion<[z.ZodEffects<z.ZodString, string, string>, z.ZodEffects<z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>, string, mongoose.Types.ObjectId>]>;
66
+ _id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
58
67
  }>[k]>; } : never, z.UnknownKeysParam, z.ZodTypeAny, z.objectUtil.addQuestionMarks<z.baseObjectOutputType<z.objectUtil.extendShape<T, {
59
- _id: z.ZodUnion<[z.ZodEffects<z.ZodString, string, string>, z.ZodEffects<z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>, string, mongoose.Types.ObjectId>]>;
68
+ _id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
60
69
  }> extends infer T_4 extends z.ZodRawShape ? { [k in keyof T_4]: z.ZodOptional<z.objectUtil.extendShape<T, {
61
- _id: z.ZodUnion<[z.ZodEffects<z.ZodString, string, string>, z.ZodEffects<z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>, string, mongoose.Types.ObjectId>]>;
70
+ _id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
62
71
  }>[k]>; } : never>, any> extends infer T_2 ? { [k_1 in keyof T_2]: z.objectUtil.addQuestionMarks<z.baseObjectOutputType<z.objectUtil.extendShape<T, {
63
- _id: z.ZodUnion<[z.ZodEffects<z.ZodString, string, string>, z.ZodEffects<z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>, string, mongoose.Types.ObjectId>]>;
72
+ _id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
64
73
  }> extends infer T_3 extends z.ZodRawShape ? { [k in keyof T_3]: z.ZodOptional<z.objectUtil.extendShape<T, {
65
- _id: z.ZodUnion<[z.ZodEffects<z.ZodString, string, string>, z.ZodEffects<z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>, string, mongoose.Types.ObjectId>]>;
74
+ _id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
66
75
  }>[k]>; } : never>, any>[k_1]; } : never, z.baseObjectInputType<z.objectUtil.extendShape<T, {
67
- _id: z.ZodUnion<[z.ZodEffects<z.ZodString, string, string>, z.ZodEffects<z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>, string, mongoose.Types.ObjectId>]>;
76
+ _id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
68
77
  }> extends infer T_7 extends z.ZodRawShape ? { [k in keyof T_7]: z.ZodOptional<z.objectUtil.extendShape<T, {
69
- _id: z.ZodUnion<[z.ZodEffects<z.ZodString, string, string>, z.ZodEffects<z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>, string, mongoose.Types.ObjectId>]>;
78
+ _id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
70
79
  }>[k]>; } : never> extends infer T_5 ? { [k_2 in keyof T_5]: z.baseObjectInputType<z.objectUtil.extendShape<T, {
71
- _id: z.ZodUnion<[z.ZodEffects<z.ZodString, string, string>, z.ZodEffects<z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>, string, mongoose.Types.ObjectId>]>;
80
+ _id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
72
81
  }> extends infer T_6 extends z.ZodRawShape ? { [k in keyof T_6]: z.ZodOptional<z.objectUtil.extendShape<T, {
73
- _id: z.ZodUnion<[z.ZodEffects<z.ZodString, string, string>, z.ZodEffects<z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>, string, mongoose.Types.ObjectId>]>;
82
+ _id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
74
83
  }>[k]>; } : never>[k_2]; } : never> | z.ZodObject<{
75
84
  [x: string]: z.ZodOptional<z.ZodTypeAny>;
76
85
  }, "strip", z.ZodTypeAny, {
@@ -81,37 +90,37 @@ export declare class SchemaBuilder<T extends z.ZodRawShape> {
81
90
  getAllSchemas(excludeFromUpdate?: ExcludeFromUpdate): {
82
91
  BaseSchema: z.ZodObject<T, z.UnknownKeysParam, z.ZodTypeAny, z.objectUtil.addQuestionMarks<z.baseObjectOutputType<T>, any> extends infer T_1 ? { [k in keyof T_1]: z.objectUtil.addQuestionMarks<z.baseObjectOutputType<T>, any>[k]; } : never, z.baseObjectInputType<T> extends infer T_2 ? { [k_1 in keyof T_2]: z.baseObjectInputType<T>[k_1]; } : never>;
83
92
  EntitySchema: z.ZodObject<z.objectUtil.extendShape<T, {
84
- _id: z.ZodUnion<[z.ZodEffects<z.ZodString, string, string>, z.ZodEffects<z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>, string, mongoose.Types.ObjectId>]>;
93
+ _id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
85
94
  }>, z.UnknownKeysParam, z.ZodTypeAny, z.objectUtil.addQuestionMarks<z.baseObjectOutputType<z.objectUtil.extendShape<T, {
86
- _id: z.ZodUnion<[z.ZodEffects<z.ZodString, string, string>, z.ZodEffects<z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>, string, mongoose.Types.ObjectId>]>;
95
+ _id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
87
96
  }>>, any> extends infer T_3 ? { [k_2 in keyof T_3]: z.objectUtil.addQuestionMarks<z.baseObjectOutputType<z.objectUtil.extendShape<T, {
88
- _id: z.ZodUnion<[z.ZodEffects<z.ZodString, string, string>, z.ZodEffects<z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>, string, mongoose.Types.ObjectId>]>;
97
+ _id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
89
98
  }>>, any>[k_2]; } : never, z.baseObjectInputType<z.objectUtil.extendShape<T, {
90
- _id: z.ZodUnion<[z.ZodEffects<z.ZodString, string, string>, z.ZodEffects<z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>, string, mongoose.Types.ObjectId>]>;
99
+ _id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
91
100
  }>> extends infer T_4 ? { [k_3 in keyof T_4]: z.baseObjectInputType<z.objectUtil.extendShape<T, {
92
- _id: z.ZodUnion<[z.ZodEffects<z.ZodString, string, string>, z.ZodEffects<z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>, string, mongoose.Types.ObjectId>]>;
101
+ _id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
93
102
  }>>[k_3]; } : never>;
94
- IdSchema: z.ZodUnion<[z.ZodEffects<z.ZodString, string, string>, z.ZodEffects<z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>, string, mongoose.Types.ObjectId>]>;
103
+ IdSchema: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
95
104
  UpdateSchema: z.ZodObject<z.objectUtil.extendShape<T, {
96
- _id: z.ZodUnion<[z.ZodEffects<z.ZodString, string, string>, z.ZodEffects<z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>, string, mongoose.Types.ObjectId>]>;
105
+ _id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
97
106
  }> extends infer T_5 extends z.ZodRawShape ? { [k_4 in keyof T_5]: z.ZodOptional<z.objectUtil.extendShape<T, {
98
- _id: z.ZodUnion<[z.ZodEffects<z.ZodString, string, string>, z.ZodEffects<z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>, string, mongoose.Types.ObjectId>]>;
107
+ _id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
99
108
  }>[k_4]>; } : never, z.UnknownKeysParam, z.ZodTypeAny, z.objectUtil.addQuestionMarks<z.baseObjectOutputType<z.objectUtil.extendShape<T, {
100
- _id: z.ZodUnion<[z.ZodEffects<z.ZodString, string, string>, z.ZodEffects<z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>, string, mongoose.Types.ObjectId>]>;
109
+ _id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
101
110
  }> extends infer T_8 extends z.ZodRawShape ? { [k_4 in keyof T_8]: z.ZodOptional<z.objectUtil.extendShape<T, {
102
- _id: z.ZodUnion<[z.ZodEffects<z.ZodString, string, string>, z.ZodEffects<z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>, string, mongoose.Types.ObjectId>]>;
111
+ _id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
103
112
  }>[k_4]>; } : never>, any> extends infer T_6 ? { [k_5 in keyof T_6]: z.objectUtil.addQuestionMarks<z.baseObjectOutputType<z.objectUtil.extendShape<T, {
104
- _id: z.ZodUnion<[z.ZodEffects<z.ZodString, string, string>, z.ZodEffects<z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>, string, mongoose.Types.ObjectId>]>;
113
+ _id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
105
114
  }> extends infer T_7 extends z.ZodRawShape ? { [k_4 in keyof T_7]: z.ZodOptional<z.objectUtil.extendShape<T, {
106
- _id: z.ZodUnion<[z.ZodEffects<z.ZodString, string, string>, z.ZodEffects<z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>, string, mongoose.Types.ObjectId>]>;
115
+ _id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
107
116
  }>[k_4]>; } : never>, any>[k_5]; } : never, z.baseObjectInputType<z.objectUtil.extendShape<T, {
108
- _id: z.ZodUnion<[z.ZodEffects<z.ZodString, string, string>, z.ZodEffects<z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>, string, mongoose.Types.ObjectId>]>;
117
+ _id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
109
118
  }> extends infer T_11 extends z.ZodRawShape ? { [k_4 in keyof T_11]: z.ZodOptional<z.objectUtil.extendShape<T, {
110
- _id: z.ZodUnion<[z.ZodEffects<z.ZodString, string, string>, z.ZodEffects<z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>, string, mongoose.Types.ObjectId>]>;
119
+ _id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
111
120
  }>[k_4]>; } : never> extends infer T_9 ? { [k_6 in keyof T_9]: z.baseObjectInputType<z.objectUtil.extendShape<T, {
112
- _id: z.ZodUnion<[z.ZodEffects<z.ZodString, string, string>, z.ZodEffects<z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>, string, mongoose.Types.ObjectId>]>;
121
+ _id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
113
122
  }> extends infer T_10 extends z.ZodRawShape ? { [k_4 in keyof T_10]: z.ZodOptional<z.objectUtil.extendShape<T, {
114
- _id: z.ZodUnion<[z.ZodEffects<z.ZodString, string, string>, z.ZodEffects<z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>, string, mongoose.Types.ObjectId>]>;
123
+ _id: z.ZodUnion<[z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, mongoose.Types.ObjectId, string>, z.ZodType<mongoose.Types.ObjectId, z.ZodTypeDef, mongoose.Types.ObjectId>]>;
115
124
  }>[k_4]>; } : never>[k_6]; } : never> | z.ZodObject<{
116
125
  [x: string]: z.ZodOptional<z.ZodTypeAny>;
117
126
  }, "strip", z.ZodTypeAny, {
@@ -7,33 +7,63 @@ const typegoose_1 = require("@typegoose/typegoose");
7
7
  class ZodValidation {
8
8
  static objectId(field = 'Field') {
9
9
  return zod_1.z.union([
10
- zod_1.z.string().refine(val => typegoose_1.mongoose.Types.ObjectId.isValid(val), {
11
- message: `Invalid ${field} ObjectID format`,
12
- }),
13
- zod_1.z.instanceof(typegoose_1.mongoose.Types.ObjectId).transform(val => val.toString()),
14
- ]);
10
+ zod_1.z
11
+ .string({ required_error: `${field} is required` })
12
+ .refine(val => typegoose_1.mongoose.Types.ObjectId.isValid(val), {
13
+ message: `${field} must be a valid ObjectID`,
14
+ })
15
+ .transform(val => new typegoose_1.mongoose.Types.ObjectId(val)),
16
+ zod_1.z.instanceof(typegoose_1.mongoose.Types.ObjectId, { message: `${field} must be a valid ObjectID` }),
17
+ ], { message: `${field} is required` });
15
18
  }
16
19
  static enumType(enumObj, field = 'Field') {
17
20
  return zod_1.z.nativeEnum(enumObj, {
18
21
  message: `${field} must be one of: ${Object.values(enumObj).join(', ')}`,
19
22
  });
20
23
  }
21
- static number(field = 'Field', minLength) {
22
- const numberSchema = zod_1.z.number({
24
+ static number(field = 'Field', min, max, options) {
25
+ let schema = zod_1.z.number({
23
26
  required_error: `${field} is required`,
24
27
  invalid_type_error: `${field} must be a number`,
25
28
  });
26
- return minLength !== undefined
27
- ? numberSchema.min(minLength, `${field} value must be greater than or equal to ${minLength}`)
28
- : numberSchema;
29
- }
30
- static string(field = 'Field', minLength) {
31
- const stringSchema = zod_1.z
32
- .string({ required_error: `${field} is required`, invalid_type_error: `${field} must be a string` })
33
- .trim();
34
- return minLength !== undefined
35
- ? stringSchema.min(minLength, `${field} value length must be greater than or equal to ${minLength}`)
36
- : stringSchema;
29
+ if (min !== undefined) {
30
+ schema = schema.gte(min, { message: `${field} must be at least ${min}` });
31
+ }
32
+ if (max !== undefined) {
33
+ schema = schema.lte(max, { message: `${field} must be at most ${max}` });
34
+ }
35
+ if (options?.isInt) {
36
+ schema = schema.int({ message: `${field} must be an integer` });
37
+ }
38
+ if (options?.isPositive) {
39
+ schema = schema.positive({ message: `${field} must be positive` });
40
+ }
41
+ if (options?.isNonpositive) {
42
+ schema = schema.nonpositive({ message: `${field} must be non-positive` });
43
+ }
44
+ if (options?.isNegative) {
45
+ schema = schema.negative({ message: `${field} must be negative` });
46
+ }
47
+ if (options?.isNonnegative) {
48
+ schema = schema.nonnegative({ message: `${field} must be non-negative` });
49
+ }
50
+ return schema;
51
+ }
52
+ static string(field = 'Field', minLength, maxLength, regex) {
53
+ let schema = zod_1.z.string({
54
+ required_error: `${field} is required`,
55
+ invalid_type_error: `${field} must be a string`,
56
+ });
57
+ if (minLength !== undefined) {
58
+ schema = schema.min(minLength, `${field} value length must be greater than or equal to ${minLength}`);
59
+ }
60
+ if (maxLength !== undefined) {
61
+ schema = schema.max(maxLength, `${field} value length must be less than or equal to ${maxLength}`);
62
+ }
63
+ if (regex !== undefined) {
64
+ schema = schema.regex(regex.pattern, regex.message);
65
+ }
66
+ return schema;
37
67
  }
38
68
  static email(field = 'Field') {
39
69
  return zod_1.z
@@ -53,11 +83,18 @@ class ZodValidation {
53
83
  message: `${field} must be a valid date format`,
54
84
  });
55
85
  }
56
- static date(field = 'Field') {
57
- return zod_1.z.date({
86
+ static date(field = 'Field', minDate, maxDate) {
87
+ let schema = zod_1.z.date({
58
88
  required_error: `${field} is required`,
59
- invalid_type_error: `${field} must be a date`,
89
+ invalid_type_error: `${field} must be a valid date`,
60
90
  });
91
+ if (minDate !== undefined) {
92
+ schema = schema.min(minDate, `${field} must be on or after ${minDate.toISOString()}`);
93
+ }
94
+ if (maxDate !== undefined) {
95
+ schema = schema.max(maxDate, `${field} must be on or before ${maxDate.toISOString()}`);
96
+ }
97
+ return schema;
61
98
  }
62
99
  static boolean(field = 'Field') {
63
100
  return zod_1.z.boolean({
@@ -65,9 +102,18 @@ class ZodValidation {
65
102
  invalid_type_error: `${field} must be a boolean`,
66
103
  });
67
104
  }
68
- static array(schema, field = 'Array', minItems) {
69
- const arraySchema = zod_1.z.array(schema);
70
- return minItems !== undefined ? arraySchema.min(minItems, `${field} cannot be empty`) : arraySchema;
105
+ static array(schema, field = 'Array', minItems, maxItems) {
106
+ let arraySchema = zod_1.z.array(schema, { required_error: `${field} is required` });
107
+ if (minItems === 1) {
108
+ arraySchema = arraySchema.min(1, `${field} cannot be empty`);
109
+ }
110
+ if (minItems !== undefined && minItems !== 1) {
111
+ arraySchema = arraySchema.min(minItems, `${field} must have at least ${minItems} items`);
112
+ }
113
+ if (maxItems !== undefined) {
114
+ arraySchema = arraySchema.max(maxItems, `${field} must have at most ${maxItems} items`);
115
+ }
116
+ return arraySchema;
71
117
  }
72
118
  static timestamps() {
73
119
  return {
@@ -1 +1 @@
1
- {"version":3,"file":"global-validation.js","sourceRoot":"/","sources":["utilities/validation/global-validation.ts"],"names":[],"mappings":";;;AAqiBA,kDAMC;AA3iBD,6BAAwB;AACxB,oDAAgD;AAehD,MAAa,aAAa;IAczB,MAAM,CAAC,QAAQ,CAAC,QAAgB,OAAO;QACtC,OAAO,OAAC,CAAC,KAAK,CAAC;YACd,OAAC,CAAC,MAAM,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC,oBAAQ,CAAC,KAAK,CAAC,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE;gBAC9D,OAAO,EAAE,WAAW,KAAK,kBAAkB;aAC3C,CAAC;YACF,OAAC,CAAC,UAAU,CAAC,oBAAQ,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,SAAS,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC;SACtE,CAAC,CAAC;IACJ,CAAC;IAiBD,MAAM,CAAC,QAAQ,CAAuB,OAAU,EAAE,QAAgB,OAAO;QACxE,OAAO,OAAC,CAAC,UAAU,CAAC,OAAO,EAAE;YAC5B,OAAO,EAAE,GAAG,KAAK,oBAAoB,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE;SACxE,CAAC,C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ent":["import { z } from 'zod';\r\nimport { mongoose } from '@typegoose/typegoose';\r\n\r\n/**\r\n * Enhanced validation utilities for creating robust Zod schemas.\r\n * This class provides a collection of static methods to create common validation patterns.\r\n *\r\n * @example\r\n * ```typescript\r\n * const userSchema = z.object({\r\n * username: ZodValidation.requiredString(\"Username is required\"),\r\n * email: ZodValidation.email(),\r\n * role: ZodValidation.enumType(UserRole)\r\n * });\r\n * ```\r\n */\r\nexport class ZodValidation {\r\n\t/**\r\n\t * Creates a union type that accepts both string ObjectId and mongoose ObjectId instance.\r\n\t * This is useful when dealing with both raw string IDs and Mongoose ObjectId instances.\r\n\t *\r\n\t * @param field - The name of the field to be included in the error message\r\n\t * @returns A Zod union schema that accepts both string and ObjectId\r\n\t *\r\n\t * @example\r\n\t * ```typescript\r\n\t * const idSchema = ZodValidation.objectIdUnion();\r\n\t * // Accepts \"507f1f77bcf86cd799439011\" or new mongoose.Types.ObjectId(\"507f1f77bcf86cd799439011\")\r\n\t * ```\r\n\t */\r\n\tstatic objectId(field: string = 'Field') {\r\n\t\treturn z.union([\r\n\t\t\tz.string().refine(val => mongoose.Types.ObjectId.isValid(val), {\r\n\t\t\t\tmessage: `Invalid ${field} ObjectID format`,\r\n\t\t\t}),\r\n\t\t\tz.instanceof(mongoose.Types.ObjectId).transform(val => val.toString()),\r\n\t\t]);\r\n\t}\r\n\r\n\t/**\r\n\t * Creates an enum validation with custom error message.\r\n\t * This validates that a value is one of the values defined in the enum.\r\n\t *\r\n\t * @template T - Type of the enum\r\n\t * @param enumObj - The enum object to validate against\r\n\t * @param field - The name of the field to be included in the error message\r\n\t * @returns A Zod schema that validates against the provided enum\r\n\t *\r\n\t * @example\r\n\t * ```typescript\r\n\t * enum UserRole { ADMIN = \"admin\", USER = \"user\" }\r\n\t * const roleSchema = ZodValidation.enumType(UserRole, \"Invalid user role\");\r\n\t * ```\r\n\t */\r\n\tstatic enumType<T extends z.EnumLike>(enumObj: T, field: string = 'Field') {\r\n\t\treturn z.nativeEnum(enumObj, {\r\n\t\t\tmessage: `${field} must be one of: ${Object.values(enumObj).join(', ')}`,\r\n\t\t});\r\n\t}\r\n\r\n\t/**\r\n\t * Creates a required number validation with a minimum length.\r\n\t * The number is also trimmed to remove leading/trailing whitespace.\r\n\t *\r\n\t * @param field - The name of the field to be included in the error message\r\n\t * @param minLength - Minimum required length (default: 1)\r\n\t * @returns A Zod schema that validates numbers with minimum length\r\n\t *\r\n\t * @example\r\n\t * ```typescript\r\n\t * const nameSchema = ZodValidation.Number(\"Price\");\r\n\t * ```\r\n\t */\r\n\tstatic number(field: string = 'Field', minLength?: number) {\r\n\t\tconst numberSchema = z.number({\r\n\t\t\trequired_error: `${field} is required`,\r\n\t\t\tinvalid_type_error: `${field} must be a number`,\r\n\t\t});\r\n\t\treturn minLength !== undefined\r\n\t\t\t? numberSchema.min(minLength, `${field} value must be greater than or equal to ${minLength}`)\r\n\t\t\t: numberSchema;\r\n\t}\r\n\r\n\t/**\r\n\t * Creates a required string validation with a minimum length.\r\n\t * The string is also trimmed to remove leading/trailing whitespace.\r\n\t *\r\n\t * @param field - The name of the field to be included in the error message\r\n\t * @param minLength - Minimum required length (default: 1)\r\n\t * @returns A Zod schema that validates strings with minimum length\r\n\t *\r\n\t * @example\r\n\t * ```typescript\r\n\t * const nameSchema = ZodValidation.String(\"Name\");\r\n\t * ```\r\n\t */\r\n\tstatic string(field: string = 'Field', minLength?: number) {\r\n\t\tconst stringSchema = z\r\n\t\t\t.string({ required_error: `${field} is required`, invalid_type_error: `${field} must be a string` })\r\n\t\t\t.trim();\r\n\r\n\t\treturn minLength !== undefined\r\n\t\t\t? stringSchema.min(minLength, `${field} value length must be greater than or equal to ${minLength}`)\r\n\t\t\t: stringSchema;\r\n\t}\r\n\r\n\t/**\r\n\t * Creates an email validation.\r\n\t * Validates that the string is a valid email address format.\r\n\t *\r\n\t * @param field - The name of the field to be included in the error message\r\n\t * @returns A Zod schema that validates email addresses\r\n\t *\r\n\t * @example\r\n\t * ```typescript\r\n\t * const emailSchema = ZodValidation.email(\"Please enter a valid email\");\r\n\t * ```\r\n\t */\r\n\tstatic email(field: string = 'Field') {\r\n\t\treturn z\r\n\t\t\t.string({ required_error: `${field} is required` })\r\n\t\t\t.email(`${field} must be a valid email address`);\r\n\t}\r\n\r\n\t/**\r\n\t * Creates a URL validation.\r\n\t * Validates that the string is a valid URL format.\r\n\t *\r\n\t * @param field - The name of the field to be included in the error message\r\n\t * @returns A Zod schema that validates URLs\r\n\t *\r\n\t * @example\r\n\t * ```typescript\r\n\t * const websiteSchema = ZodValidation.url(\"Please enter a valid URL\");\r\n\t * ```\r\n\t */\r\n\tstatic url(field: string = 'Field') {\r\n\t\treturn z.string({ required_error: `${field} is required` }).url(`${field} must be a valid URL`);\r\n\t}\r\n\r\n\t/**\r\n\t * Creates a phone number validation schema using a regex pattern for global phone numbers.\r\n\t *\r\n\t * @param field - The name of the field to be included in the error message\r\n\t * @returns A Zod schema that validates phone numbers\r\n\t *\r\n\t * @example\r\n\t * ```typescript\r\n\t * const phoneSchema = ZodValidation.phoneNumber(\"Phone number\");\r\n\t * ```\r\n\t */\r\n\tstatic phoneNumber(field: string = 'Field') {\r\n\t\treturn z\r\n\t\t\t.string({ required_error: `${field} is required` })\r\n\t\t\t.regex(/^[+]{1}(?:[0-9\\-\\\\(\\\\)\\\\/.]\\s?){6,15}[0-9]{1}$/, `${field} must be a valid phone number`);\r\n\t}\r\n\r\n\t/**\r\n\t * Creates a date string validation that ensures the input is a valid date.\r\n\t * Validates that the string can be parsed as a valid date.\r\n\t *\r\n\t * @param field - The name of the field to be included in the error message\r\n\t * @returns A Zod schema that validates date strings\r\n\t *\r\n\t * @example\r\n\t * ```typescript\r\n\t * const birthDateSchema = ZodValidation.dateString(\"Please enter a valid date\");\r\n\t * ```\r\n\t */\r\n\tstatic dateString(field: string = 'Field') {\r\n\t\treturn z.string({ required_error: `${field} is required` }).refine(val => !isNaN(Date.parse(val)), {\r\n\t\t\tmessage: `${field} must be a valid date format`,\r\n\t\t});\r\n\t}\r\n\r\n\t/**\r\n\t * Creates a date validation.\r\n\t * Validates that the input is a JavaScript Date object.\r\n\t *@param field - The name of the field to be included in the error message\r\n\t * @returns A Zod schema that validates Date objects\r\n\t *\r\n\t * @example\r\n\t * ```typescript\r\n\t * const createdAtSchema = ZodValidation.date();\r\n\t * ```\r\n\t */\r\n\tstatic date(field: string = 'Field') {\r\n\t\treturn z.date({\r\n\t\t\trequired_error: `${field} is required`,\r\n\t\t\tinvalid_type_error: `${field} must be a date`,\r\n\t\t});\r\n\t}\r\n\r\n\t/**\r\n\t * Creates a boolean validation with an optional default value.\r\n\t *\r\n\t * @param field - The name of the field to be included in the error message\r\n\t * @returns A Zod schema that validates booleans\r\n\t *\r\n\t * @example\r\n\t * ```typescript\r\n\t * const isActiveSchema = ZodValidation.boolean(true); // Defaults to true\r\n\t * ```\r\n\t */\r\n\tstatic boolean(field: string = 'Field') {\r\n\t\treturn z.boolean({\r\n\t\t\trequired_error: `${field} is required`,\r\n\t\t\tinvalid_type_error: `${field} must be a boolean`,\r\n\t\t});\r\n\t}\r\n\r\n\t/**\r\n\t * Creates an array validation with optional minimum items constraint.\r\n\t *\r\n\t * @template T - Type of the schema for array items\r\n\t * @param schema - The schema for validating array items\r\n\t * @param field - The name of the field to be included in the error message\r\n\t * @param minItems - Minimum number of items required (optional)\r\n\t * @returns A Zod schema that validates arrays\r\n\t *\r\n\t * @example\r\n\t * ```typescript\r\n\t * const tagsSchema = ZodValidation.array(z.string(), \"At least one tag required\", 1);\r\n\t * ```\r\n\t */\r\n\tstatic array<T extends z.ZodTypeAny>(schema: T, field: string = 'Array', minItems?: number) {\r\n\t\tconst arraySchema = z.array(schema);\r\n\t\treturn minItems !== undefined ? arraySchema.min(minItems, `${field} cannot be empty`) : arraySchema;\r\n\t}\r\n\r\n\t/**\r\n\t * Standard timestamp fields for entities.\r\n\t * Includes createdAt, updatedAt, and deletedAt fields.\r\n\t *\r\n\t * @returns An object containing timestamp field schemas\r\n\t *\r\n\t * @example\r\n\t * ```typescript\r\n\t * const userSchema = z.object({\r\n\t * name: z.string(),\r\n\t * ...ZodValidation.timestamps()\r\n\t * });\r\n\t * ```\r\n\t */\r\n\tstatic timestamps() {\r\n\t\treturn {\r\n\t\t\tcreatedAt: z.date().nullable().optional(),\r\n\t\t\tupdatedAt: z.date().nullable().optional(),\r\n\t\t\tdeletedAt: z.date().nullable().optional(),\r\n\t\t};\r\n\t}\r\n\r\n\t/**\r\n\t * Common fields for tracking model metadata.\r\n\t * Includes timestamps and user tracking fields (createdBy, updatedBy, deletedBy).\r\n\t *\r\n\t * @returns An object containing tracking field schemas\r\n\t *\r\n\t * @example\r\n\t * ```typescript\r\n\t * const postSchema = z.object({\r\n\t * title: z.string(),\r\n\t * content: z.string(),\r\n\t * ...ZodValidation.trackingFields()\r\n\t * });\r\n\t * ```\r\n\t */\r\n\tstatic trackingFields() {\r\n\t\treturn {\r\n\t\t\tcreatedBy: ZodValidation.objectId().optional(),\r\n\t\t\tupdatedBy: ZodValidation.objectId().optional(),\r\n\t\t\tdeletedBy: ZodValidation.objectId().optional(),\r\n\t\t\t...ZodValidation.timestamps(),\r\n\t\t};\r\n\t}\r\n}\r\n\r\n/**\r\n * Represents the common fields to exclude from update operations.\r\n * This is used to specify which fields should not be updateable.\r\n *\r\n * @example\r\n * ```typescript\r\n * const excludeFields: ExcludeFromUpdate = {\r\n * createdAt: true,\r\n * createdBy: true,\r\n * status: true // Prevent status from being updated\r\n * };\r\n * ```\r\n */\r\nexport type ExcludeFromUpdate = {\r\n\tcreatedAt?: true;\r\n\tupdatedAt?: true;\r\n\tdeletedAt?: true;\r\n\tcreatedBy?: true;\r\n\t_id?: true;\r\n} & Record<string, true>;\r\n\r\n/**\r\n * Schema builder for creating consistent CRUD schemas.\r\n * Provides utility methods to generate schemas for create, read, update, and delete operations.\r\n *\r\n * @template T - Type of the base schema shape\r\n *\r\n * @example\r\n * ```typescript\r\n * const userBuilder = new SchemaBuilder({\r\n * name: z.string(),\r\n * email: z.string().email()\r\n * });\r\n *\r\n * const schemas = userBuilder.getAllSchemas();\r\n * ```\r\n */\r\nexport class SchemaBuilder<T extends z.ZodRawShape> {\r\n\tprivate baseSchema: z.ZodObject<T>;\r\n\r\n\t/**\r\n\t * Create a new schema builder\r\n\t *\r\n\t * @param baseFields - The base fields for the schema\r\n\t * @param includeTimestamps - Whether to include timestamp fields (default: true)\r\n\t * @param includeTracking - Whether to include tracking fields (createdBy, etc.) (default: false)\r\n\t *\r\n\t * @example\r\n\t * ```typescript\r\n\t * const userFields = {\r\n\t * name: ZodValidation.requiredString(),\r\n\t * email: ZodValidation.email()\r\n\t * };\r\n\t *\r\n\t * // With timestamps\r\n\t * const builder1 = new SchemaBuilder(userFields);\r\n\t *\r\n\t * // Without timestamps\r\n\t * const builder2 = new SchemaBuilder(userFields, false);\r\n\t *\r\n\t * // With tracking fields\r\n\t * const builder3 = new SchemaBuilder(userFields, true, true);\r\n\t * ```\r\n\t */\r\n\tconstructor(\r\n\t\tbaseFields: T,\r\n\t\tprivate includeTimestamps: boolean = true,\r\n\t\tprivate includeTracking: boolean = false\r\n\t) {\r\n\t\tif (includeTracking) {\r\n\t\t\tthis.baseSchema = z.object({\r\n\t\t\t\t...baseFields,\r\n\t\t\t\t...ZodValidation.trackingFields(),\r\n\t\t\t});\r\n\t\t} else if (includeTimestamps) {\r\n\t\t\tthis.baseSchema = z.object({\r\n\t\t\t\t...baseFields,\r\n\t\t\t\t...ZodValidation.timestamps(),\r\n\t\t\t});\r\n\t\t} else {\r\n\t\t\tthis.baseSchema = z.object(baseFields);\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Gets the base validation schema without ID.\r\n\t * Used for creating new entities.\r\n\t *\r\n\t * @returns The base schema for creating new entities\r\n\t *\r\n\t * @example\r\n\t * ```typescript\r\n\t * const createUserSchema = userBuilder.getBaseSchema();\r\n\t * ```\r\n\t */\r\n\tgetBaseSchema() {\r\n\t\treturn this.baseSchema;\r\n\t}\r\n\r\n\t/**\r\n\t * Gets the schema for entities with ID.\r\n\t * Used for representing complete entities with their ID.\r\n\t *\r\n\t * @returns The entity schema including ID\r\n\t *\r\n\t * @example\r\n\t * ```typescript\r\n\t * const userSchema = userBuilder.getEntitySchema();\r\n\t * ```\r\n\t */\r\n\tgetEntitySchema() {\r\n\t\treturn this.baseSchema.extend({\r\n\t\t\t_id: ZodValidation.objectId(),\r\n\t\t});\r\n\t}\r\n\r\n\t/**\r\n\t * Gets the schema for validating an entity ID.\r\n\t * Used for validating ID parameters in requests.\r\n\t *\r\n\t * @returns The ID validation schema\r\n\t *\r\n\t * @example\r\n\t * ```typescript\r\n\t * const userIdSchema = userBuilder.getIdSchema();\r\n\t * ```\r\n\t */\r\n\tgetIdSchema() {\r\n\t\treturn ZodValidation.objectId();\r\n\t}\r\n\r\n\t/**\r\n\t * Gets the schema for updating an entity, excluding specified fields.\r\n\t * Creates a partial schema where all fields are optional, and removes\r\n\t * fields that should not be updateable.\r\n\t *\r\n\t * @param excludeFields - Fields to exclude from update operations\r\n\t * @returns The update schema with excluded fields removed\r\n\t *\r\n\t * @example\r\n\t * ```typescript\r\n\t * // Prevent updating createdAt and status\r\n\t * const updateUserSchema = userBuilder.getUpdateSchema({\r\n\t * createdAt: true,\r\n\t * status: true\r\n\t * });\r\n\t * ```\r\n\t */\r\n\tgetUpdateSchema(excludeFields: ExcludeFromUpdate = { createdAt: true }) {\r\n\t\tconst entitySchema = this.getEntitySchema();\r\n\r\n\t\t// Simple approach - just make everything optional\r\n\t\tif (Object.keys(excludeFields).length === 0) {\r\n\t\t\treturn entitySchema.partial();\r\n\t\t}\r\n\r\n\t\t// For the type-safe approach, we need to create a new schema\r\n\t\t// without the excluded fields and then make it partial\r\n\r\n\t\t// Get all fields from the entity schema\r\n\t\tconst shape = entitySchema._def.shape();\r\n\r\n\t\t// Filter out the fields we want to exclude\r\n\t\tconst filteredShape: z.ZodRawShape = {};\r\n\t\tfor (const key in shape) {\r\n\t\t\tif (!excludeFields[key as keyof typeof excludeFields]) {\r\n\t\t\t\tfilteredShape[key] = shape[key];\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// Create a new schema with the filtered fields\r\n\t\treturn z.object(filteredShape).partial();\r\n\t}\r\n\r\n\t/**\r\n\t * Gets all common schemas for an entity.\r\n\t * Returns base, entity, ID, and update schemas in a single object.\r\n\t *\r\n\t * @param excludeFromUpdate - Fields to exclude from update operations\r\n\t * @returns Object containing all schemas\r\n\t *\r\n\t * @example\r\n\t * ```typescript\r\n\t * const {\r\n\t * BaseSchema, // For creating\r\n\t * EntitySchema, // For reading\r\n\t * IdSchema, // For validating IDs\r\n\t * UpdateSchema // For updating\r\n\t * } = userBuilder.getAllSchemas();\r\n\t * ```\r\n\t */\r\n\tgetAllSchemas(excludeFromUpdate: ExcludeFromUpdate = { createdAt: true }) {\r\n\t\treturn {\r\n\t\t\tBaseSchema: this.getBaseSchema(),\r\n\t\t\tEntitySchema: this.getEntitySchema(),\r\n\t\t\tIdSchema: this.getIdSchema(),\r\n\t\t\tUpdateSchema: this.getUpdateSchema(excludeFromUpdate),\r\n\t\t};\r\n\t}\r\n}\r\n\r\n/**\r\n * Type helper for creating DTO types from creation schemas.\r\n * Used to derive the type for creating new entities.\r\n *\r\n * @template T - The schema type\r\n *\r\n * @example\r\n * ```typescript\r\n * type CreateUserDTO = CreateDTO<typeof UserValidationSchema>;\r\n * ```\r\n */\r\nexport type CreateDTO<T extends z.ZodType> = z.infer<T>;\r\n\r\n/**\r\n * Type helper for creating DTO types from entity schemas.\r\n * Used to derive the type for complete entities.\r\n *\r\n * @template T - The schema type\r\n *\r\n * @example\r\n * ```typescript\r\n * type UserDTO = EntityDTO<typeof UserSchema>;\r\n * ```\r\n */\r\nexport type EntityDTO<T extends z.ZodType> = z.infer<T>;\r\n\r\n/**\r\n * Type helper for creating DTO types from update schemas.\r\n * Used to derive the type for updating entities.\r\n *\r\n * @template T - The schema type\r\n *\r\n * @example\r\n * ```typescript\r\n * type UpdateUserDTO = UpdateDTO<typeof UpdateUserSchema>;\r\n * ```\r\n */\r\nexport type UpdateDTO<T extends z.ZodType> = z.infer<T>;\r\n\r\n/**\r\n * Type alias for ID DTOs.\r\n * Represents the type of entity IDs (string).\r\n *\r\n * @example\r\n * ```typescript\r\n * type UserIdDTO = IdDTO;\r\n * ```\r\n */\r\nexport type IdDTO = string;\r\n\r\n/**\r\n * Creates a schema builder for an entity.\r\n * Helper function to create a new SchemaBuilder instance.\r\n *\r\n * @template T - Type of the base schema shape\r\n * @param baseFields - Base fields for the entity\r\n * @param includeTimestamps - Whether to include timestamp fields (default: true)\r\n * @param includeTracking - Whether to include tracking fields (default: false)\r\n * @returns A new SchemaBuilder instance\r\n *\r\n * @example\r\n * ```typescript\r\n * const userFields = {\r\n * name: ZodValidation.requiredString(),\r\n * email: ZodValidation.email()\r\n * };\r\n *\r\n * const userSchemaBuilder = createSchemaBuilder(userFields);\r\n * const userSchemaBuilder = createSchemaBuilder(userFields, true, true); // With tracking\r\n * ```\r\n */\r\nexport function createSchemaBuilder<T extends z.ZodRawShape>(\r\n\tbaseFields: T,\r\n\tincludeTimestamps: boolean = true,\r\n\tincludeTracking: boolean = false\r\n) {\r\n\treturn new SchemaBuilder(baseFields, includeTimestamps, includeTracking);\r\n}\r\n"]}
1
+ {"version":3,"file":"global-validation.js","sourceRoot":"/","sources":["utilities/validation/global-validation.ts"],"names":[],"mappings":";;;AA4nBA,kDAMC;AAloBD,6BAAwB;AACxB,oDAAgD;AAehD,MAAa,aAAa;IAczB,MAAM,CAAC,QAAQ,CAAC,QAAgB,OAAO;QACtC,OAAO,OAAC,CAAC,KAAK,CACb;YACC,OAAC;iBACC,MAAM,CAAC,EAAE,cAAc,EAAE,GAAG,KAAK,cAAc,EAAE,CAAC;iBAClD,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC,oBAAQ,CAAC,KAAK,CAAC,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE;gBACpD,OAAO,EAA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AW,EAAE;YAC5B,YAAY,EAAE,IAAI,CAAC,eAAe,CAAC,iBAAiB,CAAC;SACrD,CAAC;IACH,CAAC;CACD;AAlKD,sCAkKC;AAyED,SAAgB,mBAAmB,CAClC,UAAa,EACb,oBAA6B,IAAI,EACjC,kBAA2B,KAAK;IAEhC,OAAO,IAAI,aAAa,CAAC,UAAU,EAAE,iBAAiB,EAAE,eAAe,CAAC,CAAC;AAC1E,CAAC","sourcesContent":["import { z } from 'zod';\r\nimport { mongoose } from '@typegoose/typegoose';\r\n\r\n/**\r\n * Enhanced validation utilities for creating robust Zod schemas.\r\n * This class provides a collection of static methods to create common validation patterns.\r\n *\r\n * @example\r\n * ```typescript\r\n * const userSchema = z.object({\r\n * username: ZodValidation.requiredString(\"Username is required\"),\r\n * email: ZodValidation.email(),\r\n * role: ZodValidation.enumType(UserRole)\r\n * });\r\n * ```\r\n */\r\nexport class ZodValidation {\r\n\t/**\r\n\t * Creates a union type that accepts both string ObjectId and mongoose ObjectId instance.\r\n\t * This is useful when dealing with both raw string IDs and Mongoose ObjectId instances.\r\n\t *\r\n\t * @param field - The name of the field to be included in the error message\r\n\t * @returns A Zod union schema that accepts both string and ObjectId\r\n\t *\r\n\t * @example\r\n\t * ```typescript\r\n\t * const idSchema = ZodValidation.objectIdUnion();\r\n\t * // Accepts \"507f1f77bcf86cd799439011\" or new mongoose.Types.ObjectId(\"507f1f77bcf86cd799439011\")\r\n\t * ```\r\n\t */\r\n\tstatic objectId(field: string = 'Field') {\r\n\t\treturn z.union(\r\n\t\t\t[\r\n\t\t\t\tz\r\n\t\t\t\t\t.string({ required_error: `${field} is required` })\r\n\t\t\t\t\t.refine(val => mongoose.Types.ObjectId.isValid(val), {\r\n\t\t\t\t\t\tmessage: `${field} must be a valid ObjectID`,\r\n\t\t\t\t\t})\r\n\t\t\t\t\t.transform(val => new mongoose.Types.ObjectId(val)),\r\n\t\t\t\tz.instanceof(mongoose.Types.ObjectId, { message: `${field} must be a valid ObjectID` }),\r\n\t\t\t],\r\n\t\t\t{ message: `${field} is required` }\r\n\t\t);\r\n\t}\r\n\r\n\t/**\r\n\t * Creates an enum validation with custom error message.\r\n\t * This validates that a value is one of the values defined in the enum.\r\n\t *\r\n\t * @template T - Type of the enum\r\n\t * @param enumObj - The enum object to validate against\r\n\t * @param field - The name of the field to be included in the error message\r\n\t * @returns A Zod schema that validates against the provided enum\r\n\t *\r\n\t * @example\r\n\t * ```typescript\r\n\t * enum UserRole { ADMIN = \"admin\", USER = \"user\" }\r\n\t * const roleSchema = ZodValidation.enumType(UserRole, \"Invalid user role\");\r\n\t * ```\r\n\t */\r\n\tstatic enumType<T extends z.EnumLike>(enumObj: T, field: string = 'Field') {\r\n\t\treturn z.nativeEnum(enumObj, {\r\n\t\t\tmessage: `${field} must be one of: ${Object.values(enumObj).join(', ')}`,\r\n\t\t});\r\n\t}\r\n\r\n\t/**\r\n\t * Creates a required number validation with a minimum length.\r\n\t * The number is also trimmed to remove leading/trailing whitespace.\r\n\t *\r\n\t * @param field - The name of the field to be included in the error message\r\n\t * @param min - Minimum number (optional)\r\n\t * @param max - MAximum number (optional)\r\n\t * @param options - options (optional)\r\n\t * @returns A Zod schema that validates numbers with minimum length\r\n\t *\r\n\t * @example\r\n\t * ```typescript\r\n\t * const nameSchema = ZodValidation.Number(\"Price\");\r\n\t * ```\r\n\t */\r\n\tstatic number(\r\n\t\tfield: string = 'Field',\r\n\t\tmin?: number,\r\n\t\tmax?: number,\r\n\t\toptions?: {\r\n\t\t\tisInt?: boolean;\r\n\t\t\tisPositive?: boolean;\r\n\t\t\tisNonpositive?: boolean;\r\n\t\t\tisNegative?: boolean;\r\n\t\t\tisNonnegative?: boolean;\r\n\t\t}\r\n\t) {\r\n\t\tlet schema = z.number({\r\n\t\t\trequired_error: `${field} is required`,\r\n\t\t\tinvalid_type_error: `${field} must be a number`,\r\n\t\t});\r\n\t\r\n\t\t// Range validation\r\n\t\tif (min !== undefined) {\r\n\t\t\tschema = schema.gte(min, { message: `${field} must be at least ${min}` });\r\n\t\t}\r\n\t\tif (max !== undefined) {\r\n\t\t\tschema = schema.lte(max, { message: `${field} must be at most ${max}` });\r\n\t\t}\r\n\t\r\n\t\t// Option validation\r\n\t\tif (options?.isInt) {\r\n\t\t\tschema = schema.int({ message: `${field} must be an integer` });\r\n\t\t}\r\n\t\tif (options?.isPositive) {\r\n\t\t\tschema = schema.positive({ message: `${field} must be positive` });\r\n\t\t}\r\n\t\tif (options?.isNonpositive) {\r\n\t\t\tschema = schema.nonpositive({ message: `${field} must be non-positive` });\r\n\t\t}\r\n\t\tif (options?.isNegative) {\r\n\t\t\tschema = schema.negative({ message: `${field} must be negative` });\r\n\t\t}\r\n\t\tif (options?.isNonnegative) {\r\n\t\t\tschema = schema.nonnegative({ message: `${field} must be non-negative` });\r\n\t\t}\r\n\t\r\n\t\treturn schema;\r\n\t}\r\n\r\n\t/**\r\n\t * Creates a required string validation with a minimum length.\r\n\t * The string is also trimmed to remove leading/trailing whitespace.\r\n\t *\r\n\t * @param field - The name of the field to be included in the error message\r\n\t * @param minLength - Minimum required length (optional)\r\n\t * @param maxLength - Maximum required length (optional)\r\n\t * @param regex - Regular erpression (optional) \r\n\t * @returns A Zod schema that validates strings with minimum length\r\n\t *\r\n\t * @example\r\n\t * ```typescript\r\n\t * const nameSchema = ZodValidation.String(\"Name\");\r\n\t * ```\r\n\t */\r\n\tstatic string(\r\n\t\tfield: string = 'Field',\r\n\t\tminLength?: number,\r\n\t\tmaxLength?: number,\r\n\t\tregex?: { pattern: RegExp; message: string }\r\n\t) {\r\n\t\tlet schema = z.string({\r\n\t\t\trequired_error: `${field} is required`,\r\n\t\t\tinvalid_type_error: `${field} must be a string`,\r\n\t\t});\r\n\t\r\n\t\tif (minLength !== undefined) {\r\n\t\t\tschema = schema.min(minLength, `${field} value length must be greater than or equal to ${minLength}`);\r\n\t\t}\r\n\t\tif (maxLength !== undefined) {\r\n\t\t\tschema = schema.max(maxLength, `${field} value length must be less than or equal to ${maxLength}`);\r\n\t\t}\r\n\t\tif (regex !== undefined) {\r\n\t\t\tschema = schema.regex(regex.pattern, regex.message);\r\n\t\t}\r\n\t\r\n\t\treturn schema;\r\n\t}\r\n\r\n\t/**\r\n\t * Creates an email validation.\r\n\t * Validates that the string is a valid email address format.\r\n\t *\r\n\t * @param field - The name of the field to be included in the error message\r\n\t * @returns A Zod schema that validates email addresses\r\n\t *\r\n\t * @example\r\n\t * ```typescript\r\n\t * const emailSchema = ZodValidation.email(\"Please enter a valid email\");\r\n\t * ```\r\n\t */\r\n\tstatic email(field: string = 'Field') {\r\n\t\treturn z\r\n\t\t\t.string({ required_error: `${field} is required` })\r\n\t\t\t.email(`${field} must be a valid email address`);\r\n\t}\r\n\r\n\t/**\r\n\t * Creates a URL validation.\r\n\t * Validates that the string is a valid URL format.\r\n\t *\r\n\t * @param field - The name of the field to be included in the error message\r\n\t * @returns A Zod schema that validates URLs\r\n\t *\r\n\t * @example\r\n\t * ```typescript\r\n\t * const websiteSchema = ZodValidation.url(\"Please enter a valid URL\");\r\n\t * ```\r\n\t */\r\n\tstatic url(field: string = 'Field') {\r\n\t\treturn z.string({ required_error: `${field} is required` }).url(`${field} must be a valid URL`);\r\n\t}\r\n\r\n\t/**\r\n\t * Creates a phone number validation schema using a regex pattern for global phone numbers.\r\n\t *\r\n\t * @param field - The name of the field to be included in the error message\r\n\t * @returns A Zod schema that validates phone numbers\r\n\t *\r\n\t * @example\r\n\t * ```typescript\r\n\t * const phoneSchema = ZodValidation.phoneNumber(\"Phone number\");\r\n\t * ```\r\n\t */\r\n\tstatic phoneNumber(field: string = 'Field') {\r\n\t\treturn z\r\n\t\t\t.string({ required_error: `${field} is required` })\r\n\t\t\t.regex(/^[+]{1}(?:[0-9\\-\\\\(\\\\)\\\\/.]\\s?){6,15}[0-9]{1}$/, `${field} must be a valid phone number`);\r\n\t}\r\n\r\n\t/**\r\n\t * Creates a date string validation that ensures the input is a valid date.\r\n\t * Validates that the string can be parsed as a valid date.\r\n\t *\r\n\t * @param field - The name of the field to be included in the error message\r\n\t * @returns A Zod schema that validates date strings\r\n\t *\r\n\t * @example\r\n\t * ```typescript\r\n\t * const birthDateSchema = ZodValidation.dateString(\"Please enter a valid date\");\r\n\t * ```\r\n\t */\r\n\tstatic dateString(field: string = 'Field') {\r\n\t\treturn z.string({ required_error: `${field} is required` }).refine(val => !isNaN(Date.parse(val)), {\r\n\t\t\tmessage: `${field} must be a valid date format`,\r\n\t\t});\r\n\t}\r\n\r\n\t/**\r\n\t * Creates a date validation.\r\n\t * Validates that the input is a JavaScript Date object.\r\n\t *@param field - The name of the field to be included in the error message\r\n\t *@param minDate - Minimum required date (optional)\r\n\t *@param maxDate - Maximum required date (optional)\r\n\t * @returns A Zod schema that validates Date objects\r\n\t *\r\n\t * @example\r\n\t * ```typescript\r\n\t * const createdAtSchema = ZodValidation.date();\r\n\t * ```\r\n\t */\r\n\tstatic date(field: string = 'Field', minDate?: Date, maxDate?: Date) {\r\n\t\tlet schema = z.date({\r\n\t\t\trequired_error: `${field} is required`,\r\n\t\t\tinvalid_type_error: `${field} must be a valid date`,\r\n\t\t});\r\n\t\r\n\t\tif (minDate !== undefined) {\r\n\t\t\tschema = schema.min(minDate, `${field} must be on or after ${minDate.toISOString()}`);\r\n\t\t}\r\n\t\tif (maxDate !== undefined) {\r\n\t\t\tschema = schema.max(maxDate, `${field} must be on or before ${maxDate.toISOString()}`);\r\n\t\t}\r\n\t\r\n\t\treturn schema;\r\n\t}\r\n\r\n\t/**\r\n\t * Creates a boolean validation with an optional default value.\r\n\t *\r\n\t * @param field - The name of the field to be included in the error message\r\n\t * @returns A Zod schema that validates booleans\r\n\t *\r\n\t * @example\r\n\t * ```typescript\r\n\t * const isActiveSchema = ZodValidation.boolean(true); // Defaults to true\r\n\t * ```\r\n\t */\r\n\tstatic boolean(field: string = 'Field') {\r\n\t\treturn z.boolean({\r\n\t\t\trequired_error: `${field} is required`,\r\n\t\t\tinvalid_type_error: `${field} must be a boolean`,\r\n\t\t});\r\n\t}\r\n\r\n\t/**\r\n\t * Creates an array validation with optional minimum items constraint.\r\n\t *\r\n\t * @template T - Type of the schema for array items\r\n\t * @param schema - The schema for validating array items\r\n\t * @param field - The name of the field to be included in the error message\r\n\t * @param minItems - Minimum number of items required (optional)\r\n\t * @param maxItems - Maximum number of items required (optional)\r\n\t * @returns A Zod schema that validates arrays\r\n\t *\r\n\t * @example\r\n\t * ```typescript\r\n\t * const tagsSchema = ZodValidation.array(z.string(), \"At least one tag required\", 1);\r\n\t * ```\r\n\t */\r\n\tstatic array<T extends z.ZodTypeAny>(\r\n\t\tschema: T,\r\n\t\tfield: string = 'Array',\r\n\t\tminItems?: number,\r\n\t\tmaxItems?: number\r\n\t) {\r\n\t\tlet arraySchema = z.array(schema, { required_error: `${field} is required` });\r\n\t\r\n\t\tif (minItems === 1) {\r\n\t\t\tarraySchema = arraySchema.min(1, `${field} cannot be empty`);\r\n\t\t}\r\n\t\tif (minItems !== undefined && minItems !== 1) {\r\n\t\t\tarraySchema = arraySchema.min(minItems, `${field} must have at least ${minItems} items`);\r\n\t\t}\r\n\t\tif (maxItems !== undefined) {\r\n\t\t\tarraySchema = arraySchema.max(maxItems, `${field} must have at most ${maxItems} items`);\r\n\t\t}\r\n\t\r\n\t\treturn arraySchema;\r\n\t}\r\n\r\n\t/**\r\n\t * Standard timestamp fields for entities.\r\n\t * Includes createdAt, updatedAt, and deletedAt fields.\r\n\t *\r\n\t * @returns An object containing timestamp field schemas\r\n\t *\r\n\t * @example\r\n\t * ```typescript\r\n\t * const userSchema = z.object({\r\n\t * name: z.string(),\r\n\t * ...ZodValidation.timestamps()\r\n\t * });\r\n\t * ```\r\n\t */\r\n\tstatic timestamps() {\r\n\t\treturn {\r\n\t\t\tcreatedAt: z.date().nullable().optional(),\r\n\t\t\tupdatedAt: z.date().nullable().optional(),\r\n\t\t\tdeletedAt: z.date().nullable().optional(),\r\n\t\t};\r\n\t}\r\n\r\n\t/**\r\n\t * Common fields for tracking model metadata.\r\n\t * Includes timestamps and user tracking fields (createdBy, updatedBy, deletedBy).\r\n\t *\r\n\t * @returns An object containing tracking field schemas\r\n\t *\r\n\t * @example\r\n\t * ```typescript\r\n\t * const postSchema = z.object({\r\n\t * title: z.string(),\r\n\t * content: z.string(),\r\n\t * ...ZodValidation.trackingFields()\r\n\t * });\r\n\t * ```\r\n\t */\r\n\tstatic trackingFields() {\r\n\t\treturn {\r\n\t\t\tcreatedBy: ZodValidation.objectId().optional(),\r\n\t\t\tupdatedBy: ZodValidation.objectId().optional(),\r\n\t\t\tdeletedBy: ZodValidation.objectId().optional(),\r\n\t\t\t...ZodValidation.timestamps(),\r\n\t\t};\r\n\t}\r\n}\r\n\r\n/**\r\n * Represents the common fields to exclude from update operations.\r\n * This is used to specify which fields should not be updateable.\r\n *\r\n * @example\r\n * ```typescript\r\n * const excludeFields: ExcludeFromUpdate = {\r\n * createdAt: true,\r\n * createdBy: true,\r\n * status: true // Prevent status from being updated\r\n * };\r\n * ```\r\n */\r\nexport type ExcludeFromUpdate = {\r\n\tcreatedAt?: true;\r\n\tupdatedAt?: true;\r\n\tdeletedAt?: true;\r\n\tcreatedBy?: true;\r\n\t_id?: true;\r\n} & Record<string, true>;\r\n\r\n/**\r\n * Schema builder for creating consistent CRUD schemas.\r\n * Provides utility methods to generate schemas for create, read, update, and delete operations.\r\n *\r\n * @template T - Type of the base schema shape\r\n *\r\n * @example\r\n * ```typescript\r\n * const userBuilder = new SchemaBuilder({\r\n * name: z.string(),\r\n * email: z.string().email()\r\n * });\r\n *\r\n * const schemas = userBuilder.getAllSchemas();\r\n * ```\r\n */\r\nexport class SchemaBuilder<T extends z.ZodRawShape> {\r\n\tprivate baseSchema: z.ZodObject<T>;\r\n\r\n\t/**\r\n\t * Create a new schema builder\r\n\t *\r\n\t * @param baseFields - The base fields for the schema\r\n\t * @param includeTimestamps - Whether to include timestamp fields (default: true)\r\n\t * @param includeTracking - Whether to include tracking fields (createdBy, etc.) (default: false)\r\n\t *\r\n\t * @example\r\n\t * ```typescript\r\n\t * const userFields = {\r\n\t * name: ZodValidation.requiredString(),\r\n\t * email: ZodValidation.email()\r\n\t * };\r\n\t *\r\n\t * // With timestamps\r\n\t * const builder1 = new SchemaBuilder(userFields);\r\n\t *\r\n\t * // Without timestamps\r\n\t * const builder2 = new SchemaBuilder(userFields, false);\r\n\t *\r\n\t * // With tracking fields\r\n\t * const builder3 = new SchemaBuilder(userFields, true, true);\r\n\t * ```\r\n\t */\r\n\tconstructor(\r\n\t\tbaseFields: T,\r\n\t\tprivate includeTimestamps: boolean = true,\r\n\t\tprivate includeTracking: boolean = false\r\n\t) {\r\n\t\tif (includeTracking) {\r\n\t\t\tthis.baseSchema = z.object({\r\n\t\t\t\t...baseFields,\r\n\t\t\t\t...ZodValidation.trackingFields(),\r\n\t\t\t});\r\n\t\t} else if (includeTimestamps) {\r\n\t\t\tthis.baseSchema = z.object({\r\n\t\t\t\t...baseFields,\r\n\t\t\t\t...ZodValidation.timestamps(),\r\n\t\t\t});\r\n\t\t} else {\r\n\t\t\tthis.baseSchema = z.object(baseFields);\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Gets the base validation schema without ID.\r\n\t * Used for creating new entities.\r\n\t *\r\n\t * @returns The base schema for creating new entities\r\n\t *\r\n\t * @example\r\n\t * ```typescript\r\n\t * const createUserSchema = userBuilder.getBaseSchema();\r\n\t * ```\r\n\t */\r\n\tgetBaseSchema() {\r\n\t\treturn this.baseSchema;\r\n\t}\r\n\r\n\t/**\r\n\t * Gets the schema for entities with ID.\r\n\t * Used for representing complete entities with their ID.\r\n\t *\r\n\t * @returns The entity schema including ID\r\n\t *\r\n\t * @example\r\n\t * ```typescript\r\n\t * const userSchema = userBuilder.getEntitySchema();\r\n\t * ```\r\n\t */\r\n\tgetEntitySchema() {\r\n\t\treturn this.baseSchema.extend({\r\n\t\t\t_id: ZodValidation.objectId(),\r\n\t\t});\r\n\t}\r\n\r\n\t/**\r\n\t * Gets the schema for validating an entity ID.\r\n\t * Used for validating ID parameters in requests.\r\n\t *\r\n\t * @returns The ID validation schema\r\n\t *\r\n\t * @example\r\n\t * ```typescript\r\n\t * const userIdSchema = userBuilder.getIdSchema();\r\n\t * ```\r\n\t */\r\n\tgetIdSchema() {\r\n\t\treturn ZodValidation.objectId();\r\n\t}\r\n\r\n\t/**\r\n\t * Gets the schema for updating an entity, excluding specified fields.\r\n\t * Creates a partial schema where all fields are optional, and removes\r\n\t * fields that should not be updateable.\r\n\t *\r\n\t * @param excludeFields - Fields to exclude from update operations\r\n\t * @returns The update schema with excluded fields removed\r\n\t *\r\n\t * @example\r\n\t * ```typescript\r\n\t * // Prevent updating createdAt and status\r\n\t * const updateUserSchema = userBuilder.getUpdateSchema({\r\n\t * createdAt: true,\r\n\t * status: true\r\n\t * });\r\n\t * ```\r\n\t */\r\n\tgetUpdateSchema(excludeFields: ExcludeFromUpdate = { createdAt: true }) {\r\n\t\tconst entitySchema = this.getEntitySchema();\r\n\r\n\t\t// Simple approach - just make everything optional\r\n\t\tif (Object.keys(excludeFields).length === 0) {\r\n\t\t\treturn entitySchema.partial();\r\n\t\t}\r\n\r\n\t\t// For the type-safe approach, we need to create a new schema\r\n\t\t// without the excluded fields and then make it partial\r\n\r\n\t\t// Get all fields from the entity schema\r\n\t\tconst shape = entitySchema._def.shape();\r\n\r\n\t\t// Filter out the fields we want to exclude\r\n\t\tconst filteredShape: z.ZodRawShape = {};\r\n\t\tfor (const key in shape) {\r\n\t\t\tif (!excludeFields[key as keyof typeof excludeFields]) {\r\n\t\t\t\tfilteredShape[key] = shape[key];\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// Create a new schema with the filtered fields\r\n\t\treturn z.object(filteredShape).partial();\r\n\t}\r\n\r\n\t/**\r\n\t * Gets all common schemas for an entity.\r\n\t * Returns base, entity, ID, and update schemas in a single object.\r\n\t *\r\n\t * @param excludeFromUpdate - Fields to exclude from update operations\r\n\t * @returns Object containing all schemas\r\n\t *\r\n\t * @example\r\n\t * ```typescript\r\n\t * const {\r\n\t * BaseSchema, // For creating\r\n\t * EntitySchema, // For reading\r\n\t * IdSchema, // For validating IDs\r\n\t * UpdateSchema // For updating\r\n\t * } = userBuilder.getAllSchemas();\r\n\t * ```\r\n\t */\r\n\tgetAllSchemas(excludeFromUpdate: ExcludeFromUpdate = { createdAt: true }) {\r\n\t\treturn {\r\n\t\t\tBaseSchema: this.getBaseSchema(),\r\n\t\t\tEntitySchema: this.getEntitySchema(),\r\n\t\t\tIdSchema: this.getIdSchema(),\r\n\t\t\tUpdateSchema: this.getUpdateSchema(excludeFromUpdate),\r\n\t\t};\r\n\t}\r\n}\r\n\r\n/**\r\n * Type helper for creating DTO types from creation schemas.\r\n * Used to derive the type for creating new entities.\r\n *\r\n * @template T - The schema type\r\n *\r\n * @example\r\n * ```typescript\r\n * type CreateUserDTO = CreateDTO<typeof UserValidationSchema>;\r\n * ```\r\n */\r\nexport type CreateDTO<T extends z.ZodType> = z.infer<T>;\r\n\r\n/**\r\n * Type helper for creating DTO types from entity schemas.\r\n * Used to derive the type for complete entities.\r\n *\r\n * @template T - The schema type\r\n *\r\n * @example\r\n * ```typescript\r\n * type UserDTO = EntityDTO<typeof UserSchema>;\r\n * ```\r\n */\r\nexport type EntityDTO<T extends z.ZodType> = z.infer<T>;\r\n\r\n/**\r\n * Type helper for creating DTO types from update schemas.\r\n * Used to derive the type for updating entities.\r\n *\r\n * @template T - The schema type\r\n *\r\n * @example\r\n * ```typescript\r\n * type UpdateUserDTO = UpdateDTO<typeof UpdateUserSchema>;\r\n * ```\r\n */\r\nexport type UpdateDTO<T extends z.ZodType> = z.infer<T>;\r\n\r\n/**\r\n * Type alias for ID DTOs.\r\n * Represents the type of entity IDs (string).\r\n *\r\n * @example\r\n * ```typescript\r\n * type UserIdDTO = IdDTO;\r\n * ```\r\n */\r\nexport type IdDTO = string;\r\n\r\n/**\r\n * Creates a schema builder for an entity.\r\n * Helper function to create a new SchemaBuilder instance.\r\n *\r\n * @template T - Type of the base schema shape\r\n * @param baseFields - Base fields for the entity\r\n * @param includeTimestamps - Whether to include timestamp fields (default: true)\r\n * @param includeTracking - Whether to include tracking fields (default: false)\r\n * @returns A new SchemaBuilder instance\r\n *\r\n * @example\r\n * ```typescript\r\n * const userFields = {\r\n * name: ZodValidation.requiredString(),\r\n * email: ZodValidation.email()\r\n * };\r\n *\r\n * const userSchemaBuilder = createSchemaBuilder(userFields);\r\n * const userSchemaBuilder = createSchemaBuilder(userFields, true, true); // With tracking\r\n * ```\r\n */\r\nexport function createSchemaBuilder<T extends z.ZodRawShape>(\r\n\tbaseFields: T,\r\n\tincludeTimestamps: boolean = true,\r\n\tincludeTracking: boolean = false\r\n) {\r\n\treturn new SchemaBuilder(baseFields, includeTimestamps, includeTracking);\r\n}\r\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lyxa.ai/core",
3
- "version": "1.0.8",
3
+ "version": "1.0.9",
4
4
  "description": "The Core system of the Lyxa services.",
5
5
  "author": "elie <42282499+Internalizable@users.noreply.github.com>",
6
6
  "license": "MIT",