@seedcord/plugins 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 ADDED
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2025 Dhruv Jain (materwelonDhruv)
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/dist/index.cjs ADDED
@@ -0,0 +1,146 @@
1
+ 'use strict';
2
+
3
+ var mongoose2 = require('mongoose');
4
+ require('reflect-metadata');
5
+ var chalk = require('chalk');
6
+ var seedcord = require('seedcord');
7
+
8
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
9
+
10
+ var mongoose2__default = /*#__PURE__*/_interopDefault(mongoose2);
11
+ var chalk__default = /*#__PURE__*/_interopDefault(chalk);
12
+
13
+ var __defProp = Object.defineProperty;
14
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
15
+ var ModelMetadataKey = Symbol("db:model");
16
+ function DatabaseModel(collection) {
17
+ return (target, propertyKey) => {
18
+ const schema = target[propertyKey];
19
+ const name = String(collection);
20
+ const model = mongoose2__default.default.model(name, schema);
21
+ Reflect.defineMetadata(ModelMetadataKey, model, target);
22
+ };
23
+ }
24
+ __name(DatabaseModel, "DatabaseModel");
25
+
26
+ // src/mongo/decorators/DatabaseService.ts
27
+ var ServiceMetadataKey = Symbol("db:serviceKey");
28
+ function DatabaseService(key) {
29
+ return (ctor) => {
30
+ Reflect.defineMetadata(ServiceMetadataKey, key, ctor);
31
+ };
32
+ }
33
+ __name(DatabaseService, "DatabaseService");
34
+
35
+ // src/mongo/BaseService.ts
36
+ var BaseService = class {
37
+ static {
38
+ __name(this, "BaseService");
39
+ }
40
+ db;
41
+ core;
42
+ model;
43
+ constructor(db, core) {
44
+ this.db = db;
45
+ this.core = core;
46
+ const ctor = this.constructor;
47
+ const key = Reflect.getMetadata(ServiceMetadataKey, ctor);
48
+ if (!key) throw new Error(`Missing @DatabaseService on ${ctor.name}`);
49
+ const model = Reflect.getMetadata(ModelMetadataKey, ctor);
50
+ if (!model) throw new Error(`Missing @DatabaseModel on ${ctor.name}`);
51
+ this.model = model;
52
+ db._register(key, this);
53
+ }
54
+ };
55
+ var Mongo = class extends seedcord.Plugin {
56
+ static {
57
+ __name(this, "Mongo");
58
+ }
59
+ core;
60
+ options;
61
+ logger = new seedcord.Logger("MongoDB");
62
+ isInitialised = false;
63
+ uri;
64
+ /**
65
+ * Map of all loaded services.
66
+ * Keys come from `@DatabaseService('key')`
67
+ */
68
+ services = {};
69
+ constructor(core, options) {
70
+ super(core), this.core = core, this.options = options;
71
+ this.uri = options.uri;
72
+ this.core.shutdown.addTask(seedcord.ShutdownPhase.ExternalResources, "stop-database", async () => await this.stop());
73
+ }
74
+ async init() {
75
+ if (this.isInitialised) return;
76
+ this.isInitialised = true;
77
+ await this.connect();
78
+ await this.loadServices();
79
+ }
80
+ async stop() {
81
+ await this.disconnect();
82
+ }
83
+ async connect() {
84
+ await mongoose2__default.default.connect(this.uri, {
85
+ dbName: this.options.name,
86
+ ...seedcord.Globals.isProduction && {
87
+ tls: true,
88
+ ssl: true
89
+ }
90
+ }).then((i) => this.logger.info(`Connected to MongoDB: ${chalk__default.default.bold.magenta(i.connection.name)}`)).catch((err) => {
91
+ throw new Error(`Could not connect to MongoDB`, err);
92
+ });
93
+ }
94
+ async disconnect() {
95
+ await mongoose2__default.default.disconnect().then(() => this.logger.info(chalk__default.default.red.bold("Disconnected from MongoDB"))).catch((err) => this.logger.error(`Could not disconnect from MongoDB: ${err.message}`));
96
+ }
97
+ async loadServices() {
98
+ const servicesDir = this.options.dir;
99
+ this.logger.info(chalk__default.default.bold(servicesDir));
100
+ await seedcord.traverseDirectory(servicesDir, (_full, rel, mod) => {
101
+ for (const Service of Object.values(mod)) {
102
+ if (this.isServiceClass(Service)) {
103
+ const instance = new Service(this, this.core);
104
+ this.logger.info(`${chalk__default.default.italic("Registered")} ${chalk__default.default.bold.yellow(instance.constructor.name)} from ${chalk__default.default.gray(rel)}`);
105
+ }
106
+ }
107
+ });
108
+ this.logger.info(`${chalk__default.default.bold.green("Loaded")}: ${chalk__default.default.magenta(Object.keys(this.services).length)} services`);
109
+ }
110
+ isServiceClass(obj) {
111
+ return typeof obj === "function" && obj.prototype instanceof BaseService && Reflect.hasMetadata(ServiceMetadataKey, obj);
112
+ }
113
+ _register(key, instance) {
114
+ this.services[key] = instance;
115
+ }
116
+ };
117
+ function DBCatchable(errorMessage) {
118
+ return function(_target, _propertyKey, descriptor) {
119
+ const originalMethod = descriptor.value;
120
+ descriptor.value = async function(...args) {
121
+ if (!originalMethod) {
122
+ throw new Error("Method not found");
123
+ }
124
+ try {
125
+ return await originalMethod.apply(this, args);
126
+ } catch (error) {
127
+ if (!(error instanceof seedcord.CustomError)) {
128
+ seedcord.throwCustomError(error, errorMessage, seedcord.DatabaseError);
129
+ } else {
130
+ throw error;
131
+ }
132
+ }
133
+ };
134
+ };
135
+ }
136
+ __name(DBCatchable, "DBCatchable");
137
+
138
+ exports.BaseService = BaseService;
139
+ exports.DBCatchable = DBCatchable;
140
+ exports.DatabaseModel = DatabaseModel;
141
+ exports.DatabaseService = DatabaseService;
142
+ exports.ModelMetadataKey = ModelMetadataKey;
143
+ exports.Mongo = Mongo;
144
+ exports.ServiceMetadataKey = ServiceMetadataKey;
145
+ //# sourceMappingURL=index.cjs.map
146
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/mongo/decorators/DatabaseModel.ts","../src/mongo/decorators/DatabaseService.ts","../src/mongo/BaseService.ts","../src/mongo/Mongo.ts","../src/mongo/decorators/DBCatchable.ts"],"names":["ModelMetadataKey","Symbol","DatabaseModel","collection","target","propertyKey","schema","name","String","model","mongoose","Reflect","defineMetadata","ServiceMetadataKey","DatabaseService","key","ctor","BaseService","db","core","getMetadata","Error","_register","Mongo","Plugin","logger","Logger","isInitialised","uri","services","options","shutdown","addTask","ShutdownPhase","ExternalResources","stop","init","connect","loadServices","disconnect","dbName","Globals","isProduction","tls","ssl","then","i","info","chalk","bold","magenta","connection","catch","err","red","error","message","servicesDir","dir","traverseDirectory","_full","rel","mod","Service","Object","values","isServiceClass","instance","italic","yellow","gray","green","keys","length","obj","prototype","hasMetadata","DBCatchable","errorMessage","_target","_propertyKey","descriptor","originalMethod","value","args","apply","CustomError","throwCustomError","DatabaseError"],"mappings":";;;;;;;;;;;;;;AAIO,I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AC,YAAAA,EACAC,UAAAA,EAA4E;AAE5E,IAAA,MAAMC,iBAAiBD,UAAAA,CAAWE,KAAAA;AAElCF,IAAAA,UAAAA,CAAWE,KAAAA,GAAQ,kBAAmBC,IAAAA,EAAW;AAC/C,MAAA,IAAI,CAACF,cAAAA,EAAgB;AACnB,QAAA,MAAM,IAAI7D,MAAM,kBAAA,CAAA;AAClB,MAAA;AAEA,MAAA,IAAI;AACF,QAAA,OAAO,MAAM6D,cAAAA,CAAeG,KAAAA,CAAM,IAAA,EAAMD,IAAAA,CAAAA;AAC1C,MAAA,CAAA,CAAA,OAAS7B,KAAAA,EAAO;AACd,QAAA,IAAI,EAAEA,iBAAiB+B,oBAAAA,CAAAA,EAAc;AACnCC,UAAAA,yBAAAA,CAAiBhC,KAAAA,EAAOuB,cAAcU,sBAAAA,CAAAA;QACxC,CAAA,MAAO;AACL,UAAA,MAAMjC,KAAAA;AACR,QAAA;AACF,MAAA;AACF,IAAA,CAAA;AACF,EAAA,CAAA;AACF;AAxBgBsB,MAAAA,CAAAA,WAAAA,EAAAA,aAAAA,CAAAA","file":"index.cjs","sourcesContent":["import mongoose from 'mongoose';\n\nimport type { ServiceKeys } from '../types/Services';\n\nexport const ModelMetadataKey = Symbol('db:model');\n\n/**\n * Associates a Mongoose model with a database service\n *\n * Creates a Mongoose model from the decorated static schema property and stores it\n * for service registration. The model becomes available as `this.model` in the service.\n * Must be applied to a `public static schema` property in the service class.\n *\n * @param collection - Collection name for the Mongoose model\n * @decorator\n * @example\n * ```typescript\n * \\@DatabaseService('users')\n * export class Users extends BaseService<IUser> {\n * \\@DatabaseModel('users')\n * public static schema = new mongoose.Schema<IUser>({\n * username: { type: String, required: true, unique: true }\n * });\n * }\n * ```\n */\nexport function DatabaseModel<TService extends ServiceKeys>(collection: TService) {\n return <\n SchemaObj extends Record<KeyOfSchema, mongoose.Schema>,\n KeyOfSchema extends keyof SchemaObj & (string | symbol)\n >(\n target: SchemaObj,\n propertyKey: KeyOfSchema\n ): void => {\n const schema = target[propertyKey];\n const name = String(collection);\n const model = mongoose.model(name, schema);\n Reflect.defineMetadata(ModelMetadataKey, model, target);\n };\n}\n","import type { BaseService } from '../BaseService';\nimport type { ServiceKeys } from '../types/Services';\nimport type { ConstructorFunction } from '@seedcord/types';\n\nexport const ServiceMetadataKey = Symbol('db:serviceKey');\n\n/**\n * Registers a database service with a typed key\n *\n * Associates a service class with a key for dependency injection.\n * The service becomes available via `core.db.services[key]`.\n *\n * @param key - Service key for registration and type-safe access\n * @decorator\n * @example\n * ```typescript\n * \\@DatabaseService('users')\n * export class Users<Doc extends IUser = IUser> extends BaseService<Doc> {\n * // Some code\n * }\n * ```\n */\nexport function DatabaseService<TService extends ServiceKeys>(key: TService) {\n return <DatabaseCtor extends ConstructorFunction & { prototype: BaseService }>(ctor: DatabaseCtor): void => {\n Reflect.defineMetadata(ServiceMetadataKey, key, ctor);\n };\n}\n","import { ModelMetadataKey } from './decorators/DatabaseModel';\nimport { ServiceMetadataKey } from './decorators/DatabaseService';\n\nimport type { Mongo } from './Mongo';\nimport type { Services } from './types/Services';\nimport type { IDocument, TypedConstructor } from '@seedcord/types';\nimport type mongoose from 'mongoose';\nimport type { Core } from 'seedcord';\n\n/**\n * Base class for MongoDB service layers\n *\n * Provides typed access to MongoDB collections through Mongoose models.\n * Services are automatically registered with the Mongo plugin when instantiated.\n *\n * @typeParam Doc - The document type this service manages\n * @example\n * ```typescript\n * \\@DatabaseService('users')\n * export class Users extends BaseService<IUser> {\n * \\@DatabaseModel('users')\n * public static schema = new mongoose.Schema<IUser>({\n * username: { type: String, required: true, unique: true }\n * });\n *\n * // Custom methods here\n * public async findByUsername(username: string) {\n * return this.model.findOne({ username });\n * }\n * }\n * ```\n */\nexport abstract class BaseService<Doc extends IDocument = IDocument> {\n public readonly model: mongoose.Model<Doc>;\n\n public constructor(\n protected readonly db: Mongo,\n protected readonly core: Core\n ) {\n const ctor = this.constructor;\n\n const key = Reflect.getMetadata(ServiceMetadataKey, ctor) as string | undefined;\n if (!key) throw new Error(`Missing @DatabaseService on ${ctor.name}`);\n\n const model = Reflect.getMetadata(ModelMetadataKey, ctor) as mongoose.Model<Doc> | undefined;\n if (!model) throw new Error(`Missing @DatabaseModel on ${ctor.name}`);\n\n this.model = model;\n\n db._register(key as keyof Services, this as unknown as Services[keyof Services]);\n }\n}\n\n/** Constructor type for BaseService classes */\nexport type BaseServiceConstructor = TypedConstructor<typeof BaseService>;\n","import 'reflect-metadata';\n\nimport chalk from 'chalk';\nimport mongoose from 'mongoose';\nimport { Globals, Logger, Plugin, ShutdownPhase, traverseDirectory } from 'seedcord';\n\nimport { BaseService } from './BaseService';\nimport { ServiceMetadataKey } from './decorators/DatabaseService';\n\nimport type { BaseServiceConstructor } from './BaseService';\nimport type { Services } from './types/Services';\nimport type { Core } from 'seedcord';\n\n/**\n * Configuration options for MongoDB connection and service loading.\n */\ninterface MongoOptions {\n /** Directory path containing database service classes */\n dir: string;\n /** MongoDB connection URI */\n uri: string;\n /** Database name to use */\n name: string;\n}\n\n/**\n * MongoDB integration plugin for Seedcord.\n *\n * Manages MongoDB connections, service loading, and provides type-safe\n * access to database services through service registration decorators.\n */\nexport class Mongo extends Plugin {\n public readonly logger = new Logger('MongoDB');\n private isInitialised = false;\n private readonly uri: string;\n\n /**\n * Map of all loaded services.\n * Keys come from `@DatabaseService('key')`\n */\n public readonly services: Services = {} as Services;\n\n constructor(\n public readonly core: Core,\n private readonly options: MongoOptions\n ) {\n super(core);\n this.uri = options.uri;\n\n this.core.shutdown.addTask(ShutdownPhase.ExternalResources, 'stop-database', async () => await this.stop());\n }\n\n public async init(): Promise<void> {\n if (this.isInitialised) return;\n this.isInitialised = true;\n\n await this.connect();\n await this.loadServices();\n }\n\n public async stop(): Promise<void> {\n await this.disconnect();\n }\n\n private async connect(): Promise<void> {\n await mongoose\n .connect(this.uri, {\n dbName: this.options.name,\n ...(Globals.isProduction && { tls: true, ssl: true })\n })\n .then((i) => this.logger.info(`Connected to MongoDB: ${chalk.bold.magenta(i.connection.name)}`))\n .catch((err) => {\n throw new Error(`Could not connect to MongoDB`, err);\n });\n }\n\n private async disconnect(): Promise<void> {\n await mongoose\n .disconnect()\n .then(() => this.logger.info(chalk.red.bold('Disconnected from MongoDB')))\n .catch((err) => this.logger.error(`Could not disconnect from MongoDB: ${(err as Error).message}`));\n }\n\n private async loadServices(): Promise<void> {\n const servicesDir = this.options.dir;\n this.logger.info(chalk.bold(servicesDir));\n\n await traverseDirectory(servicesDir, (_full, rel, mod) => {\n for (const Service of Object.values(mod)) {\n if (this.isServiceClass(Service)) {\n const instance = new Service(this, this.core);\n this.logger.info(\n `${chalk.italic('Registered')} ${chalk.bold.yellow(instance.constructor.name)} from ${chalk.gray(rel)}`\n );\n }\n }\n });\n\n this.logger.info(`${chalk.bold.green('Loaded')}: ${chalk.magenta(Object.keys(this.services).length)} services`);\n }\n\n private isServiceClass(obj: unknown): obj is BaseServiceConstructor {\n return (\n typeof obj === 'function' && obj.prototype instanceof BaseService && Reflect.hasMetadata(ServiceMetadataKey, obj)\n );\n }\n\n _register<SKey extends keyof Services>(key: SKey, instance: Services[SKey]): void {\n this.services[key] = instance;\n }\n}\n","import { CustomError, throwCustomError, DatabaseError } from 'seedcord';\n\n/**\n * Catches and wraps database operation errors.\n *\n * Automatically wraps non-CustomError exceptions in DatabaseError instances\n * with UUID tracking. Should be applied to database service methods.\n *\n * @param errorMessage - Message to include when wrapping errors\n * @decorator\n * @example\n * ```typescript\n * class UserService extends BaseService {\n * \\@DBCatchable('Failed to find user')\n * async findById(id: string) {\n * return this.model.findById(id);\n * }\n * }\n * ```\n */\nexport function DBCatchable<TypeReturn>(errorMessage: string) {\n return function (\n _target: unknown,\n _propertyKey: string,\n descriptor: TypedPropertyDescriptor<(...args: any[]) => Promise<TypeReturn>>\n ): void {\n const originalMethod = descriptor.value;\n\n descriptor.value = async function (...args: any[]): Promise<TypeReturn> {\n if (!originalMethod) {\n throw new Error('Method not found');\n }\n\n try {\n return await originalMethod.apply(this, args);\n } catch (error) {\n if (!(error instanceof CustomError)) {\n throwCustomError(error, errorMessage, DatabaseError);\n } else {\n throw error;\n }\n }\n };\n };\n}\n"]}
@@ -0,0 +1,162 @@
1
+ import { Plugin, Core, Logger } from 'seedcord';
2
+ import { IDocument, TypedConstructor, ConstructorFunction } from '@seedcord/types';
3
+ import mongoose from 'mongoose';
4
+
5
+ /**
6
+ * Registry of available database services.
7
+ *
8
+ * This interface can be augmented via declaration merging to add
9
+ * type-safe service definitions when using the \@DatabaseService and \@DatabaseModel decorator.
10
+ *
11
+ * @example
12
+ * ```typescript
13
+ * declare module 'seedcord' {
14
+ * interface Services {
15
+ * 'user': UserService;
16
+ * 'guild': GuildService;
17
+ * }
18
+ * }
19
+ * ```
20
+ */
21
+ interface Services {
22
+ }
23
+ /**
24
+ * Helper type to extract service keys from the Services interface.
25
+ */
26
+ type ServiceKeys = keyof Services;
27
+
28
+ /**
29
+ * Configuration options for MongoDB connection and service loading.
30
+ */
31
+ interface MongoOptions {
32
+ /** Directory path containing database service classes */
33
+ dir: string;
34
+ /** MongoDB connection URI */
35
+ uri: string;
36
+ /** Database name to use */
37
+ name: string;
38
+ }
39
+ /**
40
+ * MongoDB integration plugin for Seedcord.
41
+ *
42
+ * Manages MongoDB connections, service loading, and provides type-safe
43
+ * access to database services through service registration decorators.
44
+ */
45
+ declare class Mongo extends Plugin {
46
+ readonly core: Core;
47
+ private readonly options;
48
+ readonly logger: Logger;
49
+ private isInitialised;
50
+ private readonly uri;
51
+ /**
52
+ * Map of all loaded services.
53
+ * Keys come from `@DatabaseService('key')`
54
+ */
55
+ readonly services: Services;
56
+ constructor(core: Core, options: MongoOptions);
57
+ init(): Promise<void>;
58
+ stop(): Promise<void>;
59
+ private connect;
60
+ private disconnect;
61
+ private loadServices;
62
+ private isServiceClass;
63
+ _register<SKey extends keyof Services>(key: SKey, instance: Services[SKey]): void;
64
+ }
65
+
66
+ /**
67
+ * Base class for MongoDB service layers
68
+ *
69
+ * Provides typed access to MongoDB collections through Mongoose models.
70
+ * Services are automatically registered with the Mongo plugin when instantiated.
71
+ *
72
+ * @typeParam Doc - The document type this service manages
73
+ * @example
74
+ * ```typescript
75
+ * \@DatabaseService('users')
76
+ * export class Users extends BaseService<IUser> {
77
+ * \@DatabaseModel('users')
78
+ * public static schema = new mongoose.Schema<IUser>({
79
+ * username: { type: String, required: true, unique: true }
80
+ * });
81
+ *
82
+ * // Custom methods here
83
+ * public async findByUsername(username: string) {
84
+ * return this.model.findOne({ username });
85
+ * }
86
+ * }
87
+ * ```
88
+ */
89
+ declare abstract class BaseService<Doc extends IDocument = IDocument> {
90
+ protected readonly db: Mongo;
91
+ protected readonly core: Core;
92
+ readonly model: mongoose.Model<Doc>;
93
+ constructor(db: Mongo, core: Core);
94
+ }
95
+ /** Constructor type for BaseService classes */
96
+ type BaseServiceConstructor = TypedConstructor<typeof BaseService>;
97
+
98
+ /**
99
+ * Catches and wraps database operation errors.
100
+ *
101
+ * Automatically wraps non-CustomError exceptions in DatabaseError instances
102
+ * with UUID tracking. Should be applied to database service methods.
103
+ *
104
+ * @param errorMessage - Message to include when wrapping errors
105
+ * @decorator
106
+ * @example
107
+ * ```typescript
108
+ * class UserService extends BaseService {
109
+ * \@DBCatchable('Failed to find user')
110
+ * async findById(id: string) {
111
+ * return this.model.findById(id);
112
+ * }
113
+ * }
114
+ * ```
115
+ */
116
+ declare function DBCatchable<TypeReturn>(errorMessage: string): (_target: unknown, _propertyKey: string, descriptor: TypedPropertyDescriptor<(...args: any[]) => Promise<TypeReturn>>) => void;
117
+
118
+ declare const ModelMetadataKey: unique symbol;
119
+ /**
120
+ * Associates a Mongoose model with a database service
121
+ *
122
+ * Creates a Mongoose model from the decorated static schema property and stores it
123
+ * for service registration. The model becomes available as `this.model` in the service.
124
+ * Must be applied to a `public static schema` property in the service class.
125
+ *
126
+ * @param collection - Collection name for the Mongoose model
127
+ * @decorator
128
+ * @example
129
+ * ```typescript
130
+ * \@DatabaseService('users')
131
+ * export class Users extends BaseService<IUser> {
132
+ * \@DatabaseModel('users')
133
+ * public static schema = new mongoose.Schema<IUser>({
134
+ * username: { type: String, required: true, unique: true }
135
+ * });
136
+ * }
137
+ * ```
138
+ */
139
+ declare function DatabaseModel<TService extends ServiceKeys>(collection: TService): <SchemaObj extends Record<KeyOfSchema, mongoose.Schema>, KeyOfSchema extends keyof SchemaObj & (string | symbol)>(target: SchemaObj, propertyKey: KeyOfSchema) => void;
140
+
141
+ declare const ServiceMetadataKey: unique symbol;
142
+ /**
143
+ * Registers a database service with a typed key
144
+ *
145
+ * Associates a service class with a key for dependency injection.
146
+ * The service becomes available via `core.db.services[key]`.
147
+ *
148
+ * @param key - Service key for registration and type-safe access
149
+ * @decorator
150
+ * @example
151
+ * ```typescript
152
+ * \@DatabaseService('users')
153
+ * export class Users<Doc extends IUser = IUser> extends BaseService<Doc> {
154
+ * // Some code
155
+ * }
156
+ * ```
157
+ */
158
+ declare function DatabaseService<TService extends ServiceKeys>(key: TService): <DatabaseCtor extends ConstructorFunction & {
159
+ prototype: BaseService;
160
+ }>(ctor: DatabaseCtor) => void;
161
+
162
+ export { BaseService, type BaseServiceConstructor, DBCatchable, DatabaseModel, DatabaseService, ModelMetadataKey, Mongo, type ServiceKeys, ServiceMetadataKey, type Services };
@@ -0,0 +1,162 @@
1
+ import { Plugin, Core, Logger } from 'seedcord';
2
+ import { IDocument, TypedConstructor, ConstructorFunction } from '@seedcord/types';
3
+ import mongoose from 'mongoose';
4
+
5
+ /**
6
+ * Registry of available database services.
7
+ *
8
+ * This interface can be augmented via declaration merging to add
9
+ * type-safe service definitions when using the \@DatabaseService and \@DatabaseModel decorator.
10
+ *
11
+ * @example
12
+ * ```typescript
13
+ * declare module 'seedcord' {
14
+ * interface Services {
15
+ * 'user': UserService;
16
+ * 'guild': GuildService;
17
+ * }
18
+ * }
19
+ * ```
20
+ */
21
+ interface Services {
22
+ }
23
+ /**
24
+ * Helper type to extract service keys from the Services interface.
25
+ */
26
+ type ServiceKeys = keyof Services;
27
+
28
+ /**
29
+ * Configuration options for MongoDB connection and service loading.
30
+ */
31
+ interface MongoOptions {
32
+ /** Directory path containing database service classes */
33
+ dir: string;
34
+ /** MongoDB connection URI */
35
+ uri: string;
36
+ /** Database name to use */
37
+ name: string;
38
+ }
39
+ /**
40
+ * MongoDB integration plugin for Seedcord.
41
+ *
42
+ * Manages MongoDB connections, service loading, and provides type-safe
43
+ * access to database services through service registration decorators.
44
+ */
45
+ declare class Mongo extends Plugin {
46
+ readonly core: Core;
47
+ private readonly options;
48
+ readonly logger: Logger;
49
+ private isInitialised;
50
+ private readonly uri;
51
+ /**
52
+ * Map of all loaded services.
53
+ * Keys come from `@DatabaseService('key')`
54
+ */
55
+ readonly services: Services;
56
+ constructor(core: Core, options: MongoOptions);
57
+ init(): Promise<void>;
58
+ stop(): Promise<void>;
59
+ private connect;
60
+ private disconnect;
61
+ private loadServices;
62
+ private isServiceClass;
63
+ _register<SKey extends keyof Services>(key: SKey, instance: Services[SKey]): void;
64
+ }
65
+
66
+ /**
67
+ * Base class for MongoDB service layers
68
+ *
69
+ * Provides typed access to MongoDB collections through Mongoose models.
70
+ * Services are automatically registered with the Mongo plugin when instantiated.
71
+ *
72
+ * @typeParam Doc - The document type this service manages
73
+ * @example
74
+ * ```typescript
75
+ * \@DatabaseService('users')
76
+ * export class Users extends BaseService<IUser> {
77
+ * \@DatabaseModel('users')
78
+ * public static schema = new mongoose.Schema<IUser>({
79
+ * username: { type: String, required: true, unique: true }
80
+ * });
81
+ *
82
+ * // Custom methods here
83
+ * public async findByUsername(username: string) {
84
+ * return this.model.findOne({ username });
85
+ * }
86
+ * }
87
+ * ```
88
+ */
89
+ declare abstract class BaseService<Doc extends IDocument = IDocument> {
90
+ protected readonly db: Mongo;
91
+ protected readonly core: Core;
92
+ readonly model: mongoose.Model<Doc>;
93
+ constructor(db: Mongo, core: Core);
94
+ }
95
+ /** Constructor type for BaseService classes */
96
+ type BaseServiceConstructor = TypedConstructor<typeof BaseService>;
97
+
98
+ /**
99
+ * Catches and wraps database operation errors.
100
+ *
101
+ * Automatically wraps non-CustomError exceptions in DatabaseError instances
102
+ * with UUID tracking. Should be applied to database service methods.
103
+ *
104
+ * @param errorMessage - Message to include when wrapping errors
105
+ * @decorator
106
+ * @example
107
+ * ```typescript
108
+ * class UserService extends BaseService {
109
+ * \@DBCatchable('Failed to find user')
110
+ * async findById(id: string) {
111
+ * return this.model.findById(id);
112
+ * }
113
+ * }
114
+ * ```
115
+ */
116
+ declare function DBCatchable<TypeReturn>(errorMessage: string): (_target: unknown, _propertyKey: string, descriptor: TypedPropertyDescriptor<(...args: any[]) => Promise<TypeReturn>>) => void;
117
+
118
+ declare const ModelMetadataKey: unique symbol;
119
+ /**
120
+ * Associates a Mongoose model with a database service
121
+ *
122
+ * Creates a Mongoose model from the decorated static schema property and stores it
123
+ * for service registration. The model becomes available as `this.model` in the service.
124
+ * Must be applied to a `public static schema` property in the service class.
125
+ *
126
+ * @param collection - Collection name for the Mongoose model
127
+ * @decorator
128
+ * @example
129
+ * ```typescript
130
+ * \@DatabaseService('users')
131
+ * export class Users extends BaseService<IUser> {
132
+ * \@DatabaseModel('users')
133
+ * public static schema = new mongoose.Schema<IUser>({
134
+ * username: { type: String, required: true, unique: true }
135
+ * });
136
+ * }
137
+ * ```
138
+ */
139
+ declare function DatabaseModel<TService extends ServiceKeys>(collection: TService): <SchemaObj extends Record<KeyOfSchema, mongoose.Schema>, KeyOfSchema extends keyof SchemaObj & (string | symbol)>(target: SchemaObj, propertyKey: KeyOfSchema) => void;
140
+
141
+ declare const ServiceMetadataKey: unique symbol;
142
+ /**
143
+ * Registers a database service with a typed key
144
+ *
145
+ * Associates a service class with a key for dependency injection.
146
+ * The service becomes available via `core.db.services[key]`.
147
+ *
148
+ * @param key - Service key for registration and type-safe access
149
+ * @decorator
150
+ * @example
151
+ * ```typescript
152
+ * \@DatabaseService('users')
153
+ * export class Users<Doc extends IUser = IUser> extends BaseService<Doc> {
154
+ * // Some code
155
+ * }
156
+ * ```
157
+ */
158
+ declare function DatabaseService<TService extends ServiceKeys>(key: TService): <DatabaseCtor extends ConstructorFunction & {
159
+ prototype: BaseService;
160
+ }>(ctor: DatabaseCtor) => void;
161
+
162
+ export { BaseService, type BaseServiceConstructor, DBCatchable, DatabaseModel, DatabaseService, ModelMetadataKey, Mongo, type ServiceKeys, ServiceMetadataKey, type Services };
@@ -0,0 +1,162 @@
1
+ import { Plugin, Core, Logger } from 'seedcord';
2
+ import { IDocument, TypedConstructor, ConstructorFunction } from '@seedcord/types';
3
+ import mongoose from 'mongoose';
4
+
5
+ /**
6
+ * Registry of available database services.
7
+ *
8
+ * This interface can be augmented via declaration merging to add
9
+ * type-safe service definitions when using the \@DatabaseService and \@DatabaseModel decorator.
10
+ *
11
+ * @example
12
+ * ```typescript
13
+ * declare module 'seedcord' {
14
+ * interface Services {
15
+ * 'user': UserService;
16
+ * 'guild': GuildService;
17
+ * }
18
+ * }
19
+ * ```
20
+ */
21
+ interface Services {
22
+ }
23
+ /**
24
+ * Helper type to extract service keys from the Services interface.
25
+ */
26
+ type ServiceKeys = keyof Services;
27
+
28
+ /**
29
+ * Configuration options for MongoDB connection and service loading.
30
+ */
31
+ interface MongoOptions {
32
+ /** Directory path containing database service classes */
33
+ dir: string;
34
+ /** MongoDB connection URI */
35
+ uri: string;
36
+ /** Database name to use */
37
+ name: string;
38
+ }
39
+ /**
40
+ * MongoDB integration plugin for Seedcord.
41
+ *
42
+ * Manages MongoDB connections, service loading, and provides type-safe
43
+ * access to database services through service registration decorators.
44
+ */
45
+ declare class Mongo extends Plugin {
46
+ readonly core: Core;
47
+ private readonly options;
48
+ readonly logger: Logger;
49
+ private isInitialised;
50
+ private readonly uri;
51
+ /**
52
+ * Map of all loaded services.
53
+ * Keys come from `@DatabaseService('key')`
54
+ */
55
+ readonly services: Services;
56
+ constructor(core: Core, options: MongoOptions);
57
+ init(): Promise<void>;
58
+ stop(): Promise<void>;
59
+ private connect;
60
+ private disconnect;
61
+ private loadServices;
62
+ private isServiceClass;
63
+ _register<SKey extends keyof Services>(key: SKey, instance: Services[SKey]): void;
64
+ }
65
+
66
+ /**
67
+ * Base class for MongoDB service layers
68
+ *
69
+ * Provides typed access to MongoDB collections through Mongoose models.
70
+ * Services are automatically registered with the Mongo plugin when instantiated.
71
+ *
72
+ * @typeParam Doc - The document type this service manages
73
+ * @example
74
+ * ```typescript
75
+ * \@DatabaseService('users')
76
+ * export class Users extends BaseService<IUser> {
77
+ * \@DatabaseModel('users')
78
+ * public static schema = new mongoose.Schema<IUser>({
79
+ * username: { type: String, required: true, unique: true }
80
+ * });
81
+ *
82
+ * // Custom methods here
83
+ * public async findByUsername(username: string) {
84
+ * return this.model.findOne({ username });
85
+ * }
86
+ * }
87
+ * ```
88
+ */
89
+ declare abstract class BaseService<Doc extends IDocument = IDocument> {
90
+ protected readonly db: Mongo;
91
+ protected readonly core: Core;
92
+ readonly model: mongoose.Model<Doc>;
93
+ constructor(db: Mongo, core: Core);
94
+ }
95
+ /** Constructor type for BaseService classes */
96
+ type BaseServiceConstructor = TypedConstructor<typeof BaseService>;
97
+
98
+ /**
99
+ * Catches and wraps database operation errors.
100
+ *
101
+ * Automatically wraps non-CustomError exceptions in DatabaseError instances
102
+ * with UUID tracking. Should be applied to database service methods.
103
+ *
104
+ * @param errorMessage - Message to include when wrapping errors
105
+ * @decorator
106
+ * @example
107
+ * ```typescript
108
+ * class UserService extends BaseService {
109
+ * \@DBCatchable('Failed to find user')
110
+ * async findById(id: string) {
111
+ * return this.model.findById(id);
112
+ * }
113
+ * }
114
+ * ```
115
+ */
116
+ declare function DBCatchable<TypeReturn>(errorMessage: string): (_target: unknown, _propertyKey: string, descriptor: TypedPropertyDescriptor<(...args: any[]) => Promise<TypeReturn>>) => void;
117
+
118
+ declare const ModelMetadataKey: unique symbol;
119
+ /**
120
+ * Associates a Mongoose model with a database service
121
+ *
122
+ * Creates a Mongoose model from the decorated static schema property and stores it
123
+ * for service registration. The model becomes available as `this.model` in the service.
124
+ * Must be applied to a `public static schema` property in the service class.
125
+ *
126
+ * @param collection - Collection name for the Mongoose model
127
+ * @decorator
128
+ * @example
129
+ * ```typescript
130
+ * \@DatabaseService('users')
131
+ * export class Users extends BaseService<IUser> {
132
+ * \@DatabaseModel('users')
133
+ * public static schema = new mongoose.Schema<IUser>({
134
+ * username: { type: String, required: true, unique: true }
135
+ * });
136
+ * }
137
+ * ```
138
+ */
139
+ declare function DatabaseModel<TService extends ServiceKeys>(collection: TService): <SchemaObj extends Record<KeyOfSchema, mongoose.Schema>, KeyOfSchema extends keyof SchemaObj & (string | symbol)>(target: SchemaObj, propertyKey: KeyOfSchema) => void;
140
+
141
+ declare const ServiceMetadataKey: unique symbol;
142
+ /**
143
+ * Registers a database service with a typed key
144
+ *
145
+ * Associates a service class with a key for dependency injection.
146
+ * The service becomes available via `core.db.services[key]`.
147
+ *
148
+ * @param key - Service key for registration and type-safe access
149
+ * @decorator
150
+ * @example
151
+ * ```typescript
152
+ * \@DatabaseService('users')
153
+ * export class Users<Doc extends IUser = IUser> extends BaseService<Doc> {
154
+ * // Some code
155
+ * }
156
+ * ```
157
+ */
158
+ declare function DatabaseService<TService extends ServiceKeys>(key: TService): <DatabaseCtor extends ConstructorFunction & {
159
+ prototype: BaseService;
160
+ }>(ctor: DatabaseCtor) => void;
161
+
162
+ export { BaseService, type BaseServiceConstructor, DBCatchable, DatabaseModel, DatabaseService, ModelMetadataKey, Mongo, type ServiceKeys, ServiceMetadataKey, type Services };
package/dist/index.mjs ADDED
@@ -0,0 +1,133 @@
1
+ import mongoose2 from 'mongoose';
2
+ import 'reflect-metadata';
3
+ import chalk from 'chalk';
4
+ import { Plugin, Logger, ShutdownPhase, Globals, traverseDirectory, CustomError, throwCustomError, DatabaseError } from 'seedcord';
5
+
6
+ var __defProp = Object.defineProperty;
7
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
8
+ var ModelMetadataKey = Symbol("db:model");
9
+ function DatabaseModel(collection) {
10
+ return (target, propertyKey) => {
11
+ const schema = target[propertyKey];
12
+ const name = String(collection);
13
+ const model = mongoose2.model(name, schema);
14
+ Reflect.defineMetadata(ModelMetadataKey, model, target);
15
+ };
16
+ }
17
+ __name(DatabaseModel, "DatabaseModel");
18
+
19
+ // src/mongo/decorators/DatabaseService.ts
20
+ var ServiceMetadataKey = Symbol("db:serviceKey");
21
+ function DatabaseService(key) {
22
+ return (ctor) => {
23
+ Reflect.defineMetadata(ServiceMetadataKey, key, ctor);
24
+ };
25
+ }
26
+ __name(DatabaseService, "DatabaseService");
27
+
28
+ // src/mongo/BaseService.ts
29
+ var BaseService = class {
30
+ static {
31
+ __name(this, "BaseService");
32
+ }
33
+ db;
34
+ core;
35
+ model;
36
+ constructor(db, core) {
37
+ this.db = db;
38
+ this.core = core;
39
+ const ctor = this.constructor;
40
+ const key = Reflect.getMetadata(ServiceMetadataKey, ctor);
41
+ if (!key) throw new Error(`Missing @DatabaseService on ${ctor.name}`);
42
+ const model = Reflect.getMetadata(ModelMetadataKey, ctor);
43
+ if (!model) throw new Error(`Missing @DatabaseModel on ${ctor.name}`);
44
+ this.model = model;
45
+ db._register(key, this);
46
+ }
47
+ };
48
+ var Mongo = class extends Plugin {
49
+ static {
50
+ __name(this, "Mongo");
51
+ }
52
+ core;
53
+ options;
54
+ logger = new Logger("MongoDB");
55
+ isInitialised = false;
56
+ uri;
57
+ /**
58
+ * Map of all loaded services.
59
+ * Keys come from `@DatabaseService('key')`
60
+ */
61
+ services = {};
62
+ constructor(core, options) {
63
+ super(core), this.core = core, this.options = options;
64
+ this.uri = options.uri;
65
+ this.core.shutdown.addTask(ShutdownPhase.ExternalResources, "stop-database", async () => await this.stop());
66
+ }
67
+ async init() {
68
+ if (this.isInitialised) return;
69
+ this.isInitialised = true;
70
+ await this.connect();
71
+ await this.loadServices();
72
+ }
73
+ async stop() {
74
+ await this.disconnect();
75
+ }
76
+ async connect() {
77
+ await mongoose2.connect(this.uri, {
78
+ dbName: this.options.name,
79
+ ...Globals.isProduction && {
80
+ tls: true,
81
+ ssl: true
82
+ }
83
+ }).then((i) => this.logger.info(`Connected to MongoDB: ${chalk.bold.magenta(i.connection.name)}`)).catch((err) => {
84
+ throw new Error(`Could not connect to MongoDB`, err);
85
+ });
86
+ }
87
+ async disconnect() {
88
+ await mongoose2.disconnect().then(() => this.logger.info(chalk.red.bold("Disconnected from MongoDB"))).catch((err) => this.logger.error(`Could not disconnect from MongoDB: ${err.message}`));
89
+ }
90
+ async loadServices() {
91
+ const servicesDir = this.options.dir;
92
+ this.logger.info(chalk.bold(servicesDir));
93
+ await traverseDirectory(servicesDir, (_full, rel, mod) => {
94
+ for (const Service of Object.values(mod)) {
95
+ if (this.isServiceClass(Service)) {
96
+ const instance = new Service(this, this.core);
97
+ this.logger.info(`${chalk.italic("Registered")} ${chalk.bold.yellow(instance.constructor.name)} from ${chalk.gray(rel)}`);
98
+ }
99
+ }
100
+ });
101
+ this.logger.info(`${chalk.bold.green("Loaded")}: ${chalk.magenta(Object.keys(this.services).length)} services`);
102
+ }
103
+ isServiceClass(obj) {
104
+ return typeof obj === "function" && obj.prototype instanceof BaseService && Reflect.hasMetadata(ServiceMetadataKey, obj);
105
+ }
106
+ _register(key, instance) {
107
+ this.services[key] = instance;
108
+ }
109
+ };
110
+ function DBCatchable(errorMessage) {
111
+ return function(_target, _propertyKey, descriptor) {
112
+ const originalMethod = descriptor.value;
113
+ descriptor.value = async function(...args) {
114
+ if (!originalMethod) {
115
+ throw new Error("Method not found");
116
+ }
117
+ try {
118
+ return await originalMethod.apply(this, args);
119
+ } catch (error) {
120
+ if (!(error instanceof CustomError)) {
121
+ throwCustomError(error, errorMessage, DatabaseError);
122
+ } else {
123
+ throw error;
124
+ }
125
+ }
126
+ };
127
+ };
128
+ }
129
+ __name(DBCatchable, "DBCatchable");
130
+
131
+ export { BaseService, DBCatchable, DatabaseModel, DatabaseService, ModelMetadataKey, Mongo, ServiceMetadataKey };
132
+ //# sourceMappingURL=index.mjs.map
133
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/mongo/decorators/DatabaseModel.ts","../src/mongo/decorators/DatabaseService.ts","../src/mongo/BaseService.ts","../src/mongo/Mongo.ts","../src/mongo/decorators/DBCatchable.ts"],"names":["ModelMetadataKey","Symbol","DatabaseModel","collection","target","propertyKey","schema","name","String","model","mongoose","Reflect","defineMetadata","ServiceMetadataKey","DatabaseService","key","ctor","BaseService","db","core","getMetadata","Error","_register","Mongo","Plugin","logger","Logger","isInitialised","uri","services","options","shutdown","addTask","ShutdownPhase","ExternalResources","stop","init","connect","loadServices","disconnect","dbName","Globals","isProduction","tls","ssl","then","i","info","chalk","bold","magenta","connection","catch","err","red","error","message","servicesDir","dir","traverseDirectory","_full","rel","mod","Service","Object","values","isServiceClass","instance","italic","yellow","gray","green","keys","length","obj","prototype","hasMetadata","DBCatchable","errorMessage","_target","_propertyKey","descriptor","originalMethod","value","args","apply","CustomError","throwCustomError","DatabaseError"],"mappings":";;;;;;;AAIO,IAAMA,gBAAAA,GAAmBC,OAAO,UAAA;AAsBhC,SAASC,cAA4CC,UAAAA,EAAoB;AAC9E,EAAA,OAAO,CAILC,QACAC,WAAAA,KAAAA;AAEA,IAAA,MAAMC,MAAAA,GAASF,OAAOC,WAAAA,CAAAA;AACtB,IAAA,MAAME,IAAAA,GAAOC,OAAOL,UAAAA,CAAAA;AACpB,IAAA,MAAMM,KAAAA,GAAQC,SAAAA,CAASD,KAAAA,CAAMF,IAAAA,EAAMD,MAAAA,CAAAA;AACnCK,IAAAA,OAAAA,CAAQC,cAAAA,CAAeZ,gBAAAA,EAAkBS,KAAAA,EAAOL,MAAAA,CAAAA;AAClD,EAAA,CAAA;AACF;AAbgBF,MAAAA,CAAAA,aAAAA,EAAAA,eAAAA,CAAAA;;;ACtBT,IAAMW,kBAAAA,GAAqBZ,OAAO,eAAA;AAkBlC,SAASa,gBAA8CC,GAAAA,EAAa;AACzE,EAAA,OAAO,CAAw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EAAA,CAAA;AACF;AAxBgBsB,MAAAA,CAAAA,WAAAA,EAAAA,aAAAA,CAAAA","file":"index.mjs","sourcesContent":["import mongoose from 'mongoose';\n\nimport type { ServiceKeys } from '../types/Services';\n\nexport const ModelMetadataKey = Symbol('db:model');\n\n/**\n * Associates a Mongoose model with a database service\n *\n * Creates a Mongoose model from the decorated static schema property and stores it\n * for service registration. The model becomes available as `this.model` in the service.\n * Must be applied to a `public static schema` property in the service class.\n *\n * @param collection - Collection name for the Mongoose model\n * @decorator\n * @example\n * ```typescript\n * \\@DatabaseService('users')\n * export class Users extends BaseService<IUser> {\n * \\@DatabaseModel('users')\n * public static schema = new mongoose.Schema<IUser>({\n * username: { type: String, required: true, unique: true }\n * });\n * }\n * ```\n */\nexport function DatabaseModel<TService extends ServiceKeys>(collection: TService) {\n return <\n SchemaObj extends Record<KeyOfSchema, mongoose.Schema>,\n KeyOfSchema extends keyof SchemaObj & (string | symbol)\n >(\n target: SchemaObj,\n propertyKey: KeyOfSchema\n ): void => {\n const schema = target[propertyKey];\n const name = String(collection);\n const model = mongoose.model(name, schema);\n Reflect.defineMetadata(ModelMetadataKey, model, target);\n };\n}\n","import type { BaseService } from '../BaseService';\nimport type { ServiceKeys } from '../types/Services';\nimport type { ConstructorFunction } from '@seedcord/types';\n\nexport const ServiceMetadataKey = Symbol('db:serviceKey');\n\n/**\n * Registers a database service with a typed key\n *\n * Associates a service class with a key for dependency injection.\n * The service becomes available via `core.db.services[key]`.\n *\n * @param key - Service key for registration and type-safe access\n * @decorator\n * @example\n * ```typescript\n * \\@DatabaseService('users')\n * export class Users<Doc extends IUser = IUser> extends BaseService<Doc> {\n * // Some code\n * }\n * ```\n */\nexport function DatabaseService<TService extends ServiceKeys>(key: TService) {\n return <DatabaseCtor extends ConstructorFunction & { prototype: BaseService }>(ctor: DatabaseCtor): void => {\n Reflect.defineMetadata(ServiceMetadataKey, key, ctor);\n };\n}\n","import { ModelMetadataKey } from './decorators/DatabaseModel';\nimport { ServiceMetadataKey } from './decorators/DatabaseService';\n\nimport type { Mongo } from './Mongo';\nimport type { Services } from './types/Services';\nimport type { IDocument, TypedConstructor } from '@seedcord/types';\nimport type mongoose from 'mongoose';\nimport type { Core } from 'seedcord';\n\n/**\n * Base class for MongoDB service layers\n *\n * Provides typed access to MongoDB collections through Mongoose models.\n * Services are automatically registered with the Mongo plugin when instantiated.\n *\n * @typeParam Doc - The document type this service manages\n * @example\n * ```typescript\n * \\@DatabaseService('users')\n * export class Users extends BaseService<IUser> {\n * \\@DatabaseModel('users')\n * public static schema = new mongoose.Schema<IUser>({\n * username: { type: String, required: true, unique: true }\n * });\n *\n * // Custom methods here\n * public async findByUsername(username: string) {\n * return this.model.findOne({ username });\n * }\n * }\n * ```\n */\nexport abstract class BaseService<Doc extends IDocument = IDocument> {\n public readonly model: mongoose.Model<Doc>;\n\n public constructor(\n protected readonly db: Mongo,\n protected readonly core: Core\n ) {\n const ctor = this.constructor;\n\n const key = Reflect.getMetadata(ServiceMetadataKey, ctor) as string | undefined;\n if (!key) throw new Error(`Missing @DatabaseService on ${ctor.name}`);\n\n const model = Reflect.getMetadata(ModelMetadataKey, ctor) as mongoose.Model<Doc> | undefined;\n if (!model) throw new Error(`Missing @DatabaseModel on ${ctor.name}`);\n\n this.model = model;\n\n db._register(key as keyof Services, this as unknown as Services[keyof Services]);\n }\n}\n\n/** Constructor type for BaseService classes */\nexport type BaseServiceConstructor = TypedConstructor<typeof BaseService>;\n","import 'reflect-metadata';\n\nimport chalk from 'chalk';\nimport mongoose from 'mongoose';\nimport { Globals, Logger, Plugin, ShutdownPhase, traverseDirectory } from 'seedcord';\n\nimport { BaseService } from './BaseService';\nimport { ServiceMetadataKey } from './decorators/DatabaseService';\n\nimport type { BaseServiceConstructor } from './BaseService';\nimport type { Services } from './types/Services';\nimport type { Core } from 'seedcord';\n\n/**\n * Configuration options for MongoDB connection and service loading.\n */\ninterface MongoOptions {\n /** Directory path containing database service classes */\n dir: string;\n /** MongoDB connection URI */\n uri: string;\n /** Database name to use */\n name: string;\n}\n\n/**\n * MongoDB integration plugin for Seedcord.\n *\n * Manages MongoDB connections, service loading, and provides type-safe\n * access to database services through service registration decorators.\n */\nexport class Mongo extends Plugin {\n public readonly logger = new Logger('MongoDB');\n private isInitialised = false;\n private readonly uri: string;\n\n /**\n * Map of all loaded services.\n * Keys come from `@DatabaseService('key')`\n */\n public readonly services: Services = {} as Services;\n\n constructor(\n public readonly core: Core,\n private readonly options: MongoOptions\n ) {\n super(core);\n this.uri = options.uri;\n\n this.core.shutdown.addTask(ShutdownPhase.ExternalResources, 'stop-database', async () => await this.stop());\n }\n\n public async init(): Promise<void> {\n if (this.isInitialised) return;\n this.isInitialised = true;\n\n await this.connect();\n await this.loadServices();\n }\n\n public async stop(): Promise<void> {\n await this.disconnect();\n }\n\n private async connect(): Promise<void> {\n await mongoose\n .connect(this.uri, {\n dbName: this.options.name,\n ...(Globals.isProduction && { tls: true, ssl: true })\n })\n .then((i) => this.logger.info(`Connected to MongoDB: ${chalk.bold.magenta(i.connection.name)}`))\n .catch((err) => {\n throw new Error(`Could not connect to MongoDB`, err);\n });\n }\n\n private async disconnect(): Promise<void> {\n await mongoose\n .disconnect()\n .then(() => this.logger.info(chalk.red.bold('Disconnected from MongoDB')))\n .catch((err) => this.logger.error(`Could not disconnect from MongoDB: ${(err as Error).message}`));\n }\n\n private async loadServices(): Promise<void> {\n const servicesDir = this.options.dir;\n this.logger.info(chalk.bold(servicesDir));\n\n await traverseDirectory(servicesDir, (_full, rel, mod) => {\n for (const Service of Object.values(mod)) {\n if (this.isServiceClass(Service)) {\n const instance = new Service(this, this.core);\n this.logger.info(\n `${chalk.italic('Registered')} ${chalk.bold.yellow(instance.constructor.name)} from ${chalk.gray(rel)}`\n );\n }\n }\n });\n\n this.logger.info(`${chalk.bold.green('Loaded')}: ${chalk.magenta(Object.keys(this.services).length)} services`);\n }\n\n private isServiceClass(obj: unknown): obj is BaseServiceConstructor {\n return (\n typeof obj === 'function' && obj.prototype instanceof BaseService && Reflect.hasMetadata(ServiceMetadataKey, obj)\n );\n }\n\n _register<SKey extends keyof Services>(key: SKey, instance: Services[SKey]): void {\n this.services[key] = instance;\n }\n}\n","import { CustomError, throwCustomError, DatabaseError } from 'seedcord';\n\n/**\n * Catches and wraps database operation errors.\n *\n * Automatically wraps non-CustomError exceptions in DatabaseError instances\n * with UUID tracking. Should be applied to database service methods.\n *\n * @param errorMessage - Message to include when wrapping errors\n * @decorator\n * @example\n * ```typescript\n * class UserService extends BaseService {\n * \\@DBCatchable('Failed to find user')\n * async findById(id: string) {\n * return this.model.findById(id);\n * }\n * }\n * ```\n */\nexport function DBCatchable<TypeReturn>(errorMessage: string) {\n return function (\n _target: unknown,\n _propertyKey: string,\n descriptor: TypedPropertyDescriptor<(...args: any[]) => Promise<TypeReturn>>\n ): void {\n const originalMethod = descriptor.value;\n\n descriptor.value = async function (...args: any[]): Promise<TypeReturn> {\n if (!originalMethod) {\n throw new Error('Method not found');\n }\n\n try {\n return await originalMethod.apply(this, args);\n } catch (error) {\n if (!(error instanceof CustomError)) {\n throwCustomError(error, errorMessage, DatabaseError);\n } else {\n throw error;\n }\n }\n };\n };\n}\n"]}
package/package.json ADDED
@@ -0,0 +1,64 @@
1
+ {
2
+ "name": "@seedcord/plugins",
3
+ "type": "module",
4
+ "version": "0.1.0",
5
+ "description": "Official plugins for Seedcord Discord bot framework",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/materwelondhruv/seedcord.git",
9
+ "directory": "packages/plugins"
10
+ },
11
+ "exports": {
12
+ ".": {
13
+ "types": {
14
+ "development": "./src/index.ts",
15
+ "import": "./dist/index.d.mts",
16
+ "require": "./dist/index.d.cts",
17
+ "default": "./dist/index.d.ts"
18
+ },
19
+ "development": "./src/index.ts",
20
+ "import": {
21
+ "types": "./dist/index.d.mts",
22
+ "default": "./dist/index.mjs"
23
+ },
24
+ "require": {
25
+ "types": "./dist/index.d.cts",
26
+ "default": "./dist/index.cjs"
27
+ },
28
+ "default": "./dist/index.mjs"
29
+ }
30
+ },
31
+ "files": [
32
+ "dist",
33
+ "package.json",
34
+ "README.md",
35
+ "LICENSE"
36
+ ],
37
+ "peerDependencies": {
38
+ "typescript": "^5.9.2"
39
+ },
40
+ "dependencies": {
41
+ "chalk": "^5.5.0",
42
+ "mongoose": "^8.17.1",
43
+ "reflect-metadata": "^0.2.2",
44
+ "@seedcord/types": "^0.1.0",
45
+ "seedcord": "^0.1.0"
46
+ },
47
+ "devDependencies": {
48
+ "@seedcord/eslint-config": "^1.0.1",
49
+ "@seedcord/tsconfig": "^1.0.1",
50
+ "@seedcord/tsup-config": "^1.0.1"
51
+ },
52
+ "scripts": {
53
+ "build": "tsup && cp dist/index.d.cts dist/index.d.mts",
54
+ "clean": "rm -rf dist",
55
+ "lint": "eslint 'src/**/*.{ts,tsx}' --cache",
56
+ "lint:fix": "eslint 'src/**/*.{ts,tsx}' --fix --cache",
57
+ "fmt": "prettier --write 'src/**/*.{ts,tsx,json,md}' --cache",
58
+ "fmt:check": "prettier --check 'src/**/*.{ts,tsx,json,md}' --cache",
59
+ "tc": "tsc --noEmit",
60
+ "test": "vitest run",
61
+ "test:watch": "vitest dev",
62
+ "coverage": "vitest run --coverage"
63
+ }
64
+ }