@tsed/mongoose 7.0.0-beta.9 → 7.0.0-rc.1
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/lib/cjs/MongooseModule.js +3 -1
- package/lib/cjs/MongooseModule.js.map +1 -1
- package/lib/cjs/decorators/dynamicRef.js +3 -3
- package/lib/cjs/decorators/dynamicRef.js.map +1 -1
- package/lib/cjs/decorators/objectID.js +1 -1
- package/lib/cjs/decorators/objectID.js.map +1 -1
- package/lib/cjs/decorators/ref.js +4 -1
- package/lib/cjs/decorators/ref.js.map +1 -1
- package/lib/cjs/interfaces/MongooseSchemaOptions.js.map +1 -1
- package/lib/cjs/services/MongooseService.js +3 -4
- package/lib/cjs/services/MongooseService.js.map +1 -1
- package/lib/cjs/utils/createSchema.js +3 -3
- package/lib/cjs/utils/createSchema.js.map +1 -1
- package/lib/esm/MongooseModule.js +3 -1
- package/lib/esm/MongooseModule.js.map +1 -1
- package/lib/esm/decorators/dynamicRef.js +3 -3
- package/lib/esm/decorators/dynamicRef.js.map +1 -1
- package/lib/esm/decorators/objectID.js +1 -1
- package/lib/esm/decorators/objectID.js.map +1 -1
- package/lib/esm/decorators/ref.js +4 -1
- package/lib/esm/decorators/ref.js.map +1 -1
- package/lib/esm/interfaces/MongooseSchemaOptions.js.map +1 -1
- package/lib/esm/services/MongooseService.js +3 -4
- package/lib/esm/services/MongooseService.js.map +1 -1
- package/lib/esm/utils/createSchema.js +3 -3
- package/lib/esm/utils/createSchema.js.map +1 -1
- package/lib/types/interfaces/MongooseSchemaOptions.d.ts +3 -3
- package/lib/types/utils/createModel.d.ts +1 -1
- package/package.json +20 -17
- package/readme.md +3 -2
|
@@ -10,13 +10,15 @@ const MongooseService_1 = require("./services/MongooseService");
|
|
|
10
10
|
* @ignore
|
|
11
11
|
*/
|
|
12
12
|
let MongooseModule = class MongooseModule {
|
|
13
|
+
mongooseService;
|
|
14
|
+
settings;
|
|
13
15
|
constructor(mongooseService, settings) {
|
|
14
16
|
this.mongooseService = mongooseService;
|
|
15
17
|
this.settings = settings;
|
|
16
18
|
// auto configure the cache manager when mongoose is used with @tsed/mongoose
|
|
17
19
|
const cache = this.settings.get("cache");
|
|
18
20
|
// istanbul ignore next
|
|
19
|
-
if (cache
|
|
21
|
+
if (cache?.mongoose) {
|
|
20
22
|
cache.connection = this.mongooseService.get();
|
|
21
23
|
}
|
|
22
24
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MongooseModule.js","sourceRoot":"","sources":["../../src/MongooseModule.ts"],"names":[],"mappings":";;;;AAAA,iCAA+C;AAC/C,iCAA2C;AAC3C,wEAAoE;AACpE,gEAA2D;AAE3D;;GAEG;AAIH,IAAa,cAAc,GAA3B,MAAa,cAAc;
|
|
1
|
+
{"version":3,"file":"MongooseModule.js","sourceRoot":"","sources":["../../src/MongooseModule.ts"],"names":[],"mappings":";;;;AAAA,iCAA+C;AAC/C,iCAA2C;AAC3C,wEAAoE;AACpE,gEAA2D;AAE3D;;GAEG;AAIH,IAAa,cAAc,GAA3B,MAAa,cAAc;IACL;IAA2D;IAA/E,YAAoB,eAAgC,EAA2B,QAAuB;QAAlF,oBAAe,GAAf,eAAe,CAAiB;QAA2B,aAAQ,GAAR,QAAQ,CAAe;QACpG,6EAA6E;QAC7E,MAAM,KAAK,GAAG,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAM,OAAO,CAAC,CAAC;QAE9C,uBAAuB;QACvB,IAAI,KAAK,EAAE,QAAQ,EAAE;YACnB,KAAK,CAAC,UAAU,GAAG,IAAI,CAAC,eAAe,CAAC,GAAG,EAAE,CAAC;SAC/C;IACH,CAAC;IAED,OAAO,KAAyB,CAAC;IAEjC,UAAU;QACR,OAAO,IAAI,CAAC,eAAe,CAAC,gBAAgB,EAAE,CAAC;IACjD,CAAC;CACF,CAAA;AAhBY,cAAc;IAH1B,IAAA,WAAM,EAAC;QACN,OAAO,EAAE,CAAC,0CAAoB,CAAC;KAChC,CAAC;IAEuD,mBAAA,IAAA,kBAAa,GAAE,CAAA;6CAAjC,iCAAe;GADzC,cAAc,CAgB1B;AAhBY,wCAAc","sourcesContent":["import {Configuration, OnInit} from \"@tsed/di\";\nimport {Module, OnDestroy} from \"@tsed/di\";\nimport {MONGOOSE_CONNECTIONS} from \"./services/MongooseConnections\";\nimport {MongooseService} from \"./services/MongooseService\";\n\n/**\n * @ignore\n */\n@Module({\n imports: [MONGOOSE_CONNECTIONS]\n})\nexport class MongooseModule implements OnDestroy, OnInit {\n constructor(private mongooseService: MongooseService, @Configuration() private settings: Configuration) {\n // auto configure the cache manager when mongoose is used with @tsed/mongoose\n const cache = this.settings.get<any>(\"cache\");\n\n // istanbul ignore next\n if (cache?.mongoose) {\n cache.connection = this.mongooseService.get();\n }\n }\n\n $onInit(): void | Promise<any> {}\n\n $onDestroy(): Promise<any> | void {\n return this.mongooseService.closeConnections();\n }\n}\n"]}
|
|
@@ -11,7 +11,7 @@ function isRef(value) {
|
|
|
11
11
|
return (value && value._bsontype) || (0, core_1.isString)(value);
|
|
12
12
|
}
|
|
13
13
|
function getType(refPath, ctx) {
|
|
14
|
-
return (
|
|
14
|
+
return (ctx?.self[refPath] && MongooseModels_1.MongooseModels.get(ctx.self[refPath])) || Object;
|
|
15
15
|
}
|
|
16
16
|
/**
|
|
17
17
|
* Define a property as mongoose reference to other Model (decorated with @Model).
|
|
@@ -46,7 +46,7 @@ function getType(refPath, ctx) {
|
|
|
46
46
|
* @property
|
|
47
47
|
*/
|
|
48
48
|
function DynamicRef(refPath, ...types) {
|
|
49
|
-
return (0, core_1.useDecorators)((0, schema_1.Property)(Object), (0, schema_1.Example)("5ce7ad3028890bd71749d477"), (0, schema_1.Description)("
|
|
49
|
+
return (0, core_1.useDecorators)((0, schema_1.Property)(Object), (0, schema_1.Example)("5ce7ad3028890bd71749d477"), (0, schema_1.Description)("A reference ObjectID"), (0, core_1.StoreMerge)(constants_1.MONGOOSE_SCHEMA, {
|
|
50
50
|
type: mongoose_1.Schema.Types.ObjectId,
|
|
51
51
|
refPath
|
|
52
52
|
}), (0, json_mapper_1.OnDeserialize)((value, ctx) => {
|
|
@@ -59,7 +59,7 @@ function DynamicRef(refPath, ...types) {
|
|
|
59
59
|
return value.toString();
|
|
60
60
|
}
|
|
61
61
|
return (0, json_mapper_1.serialize)(value, { ...ctx, type: getType(refPath, ctx) });
|
|
62
|
-
}), (0, schema_1.OneOf)((0, schema_1.string)().example("5ce7ad3028890bd71749d477").description("
|
|
62
|
+
}), (0, schema_1.OneOf)((0, schema_1.string)().example("5ce7ad3028890bd71749d477").description("A reference ObjectID"), ...types));
|
|
63
63
|
}
|
|
64
64
|
exports.DynamicRef = DynamicRef;
|
|
65
65
|
//# sourceMappingURL=dynamicRef.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dynamicRef.js","sourceRoot":"","sources":["../../../src/decorators/dynamicRef.ts"],"names":[],"mappings":";;;AAAA,qCAAyF;AACzF,yCAA4F;AAC5F,uCAAkD;AAClD,sDAAuD;AACvD,mDAAqF;AACrF,iEAA4D;AAE5D,SAAS,KAAK,CAAC,KAA+B;IAC5C,OAAO,CAAC,KAAK,IAAI,KAAK,CAAC,SAAS,CAAC,IAAI,IAAA,eAAQ,EAAC,KAAK,CAAC,CAAC;AACvD,CAAC;AAED,SAAS,OAAO,CAAC,OAAe,EAAE,GAAoB;IACpD,OAAO,CAAC,
|
|
1
|
+
{"version":3,"file":"dynamicRef.js","sourceRoot":"","sources":["../../../src/decorators/dynamicRef.ts"],"names":[],"mappings":";;;AAAA,qCAAyF;AACzF,yCAA4F;AAC5F,uCAAkD;AAClD,sDAAuD;AACvD,mDAAqF;AACrF,iEAA4D;AAE5D,SAAS,KAAK,CAAC,KAA+B;IAC5C,OAAO,CAAC,KAAK,IAAI,KAAK,CAAC,SAAS,CAAC,IAAI,IAAA,eAAQ,EAAC,KAAK,CAAC,CAAC;AACvD,CAAC;AAED,SAAS,OAAO,CAAC,OAAe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sBAAsB,CAAC,EAAE,GAAG,KAAK,CAAC,CAC7E,CAAC;AACzB,CAAC;AAzBD,gCAyBC","sourcesContent":["import {classOf, isArrowFn, isString, StoreMerge, Type, useDecorators} from \"@tsed/core\";\nimport {Description, Example, JsonHookContext, OneOf, Property, string} from \"@tsed/schema\";\nimport {Schema as MongooseSchema} from \"mongoose\";\nimport {MONGOOSE_SCHEMA} from \"../constants/constants\";\nimport {deserialize, OnDeserialize, OnSerialize, serialize} from \"@tsed/json-mapper\";\nimport {MongooseModels} from \"../registries/MongooseModels\";\n\nfunction isRef(value: undefined | string | any) {\n return (value && value._bsontype) || isString(value);\n}\n\nfunction getType(refPath: string, ctx: JsonHookContext) {\n return (ctx?.self[refPath] && MongooseModels.get(ctx.self[refPath] as string)) || Object;\n}\n\n/**\n * Define a property as mongoose reference to other Model (decorated with @Model).\n *\n * ### Example\n *\n * ```typescript\n * @Model()\n * class FooModel {\n *\n * @DynamicRef('type')\n * field: DynamicRef<OtherFooModel | OtherModel>\n *\n * @Enum(['OtherFooModel', 'OtherModel'])\n * type: string\n * }\n *\n * @Model()\n * class OtherFooModel {\n * }\n *\n * @Model()\n * class OtherModel {\n * }\n * ```\n *\n * @param refPath {String} the path to apply the correct model\n * @param types {Type} the classes to generate the correct json schema\n * @returns {Function}\n * @decorator\n * @mongoose\n * @property\n */\nexport function DynamicRef(refPath: string, ...types: Type<any>[]): PropertyDecorator {\n return useDecorators(\n Property(Object),\n Example(\"5ce7ad3028890bd71749d477\"),\n Description(\"A reference ObjectID\"),\n StoreMerge(MONGOOSE_SCHEMA, {\n type: MongooseSchema.Types.ObjectId,\n refPath\n }),\n OnDeserialize((value, ctx) => {\n if (isRef(value)) {\n return value.toString();\n }\n\n return deserialize(value, {...ctx, type: getType(refPath, ctx)});\n }),\n OnSerialize((value: any, ctx) => {\n if (isRef(value)) {\n return value.toString();\n }\n\n return serialize(value, {...ctx, type: getType(refPath, ctx)});\n }),\n OneOf(string().example(\"5ce7ad3028890bd71749d477\").description(\"A reference ObjectID\"), ...types)\n ) as PropertyDecorator;\n}\n\nexport type DynamicRef<T> = T | string;\n"]}
|
|
@@ -20,7 +20,7 @@ const schema_1 = require("@tsed/schema");
|
|
|
20
20
|
* @schema
|
|
21
21
|
*/
|
|
22
22
|
function ObjectID(name) {
|
|
23
|
-
return (0, core_1.useDecorators)(name && (0, schema_1.Name)(name), (0, schema_1.Pattern)(/^[0-9a-fA-F]{24}$/), (0, schema_1.Description)("
|
|
23
|
+
return (0, core_1.useDecorators)(name && (0, schema_1.Name)(name), (0, schema_1.Pattern)(/^[0-9a-fA-F]{24}$/), (0, schema_1.Description)("An ObjectID"), (0, schema_1.Example)("5ce7ad3028890bd71749d477"));
|
|
24
24
|
}
|
|
25
25
|
exports.ObjectID = ObjectID;
|
|
26
26
|
//# sourceMappingURL=objectID.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"objectID.js","sourceRoot":"","sources":["../../../src/decorators/objectID.ts"],"names":[],"mappings":";;;AAAA,qCAAyC;AACzC,yCAAiE;AAGjE;;;;;;;;;;;;;;;GAeG;AACH,SAAgB,QAAQ,CAAC,IAAa;IACpC,OAAO,IAAA,oBAAa,
|
|
1
|
+
{"version":3,"file":"objectID.js","sourceRoot":"","sources":["../../../src/decorators/objectID.ts"],"names":[],"mappings":";;;AAAA,qCAAyC;AACzC,yCAAiE;AAGjE;;;;;;;;;;;;;;;GAeG;AACH,SAAgB,QAAQ,CAAC,IAAa;IACpC,OAAO,IAAA,oBAAa,EAAC,IAAI,IAAI,IAAA,aAAI,EAAC,IAAI,CAAC,EAAE,IAAA,gBAAO,EAAC,mBAAmB,CAAC,EAAE,IAAA,oBAAW,EAAC,aAAa,CAAC,EAAE,IAAA,gBAAO,EAAC,0BAA0B,CAAC,CAAC,CAAC;AAC1I,CAAC;AAFD,4BAEC","sourcesContent":["import {useDecorators} from \"@tsed/core\";\nimport {Description, Example, Name, Pattern} from \"@tsed/schema\";\nimport {Types} from \"mongoose\";\n\n/**\n * Tell Mongoose whether to define an ObjectId property.\n * ### Example\n *\n * ```typescript\n * @Model()\n * export class EventModel {\n * @ObjectId('id')\n * _id: string;\n * }\n * ```\n * @param name\n * @decorator\n * @mongoose\n * @schema\n */\nexport function ObjectID(name?: string) {\n return useDecorators(name && Name(name), Pattern(/^[0-9a-fA-F]{24}$/), Description(\"An ObjectID\"), Example(\"5ce7ad3028890bd71749d477\"));\n}\n\nexport type ObjectID = Types.ObjectId;\n"]}
|
|
@@ -53,6 +53,9 @@ function PopulateGroups(populatedGroups) {
|
|
|
53
53
|
* @property
|
|
54
54
|
*/
|
|
55
55
|
function Ref(model, options = MongooseSchemaTypes_1.MongooseSchemaTypes.OBJECT_ID) {
|
|
56
|
+
if (!model) {
|
|
57
|
+
throw new Error("A model is required on `@Ref(model)` decorator. Please give a model or wrap it inside an arrow function if you have a circular reference.");
|
|
58
|
+
}
|
|
56
59
|
const getType = () => ((0, core_1.isString)(model) ? MongooseModels_1.MongooseModels.get(model) : (0, core_1.isArrowFn)(model) ? model() : model);
|
|
57
60
|
const populatedGroups = ((0, core_1.isObject)(options) && options.populatedGroups) || [];
|
|
58
61
|
return (0, core_1.useDecorators)((0, schema_1.Property)(Object), (0, core_1.StoreMerge)(constants_1.MONGOOSE_SCHEMA, {
|
|
@@ -69,7 +72,7 @@ function Ref(model, options = MongooseSchemaTypes_1.MongooseSchemaTypes.OBJECT_I
|
|
|
69
72
|
}
|
|
70
73
|
const type = getType();
|
|
71
74
|
return (0, json_mapper_1.serialize)(value, { ...ctx, type });
|
|
72
|
-
}), (0, schema_1.OneOf)((0, schema_1.string)().example("5ce7ad3028890bd71749d477").description("
|
|
75
|
+
}), (0, schema_1.OneOf)((0, schema_1.string)().example("5ce7ad3028890bd71749d477").description("A reference ObjectID"), (0, schema_1.lazyRef)(getType)), populatedGroups.length && PopulateGroups(populatedGroups));
|
|
73
76
|
}
|
|
74
77
|
exports.Ref = Ref;
|
|
75
78
|
//# sourceMappingURL=ref.js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String, StoreMerge, Type, useDecorators} from \"@tsed/core\";\nimport {OnDeserialize, OnSerialize, serialize} from \"@tsed/json-mapper\";\nimport {ForwardGroups, JsonEntityFn, lazyRef, matchGroups, OneOf, Property, string} from \"@tsed/schema\";\nimport {Schema as MongooseSchema} from \"mongoose\";\nimport {MONGOOSE_SCHEMA} from \"../constants/constants\";\nimport {MongooseSchemaTypes} from \"../interfaces/MongooseSchemaTypes\";\nimport {MongooseModels} from \"../registries/MongooseModels\";\n\ninterface RefOptions {\n type?: MongooseSchemaTypes;\n populatedGroups?: string[];\n}\n\nfunction isRef(value: undefined | string | any) {\n return (value && value._bsontype) || isString(value);\n}\n\nfunction PopulateGroups(populatedGroups: string[]) {\n return useDecorators(\n ForwardGroups(true),\n JsonEntityFn((store) => {\n store.schema.$hooks.on(\"oneOf\", (obj: any[], givenGroups: string[]) => {\n if (matchGroups(populatedGroups, givenGroups)) {\n return obj.filter((x) => x.type === \"string\"); // keep the object id;\n } else {\n return obj.filter((x) => x.type !== \"string\"); // keep the ref definition\n }\n });\n })\n );\n}\n\n/**\n * Define a property as mongoose reference to other Model (decorated with @Model).\n *\n * ### Example\n *\n * ```typescript\n *\n * @Model()\n * class FooModel {\n *\n * @Ref(Foo2Model)\n * field: Ref<Foo2Model>\n *\n * @Ref(Foo2Model)\n * list: Ref<Foo2Model>[]\n * }\n *\n * @Model()\n * class Foo2Model {\n * }\n * ```\n *\n * @param model\n * @param options\n * @returns {Function}\n * @decorator\n * @mongoose\n * @property\n */\nexport function Ref(\n model: string | (() => Type) | any,\n options: RefOptions | MongooseSchemaTypes = MongooseSchemaTypes.OBJECT_ID\n): PropertyDecorator {\n if (!model) {\n throw new Error(\n \"A model is required on `@Ref(model)` decorator. Please give a model or wrap it inside an arrow function if you have a circular reference.\"\n );\n }\n\n const getType = () => (isString(model) ? MongooseModels.get(model) : isArrowFn(model) ? model() : model);\n const populatedGroups = (isObject(options) && options.populatedGroups) || [];\n\n return useDecorators(\n Property(Object),\n StoreMerge(MONGOOSE_SCHEMA, {\n type: MongooseSchema.Types[isObject(options) ? options.type || MongooseSchemaTypes.OBJECT_ID : options],\n ref: model\n }),\n OnDeserialize((value) => {\n if (isRef(value)) {\n return value.toString();\n }\n\n return value;\n }),\n OnSerialize((value: any, ctx) => {\n if (isRef(value)) {\n return value.toString();\n }\n const type = getType();\n\n return serialize(value, {...ctx, type});\n }),\n OneOf(string().example(\"5ce7ad3028890bd71749d477\").description(\"A reference ObjectID\"), lazyRef(getType)),\n populatedGroups.length && PopulateGroups(populatedGroups)\n ) as PropertyDecorator;\n}\n\nexport type Ref<T> = T | string;\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MongooseSchemaOptions.js","sourceRoot":"","sources":["../../../src/interfaces/MongooseSchemaOptions.ts"],"names":[],"mappings":"","sourcesContent":["import {
|
|
1
|
+
{"version":3,"file":"MongooseSchemaOptions.js","sourceRoot":"","sources":["../../../src/interfaces/MongooseSchemaOptions.ts"],"names":[],"mappings":"","sourcesContent":["import {Schema, SchemaOptions} from \"mongoose\";\nimport {MongooseDocument} from \"./MongooseDocument\";\n\nexport type MongooseNextCB = (err?: Error) => void;\n\nexport interface MongooseHookOptions {\n document?: boolean;\n query?: boolean;\n parallel?: boolean;\n}\n\nexport type MongoosePreHookCB<T = any> =\n | ((doc: T | MongooseDocument<T>, next: MongooseNextCB) => void)\n | ((doc: T | MongooseDocument<T>) => Promise<void> | void);\n\nexport type MongoosePostHookCB<T = any> =\n | ((doc: T | MongooseDocument<T>, error: Error, next: MongooseNextCB) => void)\n | ((doc: T | MongooseDocument<T>, error: Error) => Promise<void> | void)\n | ((doc: T | MongooseDocument<T>, next: MongooseNextCB) => void)\n | ((doc: T | MongooseDocument<T>) => Promise<void> | void);\n\nexport interface MongoosePreHook<T = any> {\n method: string | RegExp;\n fn: MongoosePreHookCB<T>;\n options?: MongooseHookOptions;\n}\n\nexport interface MongoosePostHook<T = any> {\n method: string | RegExp;\n fn: MongoosePostHookCB<T>;\n options?: MongooseHookOptions;\n}\n\nexport interface MongoosePluginOptions {\n plugin: (schema: Schema, options?: any) => void;\n options?: Record<string, unknown>;\n}\n\nexport interface MongooseIndexOptions {\n fields: Record<any, any>;\n options?: Record<string, unknown>;\n}\n\nexport interface MongooseSchemaOptions {\n schemaOptions?: SchemaOptions;\n plugins?: MongoosePluginOptions[];\n indexes?: MongooseIndexOptions[];\n pre?: MongoosePreHook[];\n post?: MongoosePostHook[];\n}\n"]}
|
|
@@ -10,10 +10,9 @@ function asPromise(c) {
|
|
|
10
10
|
return c && c.asPromise ? c.asPromise() : c;
|
|
11
11
|
}
|
|
12
12
|
let MongooseService = class MongooseService {
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
}
|
|
13
|
+
connections = new Map();
|
|
14
|
+
defaultConnection = "default";
|
|
15
|
+
logger;
|
|
17
16
|
/**
|
|
18
17
|
*
|
|
19
18
|
* @returns {Promise<"mongoose".Connection>}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MongooseService.js","sourceRoot":"","sources":["../../../src/services/MongooseService.ts"],"names":[],"mappings":";;;;AAAA,iCAA4C;AAC5C,yCAAoC;AACpC,gEAAgC;AAGhC,uBAAuB;AACvB,SAAS,SAAS,CAAC,CAAM;IACvB,OAAO,CAAC,IAAI,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;AAC9C,CAAC;AAGD,IAAa,eAAe,GAA5B,MAAa,eAAe;
|
|
1
|
+
{"version":3,"file":"MongooseService.js","sourceRoot":"","sources":["../../../src/services/MongooseService.ts"],"names":[],"mappings":";;;;AAAA,iCAA4C;AAC5C,yCAAoC;AACpC,gEAAgC;AAGhC,uBAAuB;AACvB,SAAS,SAAS,CAAC,CAAM;IACvB,OAAO,CAAC,IAAI,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,EAAE,CAAC,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AI,CAAC,iBAAiB,CAAC,CAAC;IAC5D,CAAC;IAED;;;;OAIG;IACH,GAAG,CAAC,EAAW;QACb,OAAO,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,EAAE,IAAI,IAAI,CAAC,iBAAiB,CAAC,CAAC;IAC5D,CAAC;IAED,KAAK,CAAC,gBAAgB;QACpB,KAAK,MAAM,CAAC,EAAE,EAAE,UAAU,CAAC,IAAI,IAAI,CAAC,WAAW,CAAC,OAAO,EAAE,EAAE;YACzD,MAAM,UAAU,CAAC,KAAK,EAAE,CAAC;YACzB,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;SAC7B;IACH,CAAC;CACF,CAAA;AAvDC;IADC,IAAA,WAAM,GAAE;sCACD,eAAM;+CAAC;AALJ,eAAe;IAD3B,IAAA,eAAU,GAAE;GACA,eAAe,CA4D3B;AA5DY,0CAAe","sourcesContent":["import {Inject, Injectable} from \"@tsed/di\";\nimport {Logger} from \"@tsed/logger\";\nimport Mongoose from \"mongoose\";\nimport {ConnectOptions} from \"mongoose\";\n\n// istanbul ignore next\nfunction asPromise(c: any) {\n return c && c.asPromise ? c.asPromise() : c;\n}\n\n@Injectable()\nexport class MongooseService {\n readonly connections: Map<string, Mongoose.Connection> = new Map();\n private defaultConnection: string = \"default\";\n\n @Inject()\n logger: Logger;\n\n /**\n *\n * @returns {Promise<\"mongoose\".Connection>}\n */\n async connect(id: string, url: string, connectionOptions: ConnectOptions, isDefault = false): Promise<any> {\n if (this.has(id)) {\n return await this.get(id)!;\n }\n\n this.logger.info(`Connect to mongo database: ${id}`);\n this.logger.debug(`Url: ${url}`);\n this.logger.debug(`options: ${JSON.stringify(connectionOptions)}`);\n\n try {\n const connection = await asPromise(Mongoose.createConnection(url, connectionOptions));\n this.connections.set(id, connection);\n\n if (id === \"default\" || isDefault) {\n this.defaultConnection = id;\n }\n\n return connection;\n } catch (er) {\n /* istanbul ignore next */\n this.logger.error(er);\n /* istanbul ignore next */\n process.exit();\n }\n }\n\n /**\n *\n * @returns {\"mongoose\".Connection}\n */\n get(id?: string): Mongoose.Connection | undefined {\n return this.connections.get(id || this.defaultConnection);\n }\n\n /**\n *\n * @param {string} id\n * @returns {boolean}\n */\n has(id?: string): boolean {\n return this.connections.has(id || this.defaultConnection);\n }\n\n async closeConnections() {\n for (const [id, connection] of this.connections.entries()) {\n await connection.close();\n this.connections.delete(id);\n }\n }\n}\n"]}
|
|
@@ -35,14 +35,14 @@ function hasVersionField(schema, versionKey) {
|
|
|
35
35
|
return versionKey in schema.paths;
|
|
36
36
|
}
|
|
37
37
|
function createSchema(target, options = {}) {
|
|
38
|
-
var _a;
|
|
39
38
|
const schemaOptionsFromStore = core_1.Store.from(target).get(constants_1.MONGOOSE_SCHEMA_OPTIONS) || {};
|
|
40
39
|
options.schemaOptions = { ...options.schemaOptions, ...schemaOptionsFromStore };
|
|
41
40
|
const schema = setUpSchema(buildMongooseSchema(target), options.schemaOptions);
|
|
42
41
|
(0, schemaOptions_1.schemaOptions)(target, options);
|
|
43
|
-
const outputVersionKey = hasVersionField(schema,
|
|
42
|
+
const outputVersionKey = hasVersionField(schema, options.schemaOptions?.versionKey);
|
|
44
43
|
schema.methods.toClass = function toClass() {
|
|
45
44
|
return (0, json_mapper_1.deserialize)(this.toObject({
|
|
45
|
+
virtuals: true,
|
|
46
46
|
versionKey: outputVersionKey,
|
|
47
47
|
flattenMaps: true
|
|
48
48
|
}), {
|
|
@@ -91,7 +91,7 @@ function buildMongooseSchema(target) {
|
|
|
91
91
|
}
|
|
92
92
|
// Keeping the Mongoose Schema separate so it can overwrite everything once schema has been built.
|
|
93
93
|
const schemaTypeOptions = propertyMetadata.store.get(constants_1.MONGOOSE_SCHEMA) || {};
|
|
94
|
-
if (schemaTypeOptions.schemaIgnore) {
|
|
94
|
+
if (schemaTypeOptions.schemaIgnore || propertyMetadata.schema.isReadOnly) {
|
|
95
95
|
return;
|
|
96
96
|
}
|
|
97
97
|
if (schemaTypeOptions.ref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AAiB,GAAG,EAAC,GAAG,iBAAiB,EAAE,IAAI,EAAE,SAAS,CAAC,UAAU,CAAC,IAAI,CAAQ,EAAC,CAAC;KACrF;IAED,iBAAiB,GAAG,IAAA,kBAAW,EAAC,EAAC,GAAG,iBAAiB,EAAE,GAAG,iBAAiB,EAAC,CAAC,CAAC;IAE9E,IAAI,UAAU,CAAC,YAAY,EAAE;QAC3B,IAAI,UAAU,CAAC,OAAO,EAAE;YACtB,OAAO,CAAC,iBAAiB,CAAC,CAAC;SAC5B;QACD,yBAAyB;QACzB,gCAAgC;QAChC,IAAI,UAAU,CAAC,cAAc,KAAK,GAAG,EAAE;YACrC,MAAM,IAAI,KAAK,CAAC,4BAA4B,IAAA,aAAM,EAAC,UAAU,CAAC,cAAc,CAAC,oBAAoB,CAAC,CAAC;SACpG;QAED,OAAO,EAAC,IAAI,EAAE,GAAG,EAAE,EAAE,EAAE,iBAAiB,EAAoC,CAAC;KAC9E;IAED,OAAO,iBAAiB,CAAC;AAC3B,CAAC;AArDD,0DAqDC","sourcesContent":["import {cleanObject, nameOf, Store, Type} from \"@tsed/core\";\nimport {deserialize, serialize} from \"@tsed/json-mapper\";\nimport {getProperties, JsonEntityStore} from \"@tsed/schema\";\nimport {pascalCase} from \"change-case\";\nimport mongoose, {Schema, SchemaDefinition, SchemaOptions, SchemaTypeOptions} from \"mongoose\";\nimport {MONGOOSE_SCHEMA, MONGOOSE_SCHEMA_OPTIONS} from \"../constants/constants\";\nimport {MongooseSchemaOptions} from \"../interfaces/MongooseSchemaOptions\";\nimport {MongooseVirtualRefOptions} from \"../interfaces/MongooseVirtualRefOptions\";\nimport {resolveRefType} from \"./resolveRefType\";\nimport {schemaOptions} from \"./schemaOptions\";\n\nconst MONGOOSE_RESERVED_KEYS = [\"_id\"];\n\nexport interface MongooseSchemaMetadata {\n schema: SchemaDefinition;\n virtuals: Map<string, MongooseVirtualRefOptions>;\n}\n\n/**\n * @ignore\n */\nfunction setUpSchema({schema, virtuals}: MongooseSchemaMetadata, options?: SchemaOptions) {\n const mongooseSchema = new mongoose.Schema(schema, options);\n\n for (const [key, options] of virtuals.entries()) {\n mongooseSchema.virtual(key, options);\n }\n\n return mongooseSchema;\n}\n\n/**\n * @ignore\n */\nfunction isVirtualRef(target: Partial<MongooseVirtualRefOptions>): target is MongooseVirtualRefOptions {\n return !!(target.ref && target.localField && target.foreignField);\n}\n\nfunction hasVersionField(schema: mongoose.Schema, versionKey?: string | boolean) {\n // Check if versioning was disabled explicitly\n if (!versionKey) return false;\n\n // Check for alternative version field in schema\n return (versionKey as string) in schema.paths;\n}\n\nexport function createSchema(target: Type<any>, options: MongooseSchemaOptions = {}): mongoose.Schema {\n const schemaOptionsFromStore = Store.from(target).get(MONGOOSE_SCHEMA_OPTIONS) || {};\n options.schemaOptions = {...options.schemaOptions, ...schemaOptionsFromStore};\n\n const schema = setUpSchema(buildMongooseSchema(target), options.schemaOptions);\n\n schemaOptions(target, options);\n\n const outputVersionKey = hasVersionField(schema, options.schemaOptions?.versionKey);\n\n schema.methods.toClass = function toClass() {\n return deserialize(\n this.toObject({\n versionKey: outputVersionKey,\n flattenMaps: true\n }),\n {\n type: target,\n useAlias: false,\n additionalProperties: true,\n groups: false\n }\n );\n };\n\n schema.methods.toJSON = function toJSON(options?: any) {\n return serialize((this as any).toClass(), options);\n };\n\n schema.loadClass(target);\n\n Store.from(target).set(MONGOOSE_SCHEMA, schema);\n\n return schema;\n}\n\n/**\n * Get a schema already created. If the schema doesn't exists in registry, it'll be created.\n * @param target\n * @param options\n */\nexport function getSchema(target: Type<any>, options: MongooseSchemaOptions = {}): Schema {\n const store = Store.from(target);\n\n if (!store.has(MONGOOSE_SCHEMA)) {\n createSchema(target, options);\n }\n\n return store.get(MONGOOSE_SCHEMA);\n}\n\nexport function getSchemaToken(target: Type<any>, options?: any) {\n const collectionName = options.name || nameOf(target);\n const token = Symbol.for(pascalCase(`${collectionName}Schema`));\n\n return {token, collectionName};\n}\n\n/**\n * @ignore\n */\nexport function buildMongooseSchema(target: any): MongooseSchemaMetadata {\n const properties = getProperties(target, {withIgnoredProps: true, mongoose: true, groups: false});\n const schema: MongooseSchemaMetadata = {schema: {}, virtuals: new Map()};\n\n properties.forEach((propertyMetadata, key) => {\n if (MONGOOSE_RESERVED_KEYS.includes(key as string)) {\n return;\n }\n\n // Keeping the Mongoose Schema separate so it can overwrite everything once schema has been built.\n const schemaTypeOptions: any = propertyMetadata.store.get(MONGOOSE_SCHEMA) || {};\n\n if (schemaTypeOptions.schemaIgnore) {\n return;\n }\n\n if (schemaTypeOptions.ref) {\n schemaTypeOptions.ref = resolveRefType(schemaTypeOptions.ref as any);\n }\n\n if (isVirtualRef(schemaTypeOptions)) {\n schema.virtuals.set(key as string, schemaTypeOptions);\n\n return;\n }\n\n schema.schema[key as string] = createSchemaTypeOptions(propertyMetadata);\n });\n\n return schema;\n}\n\n/**\n * @ignore\n */\nexport function createSchemaTypeOptions<T = any>(propEntity: JsonEntityStore): SchemaTypeOptions<T> | SchemaTypeOptions<T>[] {\n const key = propEntity.propertyKey;\n const rawMongooseSchema = propEntity.store.get(MONGOOSE_SCHEMA) || {};\n\n let schemaTypeOptions: SchemaTypeOptions<T> = {\n required: propEntity.required\n ? function () {\n return propEntity.isRequired(this[key]);\n }\n : false\n };\n\n if (!propEntity.isClass) {\n const jsonSchema = propEntity.itemSchema.toJSON();\n const {minimum: min, maximum: max, minLength: minlength, maxLength: maxlength} = jsonSchema;\n\n let match: string | RegExp = jsonSchema.pattern;\n if (match) {\n match = new RegExp(match);\n }\n\n schemaTypeOptions = {\n ...schemaTypeOptions,\n type: propEntity.type,\n match: match as RegExp,\n min,\n max,\n minlength,\n maxlength,\n enum: jsonSchema[\"enum\"],\n default: jsonSchema[\"default\"]\n };\n } else if (!rawMongooseSchema.ref) {\n // References are handled by the final merge\n schemaTypeOptions = {...schemaTypeOptions, type: getSchema(propEntity.type) as any};\n }\n\n schemaTypeOptions = cleanObject({...schemaTypeOptions, ...rawMongooseSchema});\n\n if (propEntity.isCollection) {\n if (propEntity.isArray) {\n return [schemaTypeOptions];\n }\n // Can be a Map or a Set;\n // Mongoose implements only Map;\n if (propEntity.collectionType !== Map) {\n throw new Error(`Invalid collection type. ${nameOf(propEntity.collectionType)} is not supported.`);\n }\n\n return {type: Map, of: schemaTypeOptions} as unknown as SchemaTypeOptions<T>;\n }\n\n return schemaTypeOptions;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"createSchema.js","sourceRoot":"","sources":["../../../src/utils/createSchema.ts"],"names":[],"mappings":";;;;AAAA,qCAA4D;AAC5D,mDAAyD;AACzD,yCAA4D;AAC5D,6CAAuC;AACvC,gEAA8F;AAC9F,sDAAgF;AAGhF,qDAAgD;AAChD,mDAA8C;AAE9C,MAAM,sBAAsB,GAAG,CAAC,KAAK,CAAC,CAAC;AAOvC;;GAEG;AACH,SAAS,WAAW,CAAC,EAAC,MAAM,EAAE,QAAQ,EAAyB,EAAE,OAAuB;IACtF,MAAM,cAAc,GAAG,IAAI,kBAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAE5D,KAAK,MAAM,CAAC,GAAG,EAAE,OAAO,CAAC,IAAI,QAAQ,CAAC,OAAO,EAAE,EAAE;QAC/C,cAAc,CAAC,OAAO,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;KACtC;IAED,OAAO,cAAc,CAAC;AACxB,CAAC;AAED;;GAEG;AACH,SAAS,YAAY,CAAC,MAA0C;IAC9D,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,IAAI,MAAM,CAAC,UAAU,IAAI,MAAM,CAAC,YAAY,CAAC,CAAC;AACpE,CAAC;AAED,SAAS,eAAe,CAAC,MAAuB,EAAE,UAA6B;IAC7E,8CAA8C;IAC9C,IAAI,CAAC,UAAU;QAAE,OAAO,KAAK,CAAC;IAE9B,gDAAgD;IAChD,OAAQ,UAAqB,IAAI,MAAM,CAAC,KAAK,CAAC;AAChD,CAAC;AAED,SAAgB,YAAY,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B;YACpB,IAAI,EAAE,UAAU,CAAC,IAAI;YACrB,KAAK,EAAE,KAAe;YACtB,GAAG;YACH,GAAG;YACH,SAAS;YACT,SAAS;YACT,IAAI,EAAE,UAAU,CAAC,MAAM,CAAC;YACxB,OAAO,EAAE,UAAU,CAAC,SAAS,CAAC;SAC/B,CAAC;KACH;SAAM,IAAI,CAAC,iBAAiB,CAAC,GAAG,EAAE;QACjC,4CAA4C;QAC5C,iBAAiB,GAAG,EAAC,GAAG,iBAAiB,EAAE,IAAI,EAAE,SAAS,CAAC,UAAU,CAAC,IAAI,CAAQ,EAAC,CAAC;KACrF;IAED,iBAAiB,GAAG,IAAA,kBAAW,EAAC,EAAC,GAAG,iBAAiB,EAAE,GAAG,iBAAiB,EAAC,CAAC,CAAC;IAE9E,IAAI,UAAU,CAAC,YAAY,EAAE;QAC3B,IAAI,UAAU,CAAC,OAAO,EAAE;YACtB,OAAO,CAAC,iBAAiB,CAAC,CAAC;SAC5B;QACD,yBAAyB;QACzB,gCAAgC;QAChC,IAAI,UAAU,CAAC,cAAc,KAAK,GAAG,EAAE;YACrC,MAAM,IAAI,KAAK,CAAC,4BAA4B,IAAA,aAAM,EAAC,UAAU,CAAC,cAAc,CAAC,oBAAoB,CAAC,CAAC;SACpG;QAED,OAAO,EAAC,IAAI,EAAE,GAAG,EAAE,EAAE,EAAE,iBAAiB,EAAoC,CAAC;KAC9E;IAED,OAAO,iBAAiB,CAAC;AAC3B,CAAC;AArDD,0DAqDC","sourcesContent":["import {cleanObject, nameOf, Store, Type} from \"@tsed/core\";\nimport {deserialize, serialize} from \"@tsed/json-mapper\";\nimport {getProperties, JsonEntityStore} from \"@tsed/schema\";\nimport {pascalCase} from \"change-case\";\nimport mongoose, {Schema, SchemaDefinition, SchemaOptions, SchemaTypeOptions} from \"mongoose\";\nimport {MONGOOSE_SCHEMA, MONGOOSE_SCHEMA_OPTIONS} from \"../constants/constants\";\nimport {MongooseSchemaOptions} from \"../interfaces/MongooseSchemaOptions\";\nimport {MongooseVirtualRefOptions} from \"../interfaces/MongooseVirtualRefOptions\";\nimport {resolveRefType} from \"./resolveRefType\";\nimport {schemaOptions} from \"./schemaOptions\";\n\nconst MONGOOSE_RESERVED_KEYS = [\"_id\"];\n\nexport interface MongooseSchemaMetadata {\n schema: SchemaDefinition;\n virtuals: Map<string, MongooseVirtualRefOptions>;\n}\n\n/**\n * @ignore\n */\nfunction setUpSchema({schema, virtuals}: MongooseSchemaMetadata, options?: SchemaOptions) {\n const mongooseSchema = new mongoose.Schema(schema, options);\n\n for (const [key, options] of virtuals.entries()) {\n mongooseSchema.virtual(key, options);\n }\n\n return mongooseSchema;\n}\n\n/**\n * @ignore\n */\nfunction isVirtualRef(target: Partial<MongooseVirtualRefOptions>): target is MongooseVirtualRefOptions {\n return !!(target.ref && target.localField && target.foreignField);\n}\n\nfunction hasVersionField(schema: mongoose.Schema, versionKey?: string | boolean) {\n // Check if versioning was disabled explicitly\n if (!versionKey) return false;\n\n // Check for alternative version field in schema\n return (versionKey as string) in schema.paths;\n}\n\nexport function createSchema(target: Type<any>, options: MongooseSchemaOptions = {}): mongoose.Schema {\n const schemaOptionsFromStore = Store.from(target).get(MONGOOSE_SCHEMA_OPTIONS) || {};\n options.schemaOptions = {...options.schemaOptions, ...schemaOptionsFromStore};\n\n const schema = setUpSchema(buildMongooseSchema(target), options.schemaOptions);\n\n schemaOptions(target, options);\n\n const outputVersionKey = hasVersionField(schema, options.schemaOptions?.versionKey);\n\n schema.methods.toClass = function toClass() {\n return deserialize(\n this.toObject({\n virtuals: true,\n versionKey: outputVersionKey,\n flattenMaps: true\n }),\n {\n type: target,\n useAlias: false,\n additionalProperties: true,\n groups: false\n }\n );\n };\n\n schema.methods.toJSON = function toJSON(options?: any) {\n return serialize((this as any).toClass(), options);\n };\n\n schema.loadClass(target);\n\n Store.from(target).set(MONGOOSE_SCHEMA, schema);\n\n return schema;\n}\n\n/**\n * Get a schema already created. If the schema doesn't exists in registry, it'll be created.\n * @param target\n * @param options\n */\nexport function getSchema(target: Type<any>, options: MongooseSchemaOptions = {}): Schema {\n const store = Store.from(target);\n\n if (!store.has(MONGOOSE_SCHEMA)) {\n createSchema(target, options);\n }\n\n return store.get(MONGOOSE_SCHEMA);\n}\n\nexport function getSchemaToken(target: Type<any>, options?: any) {\n const collectionName = options.name || nameOf(target);\n const token = Symbol.for(pascalCase(`${collectionName}Schema`));\n\n return {token, collectionName};\n}\n\n/**\n * @ignore\n */\nexport function buildMongooseSchema(target: any): MongooseSchemaMetadata {\n const properties = getProperties(target, {withIgnoredProps: true, mongoose: true, groups: false});\n const schema: MongooseSchemaMetadata = {schema: {}, virtuals: new Map()};\n\n properties.forEach((propertyMetadata, key) => {\n if (MONGOOSE_RESERVED_KEYS.includes(key as string)) {\n return;\n }\n\n // Keeping the Mongoose Schema separate so it can overwrite everything once schema has been built.\n const schemaTypeOptions: any = propertyMetadata.store.get(MONGOOSE_SCHEMA) || {};\n\n if (schemaTypeOptions.schemaIgnore || propertyMetadata.schema.isReadOnly) {\n return;\n }\n\n if (schemaTypeOptions.ref) {\n schemaTypeOptions.ref = resolveRefType(schemaTypeOptions.ref as any);\n }\n\n if (isVirtualRef(schemaTypeOptions)) {\n schema.virtuals.set(key as string, schemaTypeOptions);\n\n return;\n }\n\n schema.schema[key as string] = createSchemaTypeOptions(propertyMetadata);\n });\n\n return schema;\n}\n\n/**\n * @ignore\n */\nexport function createSchemaTypeOptions<T = any>(propEntity: JsonEntityStore): SchemaTypeOptions<T> | SchemaTypeOptions<T>[] {\n const key = propEntity.propertyKey;\n const rawMongooseSchema = propEntity.store.get(MONGOOSE_SCHEMA) || {};\n\n let schemaTypeOptions: SchemaTypeOptions<T> = {\n required: propEntity.required\n ? function () {\n return propEntity.isRequired(this[key]);\n }\n : false\n };\n\n if (!propEntity.isClass) {\n const jsonSchema = propEntity.itemSchema.toJSON();\n const {minimum: min, maximum: max, minLength: minlength, maxLength: maxlength} = jsonSchema;\n\n let match: string | RegExp = jsonSchema.pattern;\n if (match) {\n match = new RegExp(match);\n }\n\n schemaTypeOptions = {\n ...schemaTypeOptions,\n type: propEntity.type,\n match: match as RegExp,\n min,\n max,\n minlength,\n maxlength,\n enum: jsonSchema[\"enum\"],\n default: jsonSchema[\"default\"]\n };\n } else if (!rawMongooseSchema.ref) {\n // References are handled by the final merge\n schemaTypeOptions = {...schemaTypeOptions, type: getSchema(propEntity.type) as any};\n }\n\n schemaTypeOptions = cleanObject({...schemaTypeOptions, ...rawMongooseSchema});\n\n if (propEntity.isCollection) {\n if (propEntity.isArray) {\n return [schemaTypeOptions];\n }\n // Can be a Map or a Set;\n // Mongoose implements only Map;\n if (propEntity.collectionType !== Map) {\n throw new Error(`Invalid collection type. ${nameOf(propEntity.collectionType)} is not supported.`);\n }\n\n return {type: Map, of: schemaTypeOptions} as unknown as SchemaTypeOptions<T>;\n }\n\n return schemaTypeOptions;\n}\n"]}
|
|
@@ -7,13 +7,15 @@ import { MongooseService } from "./services/MongooseService.js";
|
|
|
7
7
|
* @ignore
|
|
8
8
|
*/
|
|
9
9
|
let MongooseModule = class MongooseModule {
|
|
10
|
+
mongooseService;
|
|
11
|
+
settings;
|
|
10
12
|
constructor(mongooseService, settings) {
|
|
11
13
|
this.mongooseService = mongooseService;
|
|
12
14
|
this.settings = settings;
|
|
13
15
|
// auto configure the cache manager when mongoose is used with @tsed/mongoose
|
|
14
16
|
const cache = this.settings.get("cache");
|
|
15
17
|
// istanbul ignore next
|
|
16
|
-
if (cache
|
|
18
|
+
if (cache?.mongoose) {
|
|
17
19
|
cache.connection = this.mongooseService.get();
|
|
18
20
|
}
|
|
19
21
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MongooseModule.js","sourceRoot":"","sources":["../../src/MongooseModule.ts"],"names":[],"mappings":";AAAA,OAAO,EAAC,aAAa,EAAS,MAAM,UAAU,CAAC;AAC/C,OAAO,EAAC,MAAM,EAAY,MAAM,UAAU,CAAC;AAC3C,OAAO,EAAC,oBAAoB,EAAC,MAAM,gCAAgC,CAAC;AACpE,OAAO,EAAC,eAAe,EAAC,MAAM,4BAA4B,CAAC;AAE3D;;GAEG;AAIH,IAAa,cAAc,GAA3B,MAAa,cAAc;
|
|
1
|
+
{"version":3,"file":"MongooseModule.js","sourceRoot":"","sources":["../../src/MongooseModule.ts"],"names":[],"mappings":";AAAA,OAAO,EAAC,aAAa,EAAS,MAAM,UAAU,CAAC;AAC/C,OAAO,EAAC,MAAM,EAAY,MAAM,UAAU,CAAC;AAC3C,OAAO,EAAC,oBAAoB,EAAC,MAAM,gCAAgC,CAAC;AACpE,OAAO,EAAC,eAAe,EAAC,MAAM,4BAA4B,CAAC;AAE3D;;GAEG;AAIH,IAAa,cAAc,GAA3B,MAAa,cAAc;IACL;IAA2D;IAA/E,YAAoB,eAAgC,EAA2B,QAAuB;QAAlF,oBAAe,GAAf,eAAe,CAAiB;QAA2B,aAAQ,GAAR,QAAQ,CAAe;QACpG,6EAA6E;QAC7E,MAAM,KAAK,GAAG,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAM,OAAO,CAAC,CAAC;QAE9C,uBAAuB;QACvB,IAAI,KAAK,EAAE,QAAQ,EAAE;YACnB,KAAK,CAAC,UAAU,GAAG,IAAI,CAAC,eAAe,CAAC,GAAG,EAAE,CAAC;SAC/C;IACH,CAAC;IAED,OAAO,KAAyB,CAAC;IAEjC,UAAU;QACR,OAAO,IAAI,CAAC,eAAe,CAAC,gBAAgB,EAAE,CAAC;IACjD,CAAC;CACF,CAAA;AAhBY,cAAc;IAH1B,MAAM,CAAC;QACN,OAAO,EAAE,CAAC,oBAAoB,CAAC;KAChC,CAAC;IAEuD,WAAA,aAAa,EAAE,CAAA;qCAAjC,eAAe;GADzC,cAAc,CAgB1B;SAhBY,cAAc","sourcesContent":["import {Configuration, OnInit} from \"@tsed/di\";\nimport {Module, OnDestroy} from \"@tsed/di\";\nimport {MONGOOSE_CONNECTIONS} from \"./services/MongooseConnections\";\nimport {MongooseService} from \"./services/MongooseService\";\n\n/**\n * @ignore\n */\n@Module({\n imports: [MONGOOSE_CONNECTIONS]\n})\nexport class MongooseModule implements OnDestroy, OnInit {\n constructor(private mongooseService: MongooseService, @Configuration() private settings: Configuration) {\n // auto configure the cache manager when mongoose is used with @tsed/mongoose\n const cache = this.settings.get<any>(\"cache\");\n\n // istanbul ignore next\n if (cache?.mongoose) {\n cache.connection = this.mongooseService.get();\n }\n }\n\n $onInit(): void | Promise<any> {}\n\n $onDestroy(): Promise<any> | void {\n return this.mongooseService.closeConnections();\n }\n}\n"]}
|
|
@@ -8,7 +8,7 @@ function isRef(value) {
|
|
|
8
8
|
return (value && value._bsontype) || isString(value);
|
|
9
9
|
}
|
|
10
10
|
function getType(refPath, ctx) {
|
|
11
|
-
return (
|
|
11
|
+
return (ctx?.self[refPath] && MongooseModels.get(ctx.self[refPath])) || Object;
|
|
12
12
|
}
|
|
13
13
|
/**
|
|
14
14
|
* Define a property as mongoose reference to other Model (decorated with @Model).
|
|
@@ -43,7 +43,7 @@ function getType(refPath, ctx) {
|
|
|
43
43
|
* @property
|
|
44
44
|
*/
|
|
45
45
|
export function DynamicRef(refPath, ...types) {
|
|
46
|
-
return useDecorators(Property(Object), Example("5ce7ad3028890bd71749d477"), Description("
|
|
46
|
+
return useDecorators(Property(Object), Example("5ce7ad3028890bd71749d477"), Description("A reference ObjectID"), StoreMerge(MONGOOSE_SCHEMA, {
|
|
47
47
|
type: MongooseSchema.Types.ObjectId,
|
|
48
48
|
refPath
|
|
49
49
|
}), OnDeserialize((value, ctx) => {
|
|
@@ -56,6 +56,6 @@ export function DynamicRef(refPath, ...types) {
|
|
|
56
56
|
return value.toString();
|
|
57
57
|
}
|
|
58
58
|
return serialize(value, { ...ctx, type: getType(refPath, ctx) });
|
|
59
|
-
}), OneOf(string().example("5ce7ad3028890bd71749d477").description("
|
|
59
|
+
}), OneOf(string().example("5ce7ad3028890bd71749d477").description("A reference ObjectID"), ...types));
|
|
60
60
|
}
|
|
61
61
|
//# sourceMappingURL=dynamicRef.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dynamicRef.js","sourceRoot":"","sources":["../../../src/decorators/dynamicRef.ts"],"names":[],"mappings":"AAAA,OAAO,EAAqB,QAAQ,EAAE,UAAU,EAAQ,aAAa,EAAC,MAAM,YAAY,CAAC;AACzF,OAAO,EAAC,WAAW,EAAE,OAAO,EAAmB,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAC,MAAM,cAAc,CAAC;AAC5F,OAAO,EAAC,MAAM,IAAI,cAAc,EAAC,MAAM,UAAU,CAAC;AAClD,OAAO,EAAC,eAAe,EAAC,MAAM,wBAAwB,CAAC;AACvD,OAAO,EAAC,WAAW,EAAE,aAAa,EAAE,WAAW,EAAE,SAAS,EAAC,MAAM,mBAAmB,CAAC;AACrF,OAAO,EAAC,cAAc,EAAC,MAAM,8BAA8B,CAAC;AAE5D,SAAS,KAAK,CAAC,KAA+B;IAC5C,OAAO,CAAC,KAAK,IAAI,KAAK,CAAC,SAAS,CAAC,IAAI,QAAQ,CAAC,KAAK,CAAC,CAAC;AACvD,CAAC;AAED,SAAS,OAAO,CAAC,OAAe,EAAE,GAAoB;IACpD,OAAO,CAAC,
|
|
1
|
+
{"version":3,"file":"dynamicRef.js","sourceRoot":"","sources":["../../../src/decorators/dynamicRef.ts"],"names":[],"mappings":"AAAA,OAAO,EAAqB,QAAQ,EAAE,UAAU,EAAQ,aAAa,EAAC,MAAM,YAAY,CAAC;AACzF,OAAO,EAAC,WAAW,EAAE,OAAO,EAAmB,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAC,MAAM,cAAc,CAAC;AAC5F,OAAO,EAAC,MAAM,IAAI,cAAc,EAAC,MAAM,UAAU,CAAC;AAClD,OAAO,EAAC,eAAe,EAAC,MAAM,wBAAwB,CAAC;AACvD,OAAO,EAAC,WAAW,EAAE,aAAa,EAAE,WAAW,EAAE,SAAS,EAAC,MAAM,mBAAmB,CAAC;AACrF,OAAO,EAAC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,CAAC,EAAC,CAAC,CAAC;IACjE,CAAC,CAAC,EACF,KAAK,CAAC,MAAM,EAAE,CAAC,OAAO,CAAC,0BAA0B,CAAC,CAAC,WAAW,CAAC,sBAAsB,CAAC,EAAE,GAAG,KAAK,CAAC,CAC7E,CAAC;AACzB,CAAC","sourcesContent":["import {classOf, isArrowFn, isString, StoreMerge, Type, useDecorators} from \"@tsed/core\";\nimport {Description, Example, JsonHookContext, OneOf, Property, string} from \"@tsed/schema\";\nimport {Schema as MongooseSchema} from \"mongoose\";\nimport {MONGOOSE_SCHEMA} from \"../constants/constants\";\nimport {deserialize, OnDeserialize, OnSerialize, serialize} from \"@tsed/json-mapper\";\nimport {MongooseModels} from \"../registries/MongooseModels\";\n\nfunction isRef(value: undefined | string | any) {\n return (value && value._bsontype) || isString(value);\n}\n\nfunction getType(refPath: string, ctx: JsonHookContext) {\n return (ctx?.self[refPath] && MongooseModels.get(ctx.self[refPath] as string)) || Object;\n}\n\n/**\n * Define a property as mongoose reference to other Model (decorated with @Model).\n *\n * ### Example\n *\n * ```typescript\n * @Model()\n * class FooModel {\n *\n * @DynamicRef('type')\n * field: DynamicRef<OtherFooModel | OtherModel>\n *\n * @Enum(['OtherFooModel', 'OtherModel'])\n * type: string\n * }\n *\n * @Model()\n * class OtherFooModel {\n * }\n *\n * @Model()\n * class OtherModel {\n * }\n * ```\n *\n * @param refPath {String} the path to apply the correct model\n * @param types {Type} the classes to generate the correct json schema\n * @returns {Function}\n * @decorator\n * @mongoose\n * @property\n */\nexport function DynamicRef(refPath: string, ...types: Type<any>[]): PropertyDecorator {\n return useDecorators(\n Property(Object),\n Example(\"5ce7ad3028890bd71749d477\"),\n Description(\"A reference ObjectID\"),\n StoreMerge(MONGOOSE_SCHEMA, {\n type: MongooseSchema.Types.ObjectId,\n refPath\n }),\n OnDeserialize((value, ctx) => {\n if (isRef(value)) {\n return value.toString();\n }\n\n return deserialize(value, {...ctx, type: getType(refPath, ctx)});\n }),\n OnSerialize((value: any, ctx) => {\n if (isRef(value)) {\n return value.toString();\n }\n\n return serialize(value, {...ctx, type: getType(refPath, ctx)});\n }),\n OneOf(string().example(\"5ce7ad3028890bd71749d477\").description(\"A reference ObjectID\"), ...types)\n ) as PropertyDecorator;\n}\n\nexport type DynamicRef<T> = T | string;\n"]}
|
|
@@ -17,6 +17,6 @@ import { Description, Example, Name, Pattern } from "@tsed/schema";
|
|
|
17
17
|
* @schema
|
|
18
18
|
*/
|
|
19
19
|
export function ObjectID(name) {
|
|
20
|
-
return useDecorators(name && Name(name), Pattern(/^[0-9a-fA-F]{24}$/), Description("
|
|
20
|
+
return useDecorators(name && Name(name), Pattern(/^[0-9a-fA-F]{24}$/), Description("An ObjectID"), Example("5ce7ad3028890bd71749d477"));
|
|
21
21
|
}
|
|
22
22
|
//# sourceMappingURL=objectID.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"objectID.js","sourceRoot":"","sources":["../../../src/decorators/objectID.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,aAAa,EAAC,MAAM,YAAY,CAAC;AACzC,OAAO,EAAC,WAAW,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAC,MAAM,cAAc,CAAC;AAGjE;;;;;;;;;;;;;;;GAeG;AACH,MAAM,UAAU,QAAQ,CAAC,IAAa;IACpC,OAAO,aAAa,
|
|
1
|
+
{"version":3,"file":"objectID.js","sourceRoot":"","sources":["../../../src/decorators/objectID.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,aAAa,EAAC,MAAM,YAAY,CAAC;AACzC,OAAO,EAAC,WAAW,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAC,MAAM,cAAc,CAAC;AAGjE;;;;;;;;;;;;;;;GAeG;AACH,MAAM,UAAU,QAAQ,CAAC,IAAa;IACpC,OAAO,aAAa,CAAC,IAAI,IAAI,IAAI,CAAC,IAAI,CAAC,EAAE,OAAO,CAAC,mBAAmB,CAAC,EAAE,WAAW,CAAC,aAAa,CAAC,EAAE,OAAO,CAAC,0BAA0B,CAAC,CAAC,CAAC;AAC1I,CAAC","sourcesContent":["import {useDecorators} from \"@tsed/core\";\nimport {Description, Example, Name, Pattern} from \"@tsed/schema\";\nimport {Types} from \"mongoose\";\n\n/**\n * Tell Mongoose whether to define an ObjectId property.\n * ### Example\n *\n * ```typescript\n * @Model()\n * export class EventModel {\n * @ObjectId('id')\n * _id: string;\n * }\n * ```\n * @param name\n * @decorator\n * @mongoose\n * @schema\n */\nexport function ObjectID(name?: string) {\n return useDecorators(name && Name(name), Pattern(/^[0-9a-fA-F]{24}$/), Description(\"An ObjectID\"), Example(\"5ce7ad3028890bd71749d477\"));\n}\n\nexport type ObjectID = Types.ObjectId;\n"]}
|
|
@@ -50,6 +50,9 @@ function PopulateGroups(populatedGroups) {
|
|
|
50
50
|
* @property
|
|
51
51
|
*/
|
|
52
52
|
export function Ref(model, options = MongooseSchemaTypes.OBJECT_ID) {
|
|
53
|
+
if (!model) {
|
|
54
|
+
throw new Error("A model is required on `@Ref(model)` decorator. Please give a model or wrap it inside an arrow function if you have a circular reference.");
|
|
55
|
+
}
|
|
53
56
|
const getType = () => (isString(model) ? MongooseModels.get(model) : isArrowFn(model) ? model() : model);
|
|
54
57
|
const populatedGroups = (isObject(options) && options.populatedGroups) || [];
|
|
55
58
|
return useDecorators(Property(Object), StoreMerge(MONGOOSE_SCHEMA, {
|
|
@@ -66,6 +69,6 @@ export function Ref(model, options = MongooseSchemaTypes.OBJECT_ID) {
|
|
|
66
69
|
}
|
|
67
70
|
const type = getType();
|
|
68
71
|
return serialize(value, { ...ctx, type });
|
|
69
|
-
}), OneOf(string().example("5ce7ad3028890bd71749d477").description("
|
|
72
|
+
}), OneOf(string().example("5ce7ad3028890bd71749d477").description("A reference ObjectID"), lazyRef(getType)), populatedGroups.length && PopulateGroups(populatedGroups));
|
|
70
73
|
}
|
|
71
74
|
//# sourceMappingURL=ref.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"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W,CAAC,CAAC,KAAU,EAAE,GAAG,EAAE,EAAE;QAC9B,IAAI,KAAK,CAAC,KAAK,CAAC,EAAE;YAChB,OAAO,KAAK,CAAC,QAAQ,EAAE,CAAC;SACzB;QACD,MAAM,IAAI,GAAG,OAAO,EAAE,CAAC;QAEvB,OAAO,SAAS,CAAC,KAAK,EAAE,EAAC,GAAG,GAAG,EAAE,IAAI,EAAC,CAAC,CAAC;IAC1C,CAAC,CAAC,EACF,KAAK,CAAC,MAAM,EAAE,CAAC,OAAO,CAAC,0BAA0B,CAAC,CAAC,WAAW,CAAC,sBAAsB,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC,EACzG,eAAe,CAAC,MAAM,IAAI,cAAc,CAAC,eAAe,CAAC,CACrC,CAAC;AACzB,CAAC","sourcesContent":["import {isArrowFn, isObject, isString, StoreMerge, Type, useDecorators} from \"@tsed/core\";\nimport {OnDeserialize, OnSerialize, serialize} from \"@tsed/json-mapper\";\nimport {ForwardGroups, JsonEntityFn, lazyRef, matchGroups, OneOf, Property, string} from \"@tsed/schema\";\nimport {Schema as MongooseSchema} from \"mongoose\";\nimport {MONGOOSE_SCHEMA} from \"../constants/constants\";\nimport {MongooseSchemaTypes} from \"../interfaces/MongooseSchemaTypes\";\nimport {MongooseModels} from \"../registries/MongooseModels\";\n\ninterface RefOptions {\n type?: MongooseSchemaTypes;\n populatedGroups?: string[];\n}\n\nfunction isRef(value: undefined | string | any) {\n return (value && value._bsontype) || isString(value);\n}\n\nfunction PopulateGroups(populatedGroups: string[]) {\n return useDecorators(\n ForwardGroups(true),\n JsonEntityFn((store) => {\n store.schema.$hooks.on(\"oneOf\", (obj: any[], givenGroups: string[]) => {\n if (matchGroups(populatedGroups, givenGroups)) {\n return obj.filter((x) => x.type === \"string\"); // keep the object id;\n } else {\n return obj.filter((x) => x.type !== \"string\"); // keep the ref definition\n }\n });\n })\n );\n}\n\n/**\n * Define a property as mongoose reference to other Model (decorated with @Model).\n *\n * ### Example\n *\n * ```typescript\n *\n * @Model()\n * class FooModel {\n *\n * @Ref(Foo2Model)\n * field: Ref<Foo2Model>\n *\n * @Ref(Foo2Model)\n * list: Ref<Foo2Model>[]\n * }\n *\n * @Model()\n * class Foo2Model {\n * }\n * ```\n *\n * @param model\n * @param options\n * @returns {Function}\n * @decorator\n * @mongoose\n * @property\n */\nexport function Ref(\n model: string | (() => Type) | any,\n options: RefOptions | MongooseSchemaTypes = MongooseSchemaTypes.OBJECT_ID\n): PropertyDecorator {\n if (!model) {\n throw new Error(\n \"A model is required on `@Ref(model)` decorator. Please give a model or wrap it inside an arrow function if you have a circular reference.\"\n );\n }\n\n const getType = () => (isString(model) ? MongooseModels.get(model) : isArrowFn(model) ? model() : model);\n const populatedGroups = (isObject(options) && options.populatedGroups) || [];\n\n return useDecorators(\n Property(Object),\n StoreMerge(MONGOOSE_SCHEMA, {\n type: MongooseSchema.Types[isObject(options) ? options.type || MongooseSchemaTypes.OBJECT_ID : options],\n ref: model\n }),\n OnDeserialize((value) => {\n if (isRef(value)) {\n return value.toString();\n }\n\n return value;\n }),\n OnSerialize((value: any, ctx) => {\n if (isRef(value)) {\n return value.toString();\n }\n const type = getType();\n\n return serialize(value, {...ctx, type});\n }),\n OneOf(string().example(\"5ce7ad3028890bd71749d477\").description(\"A reference ObjectID\"), lazyRef(getType)),\n populatedGroups.length && PopulateGroups(populatedGroups)\n ) as PropertyDecorator;\n}\n\nexport type Ref<T> = T | string;\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MongooseSchemaOptions.js","sourceRoot":"","sources":["../../../src/interfaces/MongooseSchemaOptions.ts"],"names":[],"mappings":"","sourcesContent":["import {
|
|
1
|
+
{"version":3,"file":"MongooseSchemaOptions.js","sourceRoot":"","sources":["../../../src/interfaces/MongooseSchemaOptions.ts"],"names":[],"mappings":"","sourcesContent":["import {Schema, SchemaOptions} from \"mongoose\";\nimport {MongooseDocument} from \"./MongooseDocument\";\n\nexport type MongooseNextCB = (err?: Error) => void;\n\nexport interface MongooseHookOptions {\n document?: boolean;\n query?: boolean;\n parallel?: boolean;\n}\n\nexport type MongoosePreHookCB<T = any> =\n | ((doc: T | MongooseDocument<T>, next: MongooseNextCB) => void)\n | ((doc: T | MongooseDocument<T>) => Promise<void> | void);\n\nexport type MongoosePostHookCB<T = any> =\n | ((doc: T | MongooseDocument<T>, error: Error, next: MongooseNextCB) => void)\n | ((doc: T | MongooseDocument<T>, error: Error) => Promise<void> | void)\n | ((doc: T | MongooseDocument<T>, next: MongooseNextCB) => void)\n | ((doc: T | MongooseDocument<T>) => Promise<void> | void);\n\nexport interface MongoosePreHook<T = any> {\n method: string | RegExp;\n fn: MongoosePreHookCB<T>;\n options?: MongooseHookOptions;\n}\n\nexport interface MongoosePostHook<T = any> {\n method: string | RegExp;\n fn: MongoosePostHookCB<T>;\n options?: MongooseHookOptions;\n}\n\nexport interface MongoosePluginOptions {\n plugin: (schema: Schema, options?: any) => void;\n options?: Record<string, unknown>;\n}\n\nexport interface MongooseIndexOptions {\n fields: Record<any, any>;\n options?: Record<string, unknown>;\n}\n\nexport interface MongooseSchemaOptions {\n schemaOptions?: SchemaOptions;\n plugins?: MongoosePluginOptions[];\n indexes?: MongooseIndexOptions[];\n pre?: MongoosePreHook[];\n post?: MongoosePostHook[];\n}\n"]}
|
|
@@ -7,10 +7,9 @@ function asPromise(c) {
|
|
|
7
7
|
return c && c.asPromise ? c.asPromise() : c;
|
|
8
8
|
}
|
|
9
9
|
let MongooseService = class MongooseService {
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
}
|
|
10
|
+
connections = new Map();
|
|
11
|
+
defaultConnection = "default";
|
|
12
|
+
logger;
|
|
14
13
|
/**
|
|
15
14
|
*
|
|
16
15
|
* @returns {Promise<"mongoose".Connection>}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MongooseService.js","sourceRoot":"","sources":["../../../src/services/MongooseService.ts"],"names":[],"mappings":";AAAA,OAA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AAe,CA4D3B;SA5DY,eAAe","sourcesContent":["import {Inject, Injectable} from \"@tsed/di\";\nimport {Logger} from \"@tsed/logger\";\nimport Mongoose from \"mongoose\";\nimport {ConnectOptions} from \"mongoose\";\n\n// istanbul ignore next\nfunction asPromise(c: any) {\n return c && c.asPromise ? c.asPromise() : c;\n}\n\n@Injectable()\nexport class MongooseService {\n readonly connections: Map<string, Mongoose.Connection> = new Map();\n private defaultConnection: string = \"default\";\n\n @Inject()\n logger: Logger;\n\n /**\n *\n * @returns {Promise<\"mongoose\".Connection>}\n */\n async connect(id: string, url: string, connectionOptions: ConnectOptions, isDefault = false): Promise<any> {\n if (this.has(id)) {\n return await this.get(id)!;\n }\n\n this.logger.info(`Connect to mongo database: ${id}`);\n this.logger.debug(`Url: ${url}`);\n this.logger.debug(`options: ${JSON.stringify(connectionOptions)}`);\n\n try {\n const connection = await asPromise(Mongoose.createConnection(url, connectionOptions));\n this.connections.set(id, connection);\n\n if (id === \"default\" || isDefault) {\n this.defaultConnection = id;\n }\n\n return connection;\n } catch (er) {\n /* istanbul ignore next */\n this.logger.error(er);\n /* istanbul ignore next */\n process.exit();\n }\n }\n\n /**\n *\n * @returns {\"mongoose\".Connection}\n */\n get(id?: string): Mongoose.Connection | undefined {\n return this.connections.get(id || this.defaultConnection);\n }\n\n /**\n *\n * @param {string} id\n * @returns {boolean}\n */\n has(id?: string): boolean {\n return this.connections.has(id || this.defaultConnection);\n }\n\n async closeConnections() {\n for (const [id, connection] of this.connections.entries()) {\n await connection.close();\n this.connections.delete(id);\n }\n }\n}\n"]}
|
|
@@ -31,14 +31,14 @@ function hasVersionField(schema, versionKey) {
|
|
|
31
31
|
return versionKey in schema.paths;
|
|
32
32
|
}
|
|
33
33
|
export function createSchema(target, options = {}) {
|
|
34
|
-
var _a;
|
|
35
34
|
const schemaOptionsFromStore = Store.from(target).get(MONGOOSE_SCHEMA_OPTIONS) || {};
|
|
36
35
|
options.schemaOptions = { ...options.schemaOptions, ...schemaOptionsFromStore };
|
|
37
36
|
const schema = setUpSchema(buildMongooseSchema(target), options.schemaOptions);
|
|
38
37
|
schemaOptions(target, options);
|
|
39
|
-
const outputVersionKey = hasVersionField(schema,
|
|
38
|
+
const outputVersionKey = hasVersionField(schema, options.schemaOptions?.versionKey);
|
|
40
39
|
schema.methods.toClass = function toClass() {
|
|
41
40
|
return deserialize(this.toObject({
|
|
41
|
+
virtuals: true,
|
|
42
42
|
versionKey: outputVersionKey,
|
|
43
43
|
flattenMaps: true
|
|
44
44
|
}), {
|
|
@@ -84,7 +84,7 @@ export function buildMongooseSchema(target) {
|
|
|
84
84
|
}
|
|
85
85
|
// Keeping the Mongoose Schema separate so it can overwrite everything once schema has been built.
|
|
86
86
|
const schemaTypeOptions = propertyMetadata.store.get(MONGOOSE_SCHEMA) || {};
|
|
87
|
-
if (schemaTypeOptions.schemaIgnore) {
|
|
87
|
+
if (schemaTypeOptions.schemaIgnore || propertyMetadata.schema.isReadOnly) {
|
|
88
88
|
return;
|
|
89
89
|
}
|
|
90
90
|
if (schemaTypeOptions.ref) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createSchema.js","sourceRoot":"","sources":["../../../src/utils/createSchema.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,WAAW,EAAE,MAAM,EAAE,KAAK,EAAO,MAAM,YAAY,CAAC;AAC5D,OAAO,EAAC,WAAW,EAAE,SAAS,EAAC,MAAM,mBAAmB,CAAC;AACzD,OAAO,EAAC,aAAa,EAAkB,MAAM,cAAc,CAAC;AAC5D,OAAO,EAAC,UAAU,EAAC,MAAM,aAAa,CAAC;AACvC,OAAO,QAAsE,MAAM,UAAU,CAAC;AAC9F,OAAO,EAAC,eAAe,EAAE,uBAAuB,EAAC,MAAM,wBAAwB,CAAC;AAGhF,OAAO,EAAC,cAAc,EAAC,MAAM,kBAAkB,CAAC;AAChD,OAAO,EAAC,aAAa,EAAC,MAAM,iBAAiB,CAAC;AAE9C,MAAM,sBAAsB,GAAG,C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C,IAAI,UAAU,CAAC,cAAc,KAAK,GAAG,EAAE;YACrC,MAAM,IAAI,KAAK,CAAC,4BAA4B,MAAM,CAAC,UAAU,CAAC,cAAc,CAAC,oBAAoB,CAAC,CAAC;SACpG;QAED,OAAO,EAAC,IAAI,EAAE,GAAG,EAAE,EAAE,EAAE,iBAAiB,EAAoC,CAAC;KAC9E;IAED,OAAO,iBAAiB,CAAC;AAC3B,CAAC","sourcesContent":["import {cleanObject, nameOf, Store, Type} from \"@tsed/core\";\nimport {deserialize, serialize} from \"@tsed/json-mapper\";\nimport {getProperties, JsonEntityStore} from \"@tsed/schema\";\nimport {pascalCase} from \"change-case\";\nimport mongoose, {Schema, SchemaDefinition, SchemaOptions, SchemaTypeOptions} from \"mongoose\";\nimport {MONGOOSE_SCHEMA, MONGOOSE_SCHEMA_OPTIONS} from \"../constants/constants\";\nimport {MongooseSchemaOptions} from \"../interfaces/MongooseSchemaOptions\";\nimport {MongooseVirtualRefOptions} from \"../interfaces/MongooseVirtualRefOptions\";\nimport {resolveRefType} from \"./resolveRefType\";\nimport {schemaOptions} from \"./schemaOptions\";\n\nconst MONGOOSE_RESERVED_KEYS = [\"_id\"];\n\nexport interface MongooseSchemaMetadata {\n schema: SchemaDefinition;\n virtuals: Map<string, MongooseVirtualRefOptions>;\n}\n\n/**\n * @ignore\n */\nfunction setUpSchema({schema, virtuals}: MongooseSchemaMetadata, options?: SchemaOptions) {\n const mongooseSchema = new mongoose.Schema(schema, options);\n\n for (const [key, options] of virtuals.entries()) {\n mongooseSchema.virtual(key, options);\n }\n\n return mongooseSchema;\n}\n\n/**\n * @ignore\n */\nfunction isVirtualRef(target: Partial<MongooseVirtualRefOptions>): target is MongooseVirtualRefOptions {\n return !!(target.ref && target.localField && target.foreignField);\n}\n\nfunction hasVersionField(schema: mongoose.Schema, versionKey?: string | boolean) {\n // Check if versioning was disabled explicitly\n if (!versionKey) return false;\n\n // Check for alternative version field in schema\n return (versionKey as string) in schema.paths;\n}\n\nexport function createSchema(target: Type<any>, options: MongooseSchemaOptions = {}): mongoose.Schema {\n const schemaOptionsFromStore = Store.from(target).get(MONGOOSE_SCHEMA_OPTIONS) || {};\n options.schemaOptions = {...options.schemaOptions, ...schemaOptionsFromStore};\n\n const schema = setUpSchema(buildMongooseSchema(target), options.schemaOptions);\n\n schemaOptions(target, options);\n\n const outputVersionKey = hasVersionField(schema, options.schemaOptions?.versionKey);\n\n schema.methods.toClass = function toClass() {\n return deserialize(\n this.toObject({\n versionKey: outputVersionKey,\n flattenMaps: true\n }),\n {\n type: target,\n useAlias: false,\n additionalProperties: true,\n groups: false\n }\n );\n };\n\n schema.methods.toJSON = function toJSON(options?: any) {\n return serialize((this as any).toClass(), options);\n };\n\n schema.loadClass(target);\n\n Store.from(target).set(MONGOOSE_SCHEMA, schema);\n\n return schema;\n}\n\n/**\n * Get a schema already created. If the schema doesn't exists in registry, it'll be created.\n * @param target\n * @param options\n */\nexport function getSchema(target: Type<any>, options: MongooseSchemaOptions = {}): Schema {\n const store = Store.from(target);\n\n if (!store.has(MONGOOSE_SCHEMA)) {\n createSchema(target, options);\n }\n\n return store.get(MONGOOSE_SCHEMA);\n}\n\nexport function getSchemaToken(target: Type<any>, options?: any) {\n const collectionName = options.name || nameOf(target);\n const token = Symbol.for(pascalCase(`${collectionName}Schema`));\n\n return {token, collectionName};\n}\n\n/**\n * @ignore\n */\nexport function buildMongooseSchema(target: any): MongooseSchemaMetadata {\n const properties = getProperties(target, {withIgnoredProps: true, mongoose: true, groups: false});\n const schema: MongooseSchemaMetadata = {schema: {}, virtuals: new Map()};\n\n properties.forEach((propertyMetadata, key) => {\n if (MONGOOSE_RESERVED_KEYS.includes(key as string)) {\n return;\n }\n\n // Keeping the Mongoose Schema separate so it can overwrite everything once schema has been built.\n const schemaTypeOptions: any = propertyMetadata.store.get(MONGOOSE_SCHEMA) || {};\n\n if (schemaTypeOptions.schemaIgnore) {\n return;\n }\n\n if (schemaTypeOptions.ref) {\n schemaTypeOptions.ref = resolveRefType(schemaTypeOptions.ref as any);\n }\n\n if (isVirtualRef(schemaTypeOptions)) {\n schema.virtuals.set(key as string, schemaTypeOptions);\n\n return;\n }\n\n schema.schema[key as string] = createSchemaTypeOptions(propertyMetadata);\n });\n\n return schema;\n}\n\n/**\n * @ignore\n */\nexport function createSchemaTypeOptions<T = any>(propEntity: JsonEntityStore): SchemaTypeOptions<T> | SchemaTypeOptions<T>[] {\n const key = propEntity.propertyKey;\n const rawMongooseSchema = propEntity.store.get(MONGOOSE_SCHEMA) || {};\n\n let schemaTypeOptions: SchemaTypeOptions<T> = {\n required: propEntity.required\n ? function () {\n return propEntity.isRequired(this[key]);\n }\n : false\n };\n\n if (!propEntity.isClass) {\n const jsonSchema = propEntity.itemSchema.toJSON();\n const {minimum: min, maximum: max, minLength: minlength, maxLength: maxlength} = jsonSchema;\n\n let match: string | RegExp = jsonSchema.pattern;\n if (match) {\n match = new RegExp(match);\n }\n\n schemaTypeOptions = {\n ...schemaTypeOptions,\n type: propEntity.type,\n match: match as RegExp,\n min,\n max,\n minlength,\n maxlength,\n enum: jsonSchema[\"enum\"],\n default: jsonSchema[\"default\"]\n };\n } else if (!rawMongooseSchema.ref) {\n // References are handled by the final merge\n schemaTypeOptions = {...schemaTypeOptions, type: getSchema(propEntity.type) as any};\n }\n\n schemaTypeOptions = cleanObject({...schemaTypeOptions, ...rawMongooseSchema});\n\n if (propEntity.isCollection) {\n if (propEntity.isArray) {\n return [schemaTypeOptions];\n }\n // Can be a Map or a Set;\n // Mongoose implements only Map;\n if (propEntity.collectionType !== Map) {\n throw new Error(`Invalid collection type. ${nameOf(propEntity.collectionType)} is not supported.`);\n }\n\n return {type: Map, of: schemaTypeOptions} as unknown as SchemaTypeOptions<T>;\n }\n\n return schemaTypeOptions;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"createSchema.js","sourceRoot":"","sources":["../../../src/utils/createSchema.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,WAAW,EAAE,MAAM,EAAE,KAA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;YACxB,OAAO,EAAE,UAAU,CAAC,SAAS,CAAC;SAC/B,CAAC;KACH;SAAM,IAAI,CAAC,iBAAiB,CAAC,GAAG,EAAE;QACjC,4CAA4C;QAC5C,iBAAiB,GAAG,EAAC,GAAG,iBAAiB,EAAE,IAAI,EAAE,SAAS,CAAC,UAAU,CAAC,IAAI,CAAQ,EAAC,CAAC;KACrF;IAED,iBAAiB,GAAG,WAAW,CAAC,EAAC,GAAG,iBAAiB,EAAE,GAAG,iBAAiB,EAAC,CAAC,CAAC;IAE9E,IAAI,UAAU,CAAC,YAAY,EAAE;QAC3B,IAAI,UAAU,CAAC,OAAO,EAAE;YACtB,OAAO,CAAC,iBAAiB,CAAC,CAAC;SAC5B;QACD,yBAAyB;QACzB,gCAAgC;QAChC,IAAI,UAAU,CAAC,cAAc,KAAK,GAAG,EAAE;YACrC,MAAM,IAAI,KAAK,CAAC,4BAA4B,MAAM,CAAC,UAAU,CAAC,cAAc,CAAC,oBAAoB,CAAC,CAAC;SACpG;QAED,OAAO,EAAC,IAAI,EAAE,GAAG,EAAE,EAAE,EAAE,iBAAiB,EAAoC,CAAC;KAC9E;IAED,OAAO,iBAAiB,CAAC;AAC3B,CAAC","sourcesContent":["import {cleanObject, nameOf, Store, Type} from \"@tsed/core\";\nimport {deserialize, serialize} from \"@tsed/json-mapper\";\nimport {getProperties, JsonEntityStore} from \"@tsed/schema\";\nimport {pascalCase} from \"change-case\";\nimport mongoose, {Schema, SchemaDefinition, SchemaOptions, SchemaTypeOptions} from \"mongoose\";\nimport {MONGOOSE_SCHEMA, MONGOOSE_SCHEMA_OPTIONS} from \"../constants/constants\";\nimport {MongooseSchemaOptions} from \"../interfaces/MongooseSchemaOptions\";\nimport {MongooseVirtualRefOptions} from \"../interfaces/MongooseVirtualRefOptions\";\nimport {resolveRefType} from \"./resolveRefType\";\nimport {schemaOptions} from \"./schemaOptions\";\n\nconst MONGOOSE_RESERVED_KEYS = [\"_id\"];\n\nexport interface MongooseSchemaMetadata {\n schema: SchemaDefinition;\n virtuals: Map<string, MongooseVirtualRefOptions>;\n}\n\n/**\n * @ignore\n */\nfunction setUpSchema({schema, virtuals}: MongooseSchemaMetadata, options?: SchemaOptions) {\n const mongooseSchema = new mongoose.Schema(schema, options);\n\n for (const [key, options] of virtuals.entries()) {\n mongooseSchema.virtual(key, options);\n }\n\n return mongooseSchema;\n}\n\n/**\n * @ignore\n */\nfunction isVirtualRef(target: Partial<MongooseVirtualRefOptions>): target is MongooseVirtualRefOptions {\n return !!(target.ref && target.localField && target.foreignField);\n}\n\nfunction hasVersionField(schema: mongoose.Schema, versionKey?: string | boolean) {\n // Check if versioning was disabled explicitly\n if (!versionKey) return false;\n\n // Check for alternative version field in schema\n return (versionKey as string) in schema.paths;\n}\n\nexport function createSchema(target: Type<any>, options: MongooseSchemaOptions = {}): mongoose.Schema {\n const schemaOptionsFromStore = Store.from(target).get(MONGOOSE_SCHEMA_OPTIONS) || {};\n options.schemaOptions = {...options.schemaOptions, ...schemaOptionsFromStore};\n\n const schema = setUpSchema(buildMongooseSchema(target), options.schemaOptions);\n\n schemaOptions(target, options);\n\n const outputVersionKey = hasVersionField(schema, options.schemaOptions?.versionKey);\n\n schema.methods.toClass = function toClass() {\n return deserialize(\n this.toObject({\n virtuals: true,\n versionKey: outputVersionKey,\n flattenMaps: true\n }),\n {\n type: target,\n useAlias: false,\n additionalProperties: true,\n groups: false\n }\n );\n };\n\n schema.methods.toJSON = function toJSON(options?: any) {\n return serialize((this as any).toClass(), options);\n };\n\n schema.loadClass(target);\n\n Store.from(target).set(MONGOOSE_SCHEMA, schema);\n\n return schema;\n}\n\n/**\n * Get a schema already created. If the schema doesn't exists in registry, it'll be created.\n * @param target\n * @param options\n */\nexport function getSchema(target: Type<any>, options: MongooseSchemaOptions = {}): Schema {\n const store = Store.from(target);\n\n if (!store.has(MONGOOSE_SCHEMA)) {\n createSchema(target, options);\n }\n\n return store.get(MONGOOSE_SCHEMA);\n}\n\nexport function getSchemaToken(target: Type<any>, options?: any) {\n const collectionName = options.name || nameOf(target);\n const token = Symbol.for(pascalCase(`${collectionName}Schema`));\n\n return {token, collectionName};\n}\n\n/**\n * @ignore\n */\nexport function buildMongooseSchema(target: any): MongooseSchemaMetadata {\n const properties = getProperties(target, {withIgnoredProps: true, mongoose: true, groups: false});\n const schema: MongooseSchemaMetadata = {schema: {}, virtuals: new Map()};\n\n properties.forEach((propertyMetadata, key) => {\n if (MONGOOSE_RESERVED_KEYS.includes(key as string)) {\n return;\n }\n\n // Keeping the Mongoose Schema separate so it can overwrite everything once schema has been built.\n const schemaTypeOptions: any = propertyMetadata.store.get(MONGOOSE_SCHEMA) || {};\n\n if (schemaTypeOptions.schemaIgnore || propertyMetadata.schema.isReadOnly) {\n return;\n }\n\n if (schemaTypeOptions.ref) {\n schemaTypeOptions.ref = resolveRefType(schemaTypeOptions.ref as any);\n }\n\n if (isVirtualRef(schemaTypeOptions)) {\n schema.virtuals.set(key as string, schemaTypeOptions);\n\n return;\n }\n\n schema.schema[key as string] = createSchemaTypeOptions(propertyMetadata);\n });\n\n return schema;\n}\n\n/**\n * @ignore\n */\nexport function createSchemaTypeOptions<T = any>(propEntity: JsonEntityStore): SchemaTypeOptions<T> | SchemaTypeOptions<T>[] {\n const key = propEntity.propertyKey;\n const rawMongooseSchema = propEntity.store.get(MONGOOSE_SCHEMA) || {};\n\n let schemaTypeOptions: SchemaTypeOptions<T> = {\n required: propEntity.required\n ? function () {\n return propEntity.isRequired(this[key]);\n }\n : false\n };\n\n if (!propEntity.isClass) {\n const jsonSchema = propEntity.itemSchema.toJSON();\n const {minimum: min, maximum: max, minLength: minlength, maxLength: maxlength} = jsonSchema;\n\n let match: string | RegExp = jsonSchema.pattern;\n if (match) {\n match = new RegExp(match);\n }\n\n schemaTypeOptions = {\n ...schemaTypeOptions,\n type: propEntity.type,\n match: match as RegExp,\n min,\n max,\n minlength,\n maxlength,\n enum: jsonSchema[\"enum\"],\n default: jsonSchema[\"default\"]\n };\n } else if (!rawMongooseSchema.ref) {\n // References are handled by the final merge\n schemaTypeOptions = {...schemaTypeOptions, type: getSchema(propEntity.type) as any};\n }\n\n schemaTypeOptions = cleanObject({...schemaTypeOptions, ...rawMongooseSchema});\n\n if (propEntity.isCollection) {\n if (propEntity.isArray) {\n return [schemaTypeOptions];\n }\n // Can be a Map or a Set;\n // Mongoose implements only Map;\n if (propEntity.collectionType !== Map) {\n throw new Error(`Invalid collection type. ${nameOf(propEntity.collectionType)} is not supported.`);\n }\n\n return {type: Map, of: schemaTypeOptions} as unknown as SchemaTypeOptions<T>;\n }\n\n return schemaTypeOptions;\n}\n"]}
|
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Schema, SchemaOptions } from "mongoose";
|
|
2
2
|
import { MongooseDocument } from "./MongooseDocument";
|
|
3
|
-
export declare type MongooseNextCB = (err?:
|
|
3
|
+
export declare type MongooseNextCB = (err?: Error) => void;
|
|
4
4
|
export interface MongooseHookOptions {
|
|
5
5
|
document?: boolean;
|
|
6
6
|
query?: boolean;
|
|
7
7
|
parallel?: boolean;
|
|
8
8
|
}
|
|
9
9
|
export declare type MongoosePreHookCB<T = any> = ((doc: T | MongooseDocument<T>, next: MongooseNextCB) => void) | ((doc: T | MongooseDocument<T>) => Promise<void> | void);
|
|
10
|
-
export declare type MongoosePostHookCB<T = any> = ((doc: T | MongooseDocument<T>, error:
|
|
10
|
+
export declare type MongoosePostHookCB<T = any> = ((doc: T | MongooseDocument<T>, error: Error, next: MongooseNextCB) => void) | ((doc: T | MongooseDocument<T>, error: Error) => Promise<void> | void) | ((doc: T | MongooseDocument<T>, next: MongooseNextCB) => void) | ((doc: T | MongooseDocument<T>) => Promise<void> | void);
|
|
11
11
|
export interface MongoosePreHook<T = any> {
|
|
12
12
|
method: string | RegExp;
|
|
13
13
|
fn: MongoosePreHookCB<T>;
|
|
@@ -16,4 +16,4 @@ export declare function getModelToken(target: Type<any>, options: any): {
|
|
|
16
16
|
* @param discriminatorValue
|
|
17
17
|
* @returns {Model<T extends Document>}
|
|
18
18
|
*/
|
|
19
|
-
export declare function createModel<T>(target: any, schema: mongoose.Schema, name?: string, collection?: string, overwriteModels?: boolean, connection?: Connection, discriminatorValue?: string):
|
|
19
|
+
export declare function createModel<T>(target: any, schema: mongoose.Schema, name?: string, collection?: string, overwriteModels?: boolean, connection?: Connection, discriminatorValue?: string): unknown;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tsed/mongoose",
|
|
3
|
-
"version": "7.0.0-
|
|
3
|
+
"version": "7.0.0-rc.1",
|
|
4
4
|
"description": "Mongoose package for Ts.ED framework",
|
|
5
5
|
"private": false,
|
|
6
6
|
"keywords": [
|
|
@@ -29,31 +29,34 @@
|
|
|
29
29
|
},
|
|
30
30
|
"dependencies": {
|
|
31
31
|
"change-case": "4.1.2",
|
|
32
|
-
"tslib": "2.
|
|
32
|
+
"tslib": "2.4.0"
|
|
33
33
|
},
|
|
34
34
|
"devDependencies": {
|
|
35
|
-
"@tsed/ajv": "7.0.0-
|
|
36
|
-
"@tsed/core": "7.0.0-
|
|
37
|
-
"@tsed/di": "7.0.0-
|
|
38
|
-
"@tsed/json-mapper": "7.0.0-
|
|
39
|
-
"@tsed/logger": ">=6.
|
|
40
|
-
"@tsed/schema": "7.0.0-
|
|
41
|
-
"mongoose": "
|
|
35
|
+
"@tsed/ajv": "7.0.0-rc.1",
|
|
36
|
+
"@tsed/core": "7.0.0-rc.1",
|
|
37
|
+
"@tsed/di": "7.0.0-rc.1",
|
|
38
|
+
"@tsed/json-mapper": "7.0.0-rc.1",
|
|
39
|
+
"@tsed/logger": ">=6.2.0",
|
|
40
|
+
"@tsed/schema": "7.0.0-rc.1",
|
|
41
|
+
"mongoose": "6.5.1"
|
|
42
42
|
},
|
|
43
43
|
"peerDependencies": {
|
|
44
|
-
"@tsed/ajv": "^7.0.0-
|
|
45
|
-
"@tsed/core": "^7.0.0-
|
|
46
|
-
"@tsed/di": "^7.0.0-
|
|
47
|
-
"@tsed/json-mapper": "^7.0.0-
|
|
48
|
-
"@tsed/logger": ">=6.
|
|
49
|
-
"@tsed/schema": "^7.0.0-
|
|
44
|
+
"@tsed/ajv": "^7.0.0-rc.1",
|
|
45
|
+
"@tsed/core": "^7.0.0-rc.1",
|
|
46
|
+
"@tsed/di": "^7.0.0-rc.1",
|
|
47
|
+
"@tsed/json-mapper": "^7.0.0-rc.1",
|
|
48
|
+
"@tsed/logger": ">=6.2.0",
|
|
49
|
+
"@tsed/schema": "^7.0.0-rc.1",
|
|
50
50
|
"mongoose": ">=6.0.0"
|
|
51
51
|
},
|
|
52
52
|
"repository": "https://github.com/tsedio/tsed",
|
|
53
53
|
"bugs": {
|
|
54
54
|
"url": "https://github.com/tsedio/tsed/issues"
|
|
55
55
|
},
|
|
56
|
-
"homepage": "https://github.com/tsedio/tsed/tree/
|
|
56
|
+
"homepage": "https://github.com/tsedio/tsed/tree/rc/packages/orm/mongoose",
|
|
57
57
|
"author": "Romain Lenzotti",
|
|
58
|
-
"license": "MIT"
|
|
58
|
+
"license": "MIT",
|
|
59
|
+
"publishConfig": {
|
|
60
|
+
"tag": "rc"
|
|
61
|
+
}
|
|
59
62
|
}
|
package/readme.md
CHANGED
|
@@ -11,7 +11,8 @@
|
|
|
11
11
|
[](https://badge.fury.io/js/%40tsed%2Fcommon)
|
|
12
12
|
[](https://github.com/semantic-release/semantic-release)
|
|
13
13
|
[](https://github.com/prettier/prettier)
|
|
14
|
-
[](https://github.com/sponsors/romakita)
|
|
15
|
+
[](https://opencollective.com/tsed)
|
|
15
16
|
|
|
16
17
|
</div>
|
|
17
18
|
|
|
@@ -363,7 +364,7 @@ Support this project by becoming a sponsor. Your logo will show up here with a l
|
|
|
363
364
|
|
|
364
365
|
The MIT License (MIT)
|
|
365
366
|
|
|
366
|
-
Copyright (c) 2016 -
|
|
367
|
+
Copyright (c) 2016 - 2022 Romain Lenzotti
|
|
367
368
|
|
|
368
369
|
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
369
370
|
|