@monque/tsed 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +15 -0
- package/README.md +222 -0
- package/dist/CHANGELOG.md +19 -0
- package/dist/LICENSE +15 -0
- package/dist/README.md +222 -0
- package/dist/index.cjs +712 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +582 -0
- package/dist/index.d.cts.map +1 -0
- package/dist/index.d.mts +582 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +691 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +98 -0
- package/src/config/config.ts +60 -0
- package/src/config/index.ts +2 -0
- package/src/config/types.ts +114 -0
- package/src/constants/constants.ts +12 -0
- package/src/constants/index.ts +2 -0
- package/src/constants/types.ts +21 -0
- package/src/decorators/cron.ts +58 -0
- package/src/decorators/index.ts +10 -0
- package/src/decorators/types.ts +131 -0
- package/src/decorators/worker-controller.ts +55 -0
- package/src/decorators/worker.ts +66 -0
- package/src/index.ts +20 -0
- package/src/monque-module.ts +199 -0
- package/src/services/index.ts +1 -0
- package/src/services/monque-service.ts +267 -0
- package/src/utils/build-job-name.ts +17 -0
- package/src/utils/collect-worker-metadata.ts +95 -0
- package/src/utils/get-worker-token.ts +27 -0
- package/src/utils/guards.ts +62 -0
- package/src/utils/index.ts +13 -0
- package/src/utils/resolve-database.ts +119 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/config/config.ts","../src/constants/constants.ts","../src/constants/types.ts","../src/decorators/cron.ts","../src/decorators/worker.ts","../src/decorators/worker-controller.ts","../src/services/monque-service.ts","../src/utils/build-job-name.ts","../src/utils/collect-worker-metadata.ts","../src/utils/get-worker-token.ts","../src/utils/guards.ts","../src/utils/resolve-database.ts","../src/monque-module.ts"],"sourcesContent":["/**\n * @monque/tsed - Configuration\n *\n * Defines the configuration interface and TsED module augmentation.\n */\n\nimport type { MonqueTsedConfig } from './types.js';\n\n// ─────────────────────────────────────────────────────────────────────────────\n// TsED Module Augmentation\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Augment TsED's Configuration interface to include monque settings.\n *\n * This allows type-safe configuration via @Configuration decorator.\n */\ndeclare global {\n\tnamespace TsED {\n\t\tinterface Configuration {\n\t\t\t/**\n\t\t\t * Monque job queue configuration.\n\t\t\t */\n\t\t\tmonque?: MonqueTsedConfig;\n\t\t}\n\t}\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Validation\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Validate that exactly one database resolution strategy is provided.\n *\n * @param config - The configuration to validate.\n * @throws Error if zero or multiple strategies are provided.\n *\n * @example\n * ```typescript\n * validateDatabaseConfig({ db: mongoDb }); // OK\n * validateDatabaseConfig({}); // throws\n * validateDatabaseConfig({ db: mongoDb, dbFactory: fn }); // throws\n * ```\n */\nexport function validateDatabaseConfig(config: MonqueTsedConfig): void {\n\tconst strategies = [config.db, config.dbFactory, config.dbToken].filter(Boolean);\n\n\tif (strategies.length === 0) {\n\t\tthrow new Error(\n\t\t\t\"MonqueTsedConfig requires exactly one of 'db', 'dbFactory', or 'dbToken' to be set\",\n\t\t);\n\t}\n\n\tif (strategies.length > 1) {\n\t\tthrow new Error(\n\t\t\t\"MonqueTsedConfig accepts only one of 'db', 'dbFactory', or 'dbToken' - multiple were provided\",\n\t\t);\n\t}\n}\n","/**\n * Symbol used to store decorator metadata on class constructors.\n *\n * Used by @WorkerController, @Worker, and @Cron decorators to attach\n * metadata that is later collected by MonqueModule during initialization.\n *\n * @example\n * ```typescript\n * Store.from(Class).set(MONQUE, metadata);\n * ```\n */\nexport const MONQUE = Symbol.for('monque');\n","/**\n * Provider type constants for DI scanning.\n *\n * These constants are used to categorize providers registered with Ts.ED's\n * dependency injection container, enabling MonqueModule to discover and\n * register workers automatically.\n *\n * Note: Using string constants with `as const` instead of enums per\n * Constitution guidelines.\n */\nexport const ProviderTypes = {\n\t/** Provider type for @WorkerController decorated classes */\n\tWORKER_CONTROLLER: 'monque:worker-controller',\n\t/** Provider type for cron job handlers */\n\tCRON: 'monque:cron',\n} as const;\n\n/**\n * Union type of all provider type values.\n */\nexport type ProviderType = (typeof ProviderTypes)[keyof typeof ProviderTypes];\n","import { Store } from '@tsed/core';\n\nimport { MONQUE } from '@/constants';\nimport type { CronDecoratorOptions, CronMetadata, WorkerStore } from '@/decorators/types.js';\n\n/**\n * Method decorator that registers a method as a scheduled cron job.\n *\n * @param pattern - Cron expression (e.g., \"* * * * *\", \"@daily\")\n * @param options - Optional cron configuration (name, timezone, etc.)\n *\n * @example\n * ```typescript\n * @WorkerController()\n * class ReportWorkers {\n * @Cron(\"@daily\", { timezone: \"UTC\" })\n * async generateDailyReport() {\n * // ...\n * }\n * }\n * ```\n */\nexport function Cron(pattern: string, options?: CronDecoratorOptions): MethodDecorator {\n\treturn <T>(\n\t\ttarget: object,\n\t\tpropertyKey: string | symbol,\n\t\t_descriptor: TypedPropertyDescriptor<T>,\n\t): void => {\n\t\tconst methodName = String(propertyKey);\n\n\t\tconst cronMetadata: CronMetadata = {\n\t\t\tpattern,\n\t\t\t// Default name to method name if not provided\n\t\t\tname: options?.name || methodName,\n\t\t\tmethod: methodName,\n\t\t\topts: options || {},\n\t\t};\n\n\t\t// Get the class constructor (target is the prototype for instance methods)\n\t\tconst targetConstructor = target.constructor;\n\t\tconst store = Store.from(targetConstructor);\n\n\t\t// Get or initialize the MONQUE store\n\t\tconst existing = store.get<Partial<WorkerStore>>(MONQUE) || {\n\t\t\ttype: 'controller',\n\t\t\tworkers: [],\n\t\t\tcronJobs: [],\n\t\t};\n\n\t\t// Add this cron job to the list\n\t\tconst cronJobs = [...(existing.cronJobs || []), cronMetadata];\n\n\t\tstore.set(MONQUE, {\n\t\t\t...existing,\n\t\t\tcronJobs,\n\t\t});\n\t};\n}\n","/**\n * @Worker method decorator\n *\n * Registers a method as a job handler. The method will be called when a job\n * with the matching name is picked up for processing.\n *\n * @param name - Job name (combined with controller namespace if present).\n * @param options - Worker configuration options.\n *\n * @example\n * ```typescript\n * @WorkerController(\"notifications\")\n * export class NotificationWorkers {\n * @Worker(\"push\", { concurrency: 10 })\n * async sendPush(job: Job<PushPayload>) {\n * await pushService.send(job.data);\n * }\n * }\n * ```\n */\nimport { Store } from '@tsed/core';\n\nimport { MONQUE } from '@/constants';\n\nimport type { WorkerDecoratorOptions, WorkerMetadata, WorkerStore } from './types.js';\n\n/**\n * Method decorator that registers a method as a job handler.\n *\n * @param name - The job name (will be prefixed with controller namespace if present)\n * @param options - Optional worker configuration (concurrency, replace, etc.)\n */\nexport function Worker(name: string, options?: WorkerDecoratorOptions): MethodDecorator {\n\treturn <T>(\n\t\ttarget: object,\n\t\tpropertyKey: string | symbol,\n\t\t_descriptor: TypedPropertyDescriptor<T>,\n\t): void => {\n\t\tconst methodName = String(propertyKey);\n\n\t\tconst workerMetadata: WorkerMetadata = {\n\t\t\tname,\n\t\t\tmethod: methodName,\n\t\t\topts: options || {},\n\t\t};\n\n\t\t// Get the class constructor (target is the prototype for instance methods)\n\t\tconst targetConstructor = target.constructor;\n\t\tconst store = Store.from(targetConstructor);\n\n\t\t// Get or initialize the MONQUE store\n\t\tconst existing = store.get<Partial<WorkerStore>>(MONQUE) || {\n\t\t\ttype: 'controller',\n\t\t\tworkers: [],\n\t\t\tcronJobs: [],\n\t\t};\n\n\t\t// Add this worker to the list\n\t\tconst workers = [...(existing.workers || []), workerMetadata];\n\n\t\tstore.set(MONQUE, {\n\t\t\t...existing,\n\t\t\tworkers,\n\t\t});\n\t};\n}\n","/**\n * @WorkerController class decorator\n *\n * Marks a class as containing worker methods and registers it with the Ts.ED DI container.\n * Workers in the class will have their job names prefixed with the namespace.\n *\n * @param namespace - Optional prefix for all job names in this controller.\n * When set, job names become \"{namespace}.{name}\".\n *\n * @example\n * ```typescript\n * @WorkerController(\"email\")\n * export class EmailWorkers {\n * @Worker(\"send\") // Registered as \"email.send\"\n * async send(job: Job<EmailPayload>) { }\n * }\n * ```\n */\nimport { Store, useDecorators } from '@tsed/core';\nimport { Injectable } from '@tsed/di';\n\nimport { MONQUE, ProviderTypes } from '@/constants';\n\nimport type { WorkerStore } from './types.js';\n\n/**\n * Class decorator that registers a class as a worker controller.\n *\n * @param namespace - Optional namespace prefix for job names\n */\nexport function WorkerController(namespace?: string): ClassDecorator {\n\treturn useDecorators(\n\t\t// Register as injectable with custom provider type\n\t\tInjectable({\n\t\t\ttype: ProviderTypes.WORKER_CONTROLLER,\n\t\t}),\n\t\t// Apply custom decorator to store metadata\n\t\t(target: object) => {\n\t\t\tconst store = Store.from(target);\n\n\t\t\t// Get existing store or create new one\n\t\t\tconst existing = store.get<Partial<WorkerStore>>(MONQUE) || {};\n\n\t\t\t// Merge with new metadata, only include namespace if defined\n\t\t\tconst workerStore: WorkerStore = {\n\t\t\t\ttype: 'controller',\n\t\t\t\t...(namespace !== undefined && { namespace }),\n\t\t\t\tworkers: existing.workers || [],\n\t\t\t\tcronJobs: existing.cronJobs || [],\n\t\t\t};\n\n\t\t\tstore.set(MONQUE, workerStore);\n\t\t},\n\t);\n}\n","/**\n * MonqueService - Injectable wrapper for Monque\n *\n * Provides a DI-friendly interface to the Monque job queue.\n * All methods delegate to the underlying Monque instance.\n *\n * @example\n * ```typescript\n * @Service()\n * export class OrderService {\n * @Inject()\n * private monque: MonqueService;\n *\n * async createOrder(data: CreateOrderDto) {\n * const order = await this.save(data);\n * await this.monque.enqueue(\"order.process\", { orderId: order.id });\n * return order;\n * }\n * }\n * ```\n */\n\nimport type {\n\tBulkOperationResult,\n\tCursorOptions,\n\tCursorPage,\n\tEnqueueOptions,\n\tGetJobsFilter,\n\tJobSelector,\n\tMonque,\n\tPersistedJob,\n\tQueueStats,\n\tScheduleOptions,\n} from '@monque/core';\nimport { MonqueError } from '@monque/core';\nimport { Injectable } from '@tsed/di';\nimport { ObjectId } from 'mongodb';\n\n/**\n * Injectable service that wraps the Monque instance.\n *\n * Exposes the full Monque public API through dependency injection.\n */\n@Injectable()\nexport class MonqueService {\n\t/**\n\t * Internal Monque instance (set by MonqueModule)\n\t * @internal\n\t */\n\tprivate _monque: Monque | null = null;\n\n\t/**\n\t * Set the internal Monque instance.\n\t * Called by MonqueModule during initialization.\n\t * @internal\n\t */\n\t_setMonque(monque: Monque): void {\n\t\tthis._monque = monque;\n\t}\n\n\t/**\n\t * Access the underlying Monque instance.\n\t * @throws Error if MonqueModule is not initialized\n\t */\n\tget monque(): Monque {\n\t\tif (!this._monque) {\n\t\t\tthrow new MonqueError(\n\t\t\t\t'MonqueService is not initialized. Ensure MonqueModule is imported and enabled.',\n\t\t\t);\n\t\t}\n\n\t\treturn this._monque;\n\t}\n\n\t// ─────────────────────────────────────────────────────────────────────────────\n\t// Job Scheduling\n\t// ─────────────────────────────────────────────────────────────────────────────\n\n\t/**\n\t * Enqueue a job for processing.\n\t *\n\t * @param name - Job type identifier (use full namespaced name, e.g., \"email.send\")\n\t * @param data - Job payload\n\t * @param options - Scheduling and deduplication options\n\t * @returns The created or existing job document\n\t */\n\tasync enqueue<T>(name: string, data: T, options?: EnqueueOptions): Promise<PersistedJob<T>> {\n\t\treturn this.monque.enqueue(name, data, options);\n\t}\n\n\t/**\n\t * Enqueue a job for immediate processing.\n\t *\n\t * @param name - Job type identifier\n\t * @param data - Job payload\n\t * @returns The created job document\n\t */\n\tasync now<T>(name: string, data: T): Promise<PersistedJob<T>> {\n\t\treturn this.monque.now(name, data);\n\t}\n\n\t/**\n\t * Schedule a recurring job with a cron expression.\n\t *\n\t * @param cron - Cron expression (5-field standard or predefined like @daily)\n\t * @param name - Job type identifier\n\t * @param data - Job payload\n\t * @param options - Scheduling options\n\t * @returns The created job document\n\t */\n\tasync schedule<T>(\n\t\tcron: string,\n\t\tname: string,\n\t\tdata: T,\n\t\toptions?: ScheduleOptions,\n\t): Promise<PersistedJob<T>> {\n\t\treturn this.monque.schedule(cron, name, data, options);\n\t}\n\n\t// ─────────────────────────────────────────────────────────────────────────────\n\t// Job Management (Single Job Operations)\n\t// ─────────────────────────────────────────────────────────────────────────────\n\n\t/**\n\t * Cancel a pending or scheduled job.\n\t *\n\t * @param jobId - The ID of the job to cancel\n\t * @returns The cancelled job, or null if not found\n\t */\n\tasync cancelJob(jobId: string): Promise<PersistedJob<unknown> | null> {\n\t\treturn this.monque.cancelJob(jobId);\n\t}\n\n\t/**\n\t * Retry a failed or cancelled job.\n\t *\n\t * @param jobId - The ID of the job to retry\n\t * @returns The updated job, or null if not found\n\t */\n\tasync retryJob(jobId: string): Promise<PersistedJob<unknown> | null> {\n\t\treturn this.monque.retryJob(jobId);\n\t}\n\n\t/**\n\t * Reschedule a pending job to run at a different time.\n\t *\n\t * @param jobId - The ID of the job to reschedule\n\t * @param runAt - The new Date when the job should run\n\t * @returns The updated job, or null if not found\n\t */\n\tasync rescheduleJob(jobId: string, runAt: Date): Promise<PersistedJob<unknown> | null> {\n\t\treturn this.monque.rescheduleJob(jobId, runAt);\n\t}\n\n\t/**\n\t * Permanently delete a job.\n\t *\n\t * @param jobId - The ID of the job to delete\n\t * @returns true if deleted, false if job not found\n\t */\n\tasync deleteJob(jobId: string): Promise<boolean> {\n\t\treturn this.monque.deleteJob(jobId);\n\t}\n\n\t// ─────────────────────────────────────────────────────────────────────────────\n\t// Job Management (Bulk Operations)\n\t// ─────────────────────────────────────────────────────────────────────────────\n\n\t/**\n\t * Cancel multiple jobs matching the given filter.\n\t *\n\t * @param filter - Selector for which jobs to cancel\n\t * @returns Result with count of cancelled jobs\n\t */\n\tasync cancelJobs(filter: JobSelector): Promise<BulkOperationResult> {\n\t\treturn this.monque.cancelJobs(filter);\n\t}\n\n\t/**\n\t * Retry multiple jobs matching the given filter.\n\t *\n\t * @param filter - Selector for which jobs to retry\n\t * @returns Result with count of retried jobs\n\t */\n\tasync retryJobs(filter: JobSelector): Promise<BulkOperationResult> {\n\t\treturn this.monque.retryJobs(filter);\n\t}\n\n\t/**\n\t * Delete multiple jobs matching the given filter.\n\t *\n\t * @param filter - Selector for which jobs to delete\n\t * @returns Result with count of deleted jobs\n\t */\n\tasync deleteJobs(filter: JobSelector): Promise<BulkOperationResult> {\n\t\treturn this.monque.deleteJobs(filter);\n\t}\n\n\t// ─────────────────────────────────────────────────────────────────────────────\n\t// Job Queries\n\t// ─────────────────────────────────────────────────────────────────────────────\n\n\t/**\n\t * Get a job by its ID.\n\t *\n\t * @param jobId - The job's ObjectId (as string or ObjectId)\n\t * @returns The job document, or null if not found\n\t * @throws MonqueError if jobId is an invalid hex string\n\t */\n\tasync getJob<T>(jobId: string | ObjectId): Promise<PersistedJob<T> | null> {\n\t\tlet id: ObjectId;\n\n\t\tif (typeof jobId === 'string') {\n\t\t\tif (!ObjectId.isValid(jobId)) {\n\t\t\t\tthrow new MonqueError(`Invalid job ID format: ${jobId}`);\n\t\t\t}\n\t\t\tid = ObjectId.createFromHexString(jobId);\n\t\t} else {\n\t\t\tid = jobId;\n\t\t}\n\n\t\treturn this.monque.getJob(id);\n\t}\n\n\t/**\n\t * Query jobs from the queue with optional filters.\n\t *\n\t * @param filter - Optional filter criteria (name, status, limit, skip)\n\t * @returns Array of matching jobs\n\t */\n\tasync getJobs<T>(filter?: GetJobsFilter): Promise<PersistedJob<T>[]> {\n\t\treturn this.monque.getJobs(filter);\n\t}\n\n\t/**\n\t * Get a paginated list of jobs using opaque cursors.\n\t *\n\t * @param options - Pagination options (cursor, limit, direction, filter)\n\t * @returns Page of jobs with next/prev cursors\n\t */\n\tasync getJobsWithCursor<T>(options?: CursorOptions): Promise<CursorPage<T>> {\n\t\treturn this.monque.getJobsWithCursor(options);\n\t}\n\n\t/**\n\t * Get aggregate statistics for the job queue.\n\t *\n\t * @param filter - Optional filter to scope statistics by job name\n\t * @returns Queue statistics\n\t */\n\tasync getQueueStats(filter?: Pick<JobSelector, 'name'>): Promise<QueueStats> {\n\t\treturn this.monque.getQueueStats(filter);\n\t}\n\n\t// ─────────────────────────────────────────────────────────────────────────────\n\t// Health Check\n\t// ─────────────────────────────────────────────────────────────────────────────\n\n\t/**\n\t * Check if the scheduler is healthy and running.\n\t *\n\t * @returns true if running and connected\n\t */\n\tisHealthy(): boolean {\n\t\treturn this.monque.isHealthy();\n\t}\n}\n","/**\n * Build the full job name by combining namespace and name.\n *\n * @param namespace - Optional namespace from @WorkerController\n * @param name - Job name from @Worker or @Cron\n * @returns Full job name (e.g., \"email.send\" or just \"send\")\n *\n * @example\n * ```typescript\n * buildJobName(\"email\", \"send\"); // \"email.send\"\n * buildJobName(undefined, \"send\"); // \"send\"\n * buildJobName(\"\", \"send\"); // \"send\"\n * ```\n */\nexport function buildJobName(namespace: string | undefined, name: string): string {\n\treturn namespace ? `${namespace}.${name}` : name;\n}\n","/**\n * Collect worker metadata utility\n *\n * Collects all worker metadata from a class decorated with @WorkerController.\n * Used by MonqueModule to discover and register all workers.\n */\nimport { Store } from '@tsed/core';\n\nimport { MONQUE } from '@/constants';\nimport type { CronDecoratorOptions, WorkerDecoratorOptions, WorkerStore } from '@/decorators';\n\nimport { buildJobName } from './build-job-name.js';\n\n/**\n * Collected worker registration info ready for Monque.register()\n */\nexport interface CollectedWorkerMetadata {\n\t/**\n\t * Full job name (with namespace prefix if applicable)\n\t */\n\tfullName: string;\n\n\t/**\n\t * Method name on the controller class\n\t */\n\tmethod: string;\n\n\t/**\n\t * Worker options to pass to Monque.register()\n\t */\n\topts: WorkerDecoratorOptions | CronDecoratorOptions;\n\n\t/**\n\t * Whether this is a cron job\n\t */\n\tisCron: boolean;\n\n\t/**\n\t * Cron pattern (only for cron jobs)\n\t */\n\tcronPattern?: string;\n}\n\n/**\n * Collect all worker metadata from a class.\n *\n * @param target - The class constructor (decorated with @WorkerController)\n * @returns Array of collected worker metadata ready for registration\n *\n * @example\n * ```typescript\n * const metadata = collectWorkerMetadata(EmailWorkers);\n * // Returns:\n * // [\n * // { fullName: \"email.send\", method: \"sendEmail\", opts: {}, isCron: false },\n * // { fullName: \"email.daily-digest\", method: \"sendDailyDigest\", opts: {}, isCron: true, cronPattern: \"0 9 * * *\" }\n * // ]\n * ```\n */\nexport function collectWorkerMetadata(\n\ttarget: new (...args: unknown[]) => unknown,\n): CollectedWorkerMetadata[] {\n\tconst store = Store.from(target);\n\tconst workerStore = store.get<WorkerStore>(MONQUE);\n\n\tif (!workerStore) {\n\t\treturn [];\n\t}\n\n\tconst results: CollectedWorkerMetadata[] = [];\n\tconst namespace = workerStore.namespace;\n\n\t// Collect regular workers\n\tfor (const worker of workerStore.workers) {\n\t\tresults.push({\n\t\t\tfullName: buildJobName(namespace, worker.name),\n\t\t\tmethod: worker.method,\n\t\t\topts: worker.opts,\n\t\t\tisCron: false,\n\t\t});\n\t}\n\n\t// Collect cron jobs\n\tfor (const cron of workerStore.cronJobs) {\n\t\tresults.push({\n\t\t\tfullName: buildJobName(namespace, cron.name),\n\t\t\tmethod: cron.method,\n\t\t\topts: cron.opts,\n\t\t\tisCron: true,\n\t\t\tcronPattern: cron.pattern,\n\t\t});\n\t}\n\n\treturn results;\n}\n","/**\n * Generate a unique token for a worker controller.\n *\n * Used internally by Ts.ED DI to identify worker controller providers.\n * The token is based on the class name for debugging purposes.\n *\n * @param target - The class constructor\n * @returns A Symbol token unique to this worker controller\n *\n * @example\n * ```typescript\n * @WorkerController(\"email\")\n * class EmailWorkers {}\n *\n * const token = getWorkerToken(EmailWorkers);\n * // Symbol(\"monque:worker:EmailWorkers\")\n * ```\n */\nexport function getWorkerToken(target: new (...args: unknown[]) => unknown): symbol {\n\tconst name = target.name?.trim();\n\n\tif (!name) {\n\t\tthrow new Error('Worker class must have a non-empty name');\n\t}\n\n\treturn Symbol.for(`monque:worker:${name}`);\n}\n","/**\n * @monque/tsed - Type Guards\n *\n * Utilities for duck-typing Mongoose and MongoDB related objects\n * to avoid hard dependencies on @tsed/mongoose.\n */\n\nimport type { Db } from 'mongodb';\n\n/**\n * Interface representing a Mongoose Connection object.\n * We only care that it has a `db` property which is a MongoDB Db instance.\n */\nexport interface MongooseConnection {\n\tdb: Db;\n}\n\n/**\n * Interface representing the @tsed/mongoose MongooseService.\n * It acts as a registry/factory for connections.\n */\nexport interface MongooseService {\n\t/**\n\t * Get a connection by its ID (configuration key).\n\t * @param id The connection ID (default: \"default\")\n\t */\n\tget(id?: string): MongooseConnection | undefined;\n}\n\n/**\n * Type guard to check if an object acts like a Mongoose Service.\n *\n * Checks if the object has a `get` method.\n *\n * @param value The value to check\n */\nexport function isMongooseService(value: unknown): value is MongooseService {\n\treturn (\n\t\ttypeof value === 'object' &&\n\t\tvalue !== null &&\n\t\t'get' in value &&\n\t\ttypeof (value as MongooseService).get === 'function'\n\t);\n}\n\n/**\n * Type guard to check if an object acts like a Mongoose Connection.\n *\n * Checks if the object has a `db` property.\n *\n * @param value The value to check\n */\nexport function isMongooseConnection(value: unknown): value is MongooseConnection {\n\treturn (\n\t\ttypeof value === 'object' &&\n\t\tvalue !== null &&\n\t\t'db' in value &&\n\t\ttypeof (value as MongooseConnection).db === 'object' &&\n\t\t(value as MongooseConnection).db !== null &&\n\t\ttypeof (value as MongooseConnection).db.collection === 'function'\n\t);\n}\n","/**\n * @monque/tsed - Database Resolution Utility\n *\n * Multi-strategy database resolution for flexible MongoDB connection handling.\n */\n\nimport type { TokenProvider } from '@tsed/di';\nimport type { Db } from 'mongodb';\n\nimport type { MonqueTsedConfig } from '@/config';\n\nimport { isMongooseConnection, isMongooseService } from './guards.js';\n\n/**\n * Type for the injector function used to resolve DI tokens.\n */\nexport type InjectorFn = <T>(token: TokenProvider<T>) => T | undefined;\n\n/**\n * Resolve the MongoDB database instance from the configuration.\n *\n * Supports three resolution strategies:\n * 1. **Direct `db`**: Returns the provided Db instance directly\n * 2. **Factory `dbFactory`**: Calls the factory function (supports async)\n * 3. **DI Token `dbToken`**: Resolves the Db from the DI container\n *\n * @param config - The Monque configuration containing database settings\n * @param injectorFn - Optional function to resolve DI tokens (required for dbToken strategy)\n * @returns The resolved MongoDB Db instance\n * @throws Error if no database strategy is provided or if DI resolution fails\n *\n * @example\n * ```typescript\n * // Direct Db instance\n * const db = await resolveDatabase({ db: mongoDb });\n *\n * // Factory function\n * const db = await resolveDatabase({\n * dbFactory: async () => {\n * const client = await MongoClient.connect(uri);\n * return client.db(\"myapp\");\n * }\n * });\n *\n * // DI token\n * const db = await resolveDatabase(\n * { dbToken: \"MONGODB_DATABASE\" },\n * (token) => injector.get(token)\n * );\n * ```\n */\nexport async function resolveDatabase(\n\tconfig: MonqueTsedConfig,\n\tinjectorFn?: InjectorFn,\n): Promise<Db> {\n\t// Strategy 1: Direct Db instance\n\tif (config.db) {\n\t\treturn config.db;\n\t}\n\n\t// Strategy 2: Factory function (sync or async)\n\tif (config.dbFactory) {\n\t\treturn config.dbFactory();\n\t}\n\n\t// Strategy 3: DI token resolution\n\tif (config.dbToken) {\n\t\tif (!injectorFn) {\n\t\t\tthrow new Error(\n\t\t\t\t'MonqueTsedConfig.dbToken requires an injector function to resolve the database',\n\t\t\t);\n\t\t}\n\n\t\tconst resolved = injectorFn(config.dbToken);\n\n\t\tif (!resolved) {\n\t\t\tthrow new Error(\n\t\t\t\t`Could not resolve database from token: ${String(config.dbToken)}. ` +\n\t\t\t\t\t'Make sure the provider is registered in the DI container.',\n\t\t\t);\n\t\t}\n\n\t\tif (isMongooseService(resolved)) {\n\t\t\t// Check for Mongoose Service (duck typing)\n\t\t\t// It has a get() method that returns a connection\n\t\t\tconst connectionId = config.mongooseConnectionId || 'default';\n\t\t\tconst connection = resolved.get(connectionId);\n\n\t\t\tif (!connection) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`MongooseService resolved from token \"${String(config.dbToken)}\" returned no connection for ID \"${connectionId}\". ` +\n\t\t\t\t\t\t'Ensure the connection ID is correct and the connection is established.',\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif ('db' in connection && connection.db) {\n\t\t\t\treturn connection.db as Db;\n\t\t\t}\n\t\t}\n\n\t\tif (isMongooseConnection(resolved)) {\n\t\t\t// Check for Mongoose Connection (duck typing)\n\t\t\t// It has a db property that is the native Db instance\n\t\t\treturn resolved.db as Db;\n\t\t}\n\n\t\t// Default: Assume it is a native Db instance\n\t\tif (typeof resolved !== 'object' || resolved === null || !('collection' in resolved)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Resolved value from token \"${String(config.dbToken)}\" does not appear to be a valid MongoDB Db instance.`,\n\t\t\t);\n\t\t}\n\n\t\treturn resolved as Db;\n\t}\n\n\t// No strategy provided\n\tthrow new Error(\"MonqueTsedConfig requires 'db', 'dbFactory', or 'dbToken' to be set\");\n}\n","/**\n * MonqueModule - Main Integration Module\n *\n * Orchestrates the integration between Monque and Ts.ED.\n * Handles lifecycle hooks, configuration resolution, and worker registration.\n */\n\nimport {\n\ttype Job,\n\tMonque,\n\ttype MonqueOptions,\n\ttype ScheduleOptions,\n\ttype WorkerOptions,\n} from '@monque/core';\nimport {\n\tConfiguration,\n\tDIContext,\n\tInject,\n\tInjectorService,\n\tLOGGER,\n\tModule,\n\ttype OnDestroy,\n\ttype OnInit,\n\tProviderScope,\n\trunInContext,\n\ttype TokenProvider,\n} from '@tsed/di';\n\nimport { type MonqueTsedConfig, validateDatabaseConfig } from '@/config';\nimport { ProviderTypes } from '@/constants';\nimport { MonqueService } from '@/services';\nimport { collectWorkerMetadata, resolveDatabase } from '@/utils';\n\n@Module({\n\timports: [MonqueService],\n})\nexport class MonqueModule implements OnInit, OnDestroy {\n\tprotected injector: InjectorService;\n\tprotected monqueService: MonqueService;\n\tprotected logger: LOGGER;\n\tprotected monqueConfig: MonqueTsedConfig;\n\n\tprotected monque: Monque | null = null;\n\n\tconstructor(\n\t\t@Inject(InjectorService) injector: InjectorService,\n\t\t@Inject(MonqueService) monqueService: MonqueService,\n\t\t@Inject(LOGGER) logger: LOGGER,\n\t\t@Inject(Configuration) configuration: Configuration,\n\t) {\n\t\tthis.injector = injector;\n\t\tthis.monqueService = monqueService;\n\t\tthis.logger = logger;\n\t\tthis.monqueConfig = configuration.get<MonqueTsedConfig>('monque') || {};\n\t}\n\n\tasync $onInit(): Promise<void> {\n\t\tconst config = this.monqueConfig;\n\n\t\tif (config?.enabled === false) {\n\t\t\tthis.logger.info('Monque integration is disabled');\n\n\t\t\treturn;\n\t\t}\n\n\t\tvalidateDatabaseConfig(config);\n\n\t\ttry {\n\t\t\tconst db = await resolveDatabase(config, (token) =>\n\t\t\t\tthis.injector.get(token as TokenProvider),\n\t\t\t);\n\n\t\t\t// We construct the options object carefully to match MonqueOptions\n\t\t\tconst { db: _db, ...restConfig } = config;\n\t\t\tconst options: MonqueOptions = restConfig;\n\n\t\t\tthis.monque = new Monque(db, options);\n\t\t\tthis.monqueService._setMonque(this.monque);\n\n\t\t\tthis.logger.info('Monque: Connecting to MongoDB...');\n\t\t\tawait this.monque.initialize();\n\n\t\t\tawait this.registerWorkers();\n\n\t\t\tawait this.monque.start();\n\n\t\t\tthis.logger.info('Monque: Started successfully');\n\t\t} catch (error) {\n\t\t\tthis.logger.error({\n\t\t\t\tevent: 'MONQUE_INIT_ERROR',\n\t\t\t\tmessage: 'Failed to initialize Monque',\n\t\t\t\terror,\n\t\t\t});\n\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tasync $onDestroy(): Promise<void> {\n\t\tif (this.monque) {\n\t\t\tthis.logger.info('Monque: Stopping...');\n\n\t\t\tawait this.monque.stop();\n\n\t\t\tthis.logger.info('Monque: Stopped');\n\t\t}\n\t}\n\n\t/**\n\t * Discover and register all workers from @WorkerController providers\n\t */\n\tprotected async registerWorkers(): Promise<void> {\n\t\tif (!this.monque) {\n\t\t\tthrow new Error('Monque instance not initialized');\n\t\t}\n\n\t\tconst monque = this.monque;\n\t\tconst workerControllers = this.injector.getProviders(ProviderTypes.WORKER_CONTROLLER);\n\t\tconst registeredJobs = new Set<string>();\n\n\t\tthis.logger.info(`Monque: Found ${workerControllers.length} worker controllers`);\n\n\t\tfor (const provider of workerControllers) {\n\t\t\tconst useClass = provider.useClass;\n\t\t\tconst workers = collectWorkerMetadata(useClass);\n\t\t\t// Try to resolve singleton instance immediately\n\t\t\tconst instance = this.injector.get(provider.token);\n\n\t\t\tif (!instance && provider.scope !== ProviderScope.REQUEST) {\n\t\t\t\tthis.logger.warn(\n\t\t\t\t\t`Monque: Could not resolve instance for controller ${provider.name}. Skipping.`,\n\t\t\t\t);\n\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tfor (const worker of workers) {\n\t\t\t\tconst { fullName, method, opts, isCron, cronPattern } = worker;\n\n\t\t\t\tif (registeredJobs.has(fullName)) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Monque: Duplicate job registration detected. Job \"${fullName}\" is already registered.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tregisteredJobs.add(fullName);\n\n\t\t\t\tconst handler = async (job: Job) => {\n\t\t\t\t\tconst $ctx = new DIContext({\n\t\t\t\t\t\tinjector: this.injector,\n\t\t\t\t\t\tid: job._id?.toString() || 'unknown',\n\t\t\t\t\t});\n\t\t\t\t\t$ctx.set('MONQUE_JOB', job);\n\t\t\t\t\t$ctx.container.set(DIContext, $ctx);\n\n\t\t\t\t\tawait runInContext($ctx, async () => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tlet targetInstance = instance;\n\t\t\t\t\t\t\tif (provider.scope === ProviderScope.REQUEST || !targetInstance) {\n\t\t\t\t\t\t\t\ttargetInstance = await this.injector.invoke(provider.token, {\n\t\t\t\t\t\t\t\t\tlocals: $ctx.container,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tconst typedInstance = targetInstance as Record<string, (job: Job) => unknown>;\n\n\t\t\t\t\t\t\tif (typedInstance && typeof typedInstance[method] === 'function') {\n\t\t\t\t\t\t\t\tawait typedInstance[method](job);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tthis.logger.error({\n\t\t\t\t\t\t\t\tevent: 'MONQUE_JOB_ERROR',\n\t\t\t\t\t\t\t\tjobName: fullName,\n\t\t\t\t\t\t\t\tjobId: job._id,\n\t\t\t\t\t\t\t\tmessage: `Error processing job ${fullName}`,\n\t\t\t\t\t\t\t\terror,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\tawait $ctx.destroy();\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t};\n\n\t\t\t\tif (isCron && cronPattern) {\n\t\t\t\t\tthis.logger.debug(`Monque: Registering cron job \"${fullName}\" (${cronPattern})`);\n\n\t\t\t\t\tmonque.register(fullName, handler, opts as WorkerOptions);\n\t\t\t\t\tawait monque.schedule(cronPattern, fullName, {}, opts as ScheduleOptions);\n\t\t\t\t} else {\n\t\t\t\t\tthis.logger.debug(`Monque: Registering worker \"${fullName}\"`);\n\t\t\t\t\tmonque.register(fullName, handler, opts as WorkerOptions);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthis.logger.info(`Monque: Registered ${registeredJobs.size} jobs`);\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA6CA,SAAgB,uBAAuB,QAAgC;CACtE,MAAM,aAAa;EAAC,OAAO;EAAI,OAAO;EAAW,OAAO;EAAQ,CAAC,OAAO,QAAQ;AAEhF,KAAI,WAAW,WAAW,EACzB,OAAM,IAAI,MACT,qFACA;AAGF,KAAI,WAAW,SAAS,EACvB,OAAM,IAAI,MACT,gGACA;;;;;;;;;;;;;;;;AC9CH,MAAa,SAAS,OAAO,IAAI,SAAS;;;;;;;;;;;;;;ACD1C,MAAa,gBAAgB;CAE5B,mBAAmB;CAEnB,MAAM;CACN;;;;;;;;;;;;;;;;;;;;;ACOD,SAAgB,KAAK,SAAiB,SAAiD;AACtF,SACC,QACA,aACA,gBACU;EACV,MAAM,aAAa,OAAO,YAAY;EAEtC,MAAM,eAA6B;GAClC;GAEA,MAAM,SAAS,QAAQ;GACvB,QAAQ;GACR,MAAM,WAAW,EAAE;GACnB;EAG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|
+
{
|
|
2
|
+
"name": "@monque/tsed",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Ts.ED integration for Monque - A robust, type-safe MongoDB job queue for TypeScript",
|
|
5
|
+
"author": "Maurice de Bruyn <debruyn.maurice@gmail.com>",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/ueberBrot/monque.git",
|
|
9
|
+
"directory": "packages/tsed"
|
|
10
|
+
},
|
|
11
|
+
"license": "ISC",
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/ueberBrot/monque/issues"
|
|
14
|
+
},
|
|
15
|
+
"homepage": "https://github.com/ueberBrot/monque#readme",
|
|
16
|
+
"sideEffects": false,
|
|
17
|
+
"type": "module",
|
|
18
|
+
"engines": {
|
|
19
|
+
"node": ">=22.0.0"
|
|
20
|
+
},
|
|
21
|
+
"publishConfig": {
|
|
22
|
+
"access": "public"
|
|
23
|
+
},
|
|
24
|
+
"keywords": [
|
|
25
|
+
"tsed",
|
|
26
|
+
"tsed-module",
|
|
27
|
+
"monque",
|
|
28
|
+
"mongodb",
|
|
29
|
+
"queue",
|
|
30
|
+
"job-queue",
|
|
31
|
+
"worker",
|
|
32
|
+
"background-jobs",
|
|
33
|
+
"cron",
|
|
34
|
+
"scheduler",
|
|
35
|
+
"typescript"
|
|
36
|
+
],
|
|
37
|
+
"main": "./dist/index.cjs",
|
|
38
|
+
"module": "./dist/index.mjs",
|
|
39
|
+
"types": "./dist/index.d.mts",
|
|
40
|
+
"exports": {
|
|
41
|
+
".": {
|
|
42
|
+
"import": {
|
|
43
|
+
"types": "./dist/index.d.mts",
|
|
44
|
+
"default": "./dist/index.mjs"
|
|
45
|
+
},
|
|
46
|
+
"require": {
|
|
47
|
+
"types": "./dist/index.d.cts",
|
|
48
|
+
"default": "./dist/index.cjs"
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
},
|
|
52
|
+
"files": [
|
|
53
|
+
"dist",
|
|
54
|
+
"src"
|
|
55
|
+
],
|
|
56
|
+
"scripts": {
|
|
57
|
+
"build": "tsdown",
|
|
58
|
+
"check:exports": "publint && attw --pack .",
|
|
59
|
+
"clean": "rimraf dist coverage .turbo",
|
|
60
|
+
"type-check": "tsc --noEmit",
|
|
61
|
+
"pretest": "bun run type-check",
|
|
62
|
+
"test": "vitest run",
|
|
63
|
+
"test:unit": "bun run type-check && vitest run --config vitest.unit.config.ts --coverage.enabled=false",
|
|
64
|
+
"test:integration": "bun run type-check && vitest run tests/integration --coverage.enabled=false",
|
|
65
|
+
"test:watch": "vitest",
|
|
66
|
+
"test:watch:unit": "vitest --config vitest.unit.config.ts",
|
|
67
|
+
"test:watch:integration": "vitest tests/integration",
|
|
68
|
+
"lint": "biome check ."
|
|
69
|
+
},
|
|
70
|
+
"peerDependencies": {
|
|
71
|
+
"@monque/core": "^1.1.2",
|
|
72
|
+
"@tsed/core": "^8.24.1",
|
|
73
|
+
"@tsed/di": "^8.24.1",
|
|
74
|
+
"@tsed/mongoose": "^8.24.1",
|
|
75
|
+
"mongodb": "^7.0.0"
|
|
76
|
+
},
|
|
77
|
+
"peerDependenciesMeta": {
|
|
78
|
+
"@tsed/mongoose": {
|
|
79
|
+
"optional": true
|
|
80
|
+
}
|
|
81
|
+
},
|
|
82
|
+
"devDependencies": {
|
|
83
|
+
"@monque/core": "workspace:*",
|
|
84
|
+
"@testcontainers/mongodb": "^11.11.0",
|
|
85
|
+
"@total-typescript/ts-reset": "^0.6.1",
|
|
86
|
+
"@tsed/core": "^8.24.1",
|
|
87
|
+
"@tsed/di": "^8.24.1",
|
|
88
|
+
"@tsed/mongoose": "^8.24.1",
|
|
89
|
+
"@tsed/platform-http": "^8.24.1",
|
|
90
|
+
"@tsed/testcontainers-mongo": "^8.24.1",
|
|
91
|
+
"@types/bun": "^1.3.7",
|
|
92
|
+
"@vitest/coverage-v8": "^4.0.18",
|
|
93
|
+
"mongodb": "^7.0.0",
|
|
94
|
+
"testcontainers": "^11.11.0",
|
|
95
|
+
"tsdown": "^0.20.1",
|
|
96
|
+
"vitest": "^4.0.18"
|
|
97
|
+
}
|
|
98
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @monque/tsed - Configuration
|
|
3
|
+
*
|
|
4
|
+
* Defines the configuration interface and TsED module augmentation.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import type { MonqueTsedConfig } from './types.js';
|
|
8
|
+
|
|
9
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
10
|
+
// TsED Module Augmentation
|
|
11
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Augment TsED's Configuration interface to include monque settings.
|
|
15
|
+
*
|
|
16
|
+
* This allows type-safe configuration via @Configuration decorator.
|
|
17
|
+
*/
|
|
18
|
+
declare global {
|
|
19
|
+
namespace TsED {
|
|
20
|
+
interface Configuration {
|
|
21
|
+
/**
|
|
22
|
+
* Monque job queue configuration.
|
|
23
|
+
*/
|
|
24
|
+
monque?: MonqueTsedConfig;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
30
|
+
// Validation
|
|
31
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Validate that exactly one database resolution strategy is provided.
|
|
35
|
+
*
|
|
36
|
+
* @param config - The configuration to validate.
|
|
37
|
+
* @throws Error if zero or multiple strategies are provided.
|
|
38
|
+
*
|
|
39
|
+
* @example
|
|
40
|
+
* ```typescript
|
|
41
|
+
* validateDatabaseConfig({ db: mongoDb }); // OK
|
|
42
|
+
* validateDatabaseConfig({}); // throws
|
|
43
|
+
* validateDatabaseConfig({ db: mongoDb, dbFactory: fn }); // throws
|
|
44
|
+
* ```
|
|
45
|
+
*/
|
|
46
|
+
export function validateDatabaseConfig(config: MonqueTsedConfig): void {
|
|
47
|
+
const strategies = [config.db, config.dbFactory, config.dbToken].filter(Boolean);
|
|
48
|
+
|
|
49
|
+
if (strategies.length === 0) {
|
|
50
|
+
throw new Error(
|
|
51
|
+
"MonqueTsedConfig requires exactly one of 'db', 'dbFactory', or 'dbToken' to be set",
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
if (strategies.length > 1) {
|
|
56
|
+
throw new Error(
|
|
57
|
+
"MonqueTsedConfig accepts only one of 'db', 'dbFactory', or 'dbToken' - multiple were provided",
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @monque/tsed - Configuration Types
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import type { MonqueOptions } from '@monque/core';
|
|
6
|
+
import type { TokenProvider } from '@tsed/di';
|
|
7
|
+
import type { Db } from 'mongodb';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Configuration options for @monque/tsed.
|
|
11
|
+
*
|
|
12
|
+
* Extends MonqueOptions with Ts.ED-specific settings for database resolution
|
|
13
|
+
* and module behavior.
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* ```typescript
|
|
17
|
+
* @Configuration({
|
|
18
|
+
* monque: {
|
|
19
|
+
* db: mongoClient.db("myapp"),
|
|
20
|
+
* collectionName: "jobs",
|
|
21
|
+
* defaultConcurrency: 5
|
|
22
|
+
* }
|
|
23
|
+
* })
|
|
24
|
+
* export class Server {}
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
27
|
+
export interface MonqueTsedConfig extends Omit<MonqueOptions, 'db'> {
|
|
28
|
+
/**
|
|
29
|
+
* Enable or disable the Monque module.
|
|
30
|
+
*
|
|
31
|
+
* When disabled:
|
|
32
|
+
* - Workers are not registered
|
|
33
|
+
* - Lifecycle hooks are no-ops
|
|
34
|
+
* - MonqueService throws on access
|
|
35
|
+
*
|
|
36
|
+
* @default true
|
|
37
|
+
*/
|
|
38
|
+
enabled?: boolean;
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Direct MongoDB database instance.
|
|
42
|
+
*
|
|
43
|
+
* Use when you have a pre-connected Db object available synchronously.
|
|
44
|
+
*
|
|
45
|
+
* @example
|
|
46
|
+
* ```typescript
|
|
47
|
+
* @Configuration({
|
|
48
|
+
* monque: {
|
|
49
|
+
* db: mongoClient.db("myapp"),
|
|
50
|
+
* collectionName: "jobs"
|
|
51
|
+
* }
|
|
52
|
+
* })
|
|
53
|
+
* ```
|
|
54
|
+
*/
|
|
55
|
+
db?: Db;
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Factory function to create the database connection.
|
|
59
|
+
*
|
|
60
|
+
* Called once during module initialization. Supports async factories
|
|
61
|
+
* for connection pooling or lazy initialization.
|
|
62
|
+
*
|
|
63
|
+
* @example
|
|
64
|
+
* ```typescript
|
|
65
|
+
* @Configuration({
|
|
66
|
+
* monque: {
|
|
67
|
+
* dbFactory: async () => {
|
|
68
|
+
* const client = await MongoClient.connect(process.env.MONGO_URI!);
|
|
69
|
+
* return client.db("myapp");
|
|
70
|
+
* }
|
|
71
|
+
* }
|
|
72
|
+
* })
|
|
73
|
+
* ```
|
|
74
|
+
*/
|
|
75
|
+
dbFactory?: () => Promise<Db> | Db;
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* DI token to inject the Db instance from the container.
|
|
79
|
+
*
|
|
80
|
+
* Use when your application already has a MongoDB provider registered
|
|
81
|
+
* in the DI container.
|
|
82
|
+
*
|
|
83
|
+
* Can also be used to inject a MongooseService or Connection.
|
|
84
|
+
*
|
|
85
|
+
* @example
|
|
86
|
+
* ```typescript
|
|
87
|
+
* // First, register a MongoDB provider
|
|
88
|
+
* registerProvider({
|
|
89
|
+
* provide: "MONGODB_DATABASE",
|
|
90
|
+
* useFactory: async () => {
|
|
91
|
+
* const client = await MongoClient.connect(uri);
|
|
92
|
+
* return client.db("myapp");
|
|
93
|
+
* }
|
|
94
|
+
* });
|
|
95
|
+
*
|
|
96
|
+
* // Then reference it in config
|
|
97
|
+
* @Configuration({
|
|
98
|
+
* monque: {
|
|
99
|
+
* dbToken: "MONGODB_DATABASE"
|
|
100
|
+
* }
|
|
101
|
+
* })
|
|
102
|
+
* ```
|
|
103
|
+
*/
|
|
104
|
+
dbToken?: TokenProvider<Db> | string;
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Connection ID of the Mongoose connection to use.
|
|
108
|
+
*
|
|
109
|
+
* Requires the use of `dbToken` pointing to `MongooseService`.
|
|
110
|
+
*
|
|
111
|
+
* @default "default"
|
|
112
|
+
*/
|
|
113
|
+
mongooseConnectionId?: string;
|
|
114
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Symbol used to store decorator metadata on class constructors.
|
|
3
|
+
*
|
|
4
|
+
* Used by @WorkerController, @Worker, and @Cron decorators to attach
|
|
5
|
+
* metadata that is later collected by MonqueModule during initialization.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```typescript
|
|
9
|
+
* Store.from(Class).set(MONQUE, metadata);
|
|
10
|
+
* ```
|
|
11
|
+
*/
|
|
12
|
+
export const MONQUE = Symbol.for('monque');
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Provider type constants for DI scanning.
|
|
3
|
+
*
|
|
4
|
+
* These constants are used to categorize providers registered with Ts.ED's
|
|
5
|
+
* dependency injection container, enabling MonqueModule to discover and
|
|
6
|
+
* register workers automatically.
|
|
7
|
+
*
|
|
8
|
+
* Note: Using string constants with `as const` instead of enums per
|
|
9
|
+
* Constitution guidelines.
|
|
10
|
+
*/
|
|
11
|
+
export const ProviderTypes = {
|
|
12
|
+
/** Provider type for @WorkerController decorated classes */
|
|
13
|
+
WORKER_CONTROLLER: 'monque:worker-controller',
|
|
14
|
+
/** Provider type for cron job handlers */
|
|
15
|
+
CRON: 'monque:cron',
|
|
16
|
+
} as const;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Union type of all provider type values.
|
|
20
|
+
*/
|
|
21
|
+
export type ProviderType = (typeof ProviderTypes)[keyof typeof ProviderTypes];
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { Store } from '@tsed/core';
|
|
2
|
+
|
|
3
|
+
import { MONQUE } from '@/constants';
|
|
4
|
+
import type { CronDecoratorOptions, CronMetadata, WorkerStore } from '@/decorators/types.js';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Method decorator that registers a method as a scheduled cron job.
|
|
8
|
+
*
|
|
9
|
+
* @param pattern - Cron expression (e.g., "* * * * *", "@daily")
|
|
10
|
+
* @param options - Optional cron configuration (name, timezone, etc.)
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```typescript
|
|
14
|
+
* @WorkerController()
|
|
15
|
+
* class ReportWorkers {
|
|
16
|
+
* @Cron("@daily", { timezone: "UTC" })
|
|
17
|
+
* async generateDailyReport() {
|
|
18
|
+
* // ...
|
|
19
|
+
* }
|
|
20
|
+
* }
|
|
21
|
+
* ```
|
|
22
|
+
*/
|
|
23
|
+
export function Cron(pattern: string, options?: CronDecoratorOptions): MethodDecorator {
|
|
24
|
+
return <T>(
|
|
25
|
+
target: object,
|
|
26
|
+
propertyKey: string | symbol,
|
|
27
|
+
_descriptor: TypedPropertyDescriptor<T>,
|
|
28
|
+
): void => {
|
|
29
|
+
const methodName = String(propertyKey);
|
|
30
|
+
|
|
31
|
+
const cronMetadata: CronMetadata = {
|
|
32
|
+
pattern,
|
|
33
|
+
// Default name to method name if not provided
|
|
34
|
+
name: options?.name || methodName,
|
|
35
|
+
method: methodName,
|
|
36
|
+
opts: options || {},
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
// Get the class constructor (target is the prototype for instance methods)
|
|
40
|
+
const targetConstructor = target.constructor;
|
|
41
|
+
const store = Store.from(targetConstructor);
|
|
42
|
+
|
|
43
|
+
// Get or initialize the MONQUE store
|
|
44
|
+
const existing = store.get<Partial<WorkerStore>>(MONQUE) || {
|
|
45
|
+
type: 'controller',
|
|
46
|
+
workers: [],
|
|
47
|
+
cronJobs: [],
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
// Add this cron job to the list
|
|
51
|
+
const cronJobs = [...(existing.cronJobs || []), cronMetadata];
|
|
52
|
+
|
|
53
|
+
store.set(MONQUE, {
|
|
54
|
+
...existing,
|
|
55
|
+
cronJobs,
|
|
56
|
+
});
|
|
57
|
+
};
|
|
58
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export { Cron } from './cron.js';
|
|
2
|
+
export type {
|
|
3
|
+
CronDecoratorOptions,
|
|
4
|
+
CronMetadata,
|
|
5
|
+
WorkerDecoratorOptions,
|
|
6
|
+
WorkerMetadata,
|
|
7
|
+
WorkerStore,
|
|
8
|
+
} from './types.js';
|
|
9
|
+
export { Worker } from './worker.js';
|
|
10
|
+
export { WorkerController } from './worker-controller.js';
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @monque/tsed - Decorator Types
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import type { WorkerOptions as CoreWorkerOptions, ScheduleOptions } from '@monque/core';
|
|
6
|
+
|
|
7
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
8
|
+
// Worker Decorator Options
|
|
9
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Options for the @Worker method decorator.
|
|
13
|
+
*
|
|
14
|
+
* Maps to @monque/core WorkerOptions. All standard Monque worker options
|
|
15
|
+
* are exposed here for decorator-based configuration.
|
|
16
|
+
*/
|
|
17
|
+
export interface WorkerDecoratorOptions extends CoreWorkerOptions {}
|
|
18
|
+
|
|
19
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
20
|
+
// Worker Metadata
|
|
21
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Metadata for a single @Worker decorated method.
|
|
25
|
+
*
|
|
26
|
+
* Stored in the WorkerStore and used by MonqueModule to register workers.
|
|
27
|
+
*/
|
|
28
|
+
export interface WorkerMetadata {
|
|
29
|
+
/**
|
|
30
|
+
* Job name (without namespace prefix).
|
|
31
|
+
* Combined with controller namespace to form full job name.
|
|
32
|
+
*/
|
|
33
|
+
name: string;
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Method name on the controller class.
|
|
37
|
+
*/
|
|
38
|
+
method: string;
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Worker options forwarded to Monque.register().
|
|
42
|
+
*/
|
|
43
|
+
opts: WorkerDecoratorOptions;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
47
|
+
// Cron Decorator Options
|
|
48
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Options for the @Cron method decorator.
|
|
52
|
+
*
|
|
53
|
+
* Maps to @monque/core ScheduleOptions with additional metadata overrides.
|
|
54
|
+
*/
|
|
55
|
+
export interface CronDecoratorOptions extends ScheduleOptions {
|
|
56
|
+
/**
|
|
57
|
+
* Override job name (defaults to method name).
|
|
58
|
+
*/
|
|
59
|
+
name?: string;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
63
|
+
// Cron Metadata
|
|
64
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Metadata for a single @Cron decorated method.
|
|
68
|
+
*
|
|
69
|
+
* Stored in the WorkerStore and used by MonqueModule to schedule cron jobs.
|
|
70
|
+
*/
|
|
71
|
+
export interface CronMetadata {
|
|
72
|
+
/**
|
|
73
|
+
* Cron expression (5-field standard or predefined like @daily).
|
|
74
|
+
*/
|
|
75
|
+
pattern: string;
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Job name (defaults to method name if not specified in options).
|
|
79
|
+
*/
|
|
80
|
+
name: string;
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Method name on the controller class.
|
|
84
|
+
*/
|
|
85
|
+
method: string;
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Schedule options forwarded to Monque.schedule().
|
|
89
|
+
*/
|
|
90
|
+
opts: CronDecoratorOptions;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
94
|
+
// Worker Store
|
|
95
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Complete metadata structure stored on @WorkerController classes.
|
|
99
|
+
*
|
|
100
|
+
* Accessed via `Store.from(Class).get(MONQUE)`.
|
|
101
|
+
*
|
|
102
|
+
* @example
|
|
103
|
+
* ```typescript
|
|
104
|
+
* const store = Store.from(EmailWorkers).get<WorkerStore>(MONQUE);
|
|
105
|
+
* console.log(store.namespace); // "email"
|
|
106
|
+
* console.log(store.workers); // [{ name: "send", method: "sendEmail", opts: {} }]
|
|
107
|
+
* ```
|
|
108
|
+
*/
|
|
109
|
+
export interface WorkerStore {
|
|
110
|
+
/**
|
|
111
|
+
* Type identifier for the store.
|
|
112
|
+
* Always "controller" for WorkerController.
|
|
113
|
+
*/
|
|
114
|
+
type: 'controller';
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Optional namespace prefix for all jobs in this controller.
|
|
118
|
+
* When set, job names become "{namespace}.{name}".
|
|
119
|
+
*/
|
|
120
|
+
namespace?: string;
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Worker method registrations from @Worker decorators.
|
|
124
|
+
*/
|
|
125
|
+
workers: WorkerMetadata[];
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Cron job registrations from @Cron decorators.
|
|
129
|
+
*/
|
|
130
|
+
cronJobs: CronMetadata[];
|
|
131
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @WorkerController class decorator
|
|
3
|
+
*
|
|
4
|
+
* Marks a class as containing worker methods and registers it with the Ts.ED DI container.
|
|
5
|
+
* Workers in the class will have their job names prefixed with the namespace.
|
|
6
|
+
*
|
|
7
|
+
* @param namespace - Optional prefix for all job names in this controller.
|
|
8
|
+
* When set, job names become "{namespace}.{name}".
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* ```typescript
|
|
12
|
+
* @WorkerController("email")
|
|
13
|
+
* export class EmailWorkers {
|
|
14
|
+
* @Worker("send") // Registered as "email.send"
|
|
15
|
+
* async send(job: Job<EmailPayload>) { }
|
|
16
|
+
* }
|
|
17
|
+
* ```
|
|
18
|
+
*/
|
|
19
|
+
import { Store, useDecorators } from '@tsed/core';
|
|
20
|
+
import { Injectable } from '@tsed/di';
|
|
21
|
+
|
|
22
|
+
import { MONQUE, ProviderTypes } from '@/constants';
|
|
23
|
+
|
|
24
|
+
import type { WorkerStore } from './types.js';
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Class decorator that registers a class as a worker controller.
|
|
28
|
+
*
|
|
29
|
+
* @param namespace - Optional namespace prefix for job names
|
|
30
|
+
*/
|
|
31
|
+
export function WorkerController(namespace?: string): ClassDecorator {
|
|
32
|
+
return useDecorators(
|
|
33
|
+
// Register as injectable with custom provider type
|
|
34
|
+
Injectable({
|
|
35
|
+
type: ProviderTypes.WORKER_CONTROLLER,
|
|
36
|
+
}),
|
|
37
|
+
// Apply custom decorator to store metadata
|
|
38
|
+
(target: object) => {
|
|
39
|
+
const store = Store.from(target);
|
|
40
|
+
|
|
41
|
+
// Get existing store or create new one
|
|
42
|
+
const existing = store.get<Partial<WorkerStore>>(MONQUE) || {};
|
|
43
|
+
|
|
44
|
+
// Merge with new metadata, only include namespace if defined
|
|
45
|
+
const workerStore: WorkerStore = {
|
|
46
|
+
type: 'controller',
|
|
47
|
+
...(namespace !== undefined && { namespace }),
|
|
48
|
+
workers: existing.workers || [],
|
|
49
|
+
cronJobs: existing.cronJobs || [],
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
store.set(MONQUE, workerStore);
|
|
53
|
+
},
|
|
54
|
+
);
|
|
55
|
+
}
|