Skip to content

Commit

Permalink
feat(mongoose): Add VirtualRef decorator
Browse files Browse the repository at this point in the history
  • Loading branch information
alex-dev authored and Romakita committed Jan 19, 2019
1 parent 36edbe1 commit b4ff467
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 1 deletion.
3 changes: 2 additions & 1 deletion packages/mongoose/src/decorators/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,6 @@ export * from "./postHook";
export * from "./preHook";
export * from "./ref";
export * from "./schema";
export * from "./unique";
export * from "./select";
export * from "./unique";
export * from "./virtualRef";
49 changes: 49 additions & 0 deletions packages/mongoose/src/decorators/virtualRef.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import {PropertyMetadata, PropertyRegistry} from "@tsed/common";
import {MONGOOSE_SCHEMA} from "../constants";

export type VirtualRef<T> = T | null;
export type VirtualRefs<T> = T[];

/**
* Define a property as mongoose virtual reference to other Model (decorated with @Model).
*
* Warning: To avoid circular dependencies, do not use the virtual reference model in
* anything except a type declaration. Using the virtual reference model will prevent
* typescript transpiler from stripping away the import statement and cause a circular
* import in node.
*
* ### Example
*
* ```typescript
*
* @Model()
* class FooModel {
*
* @VirtualRef("Foo2Model", "foo")
* field: VirtualRef<Foo2Model>
*
* @VirtualRef("Foo2Model", "foo")
* list: VirtualRefs<Foo2Model>
* }
*
* @Model()
* class Foo2Model {
* @Ref(FooModel)
* foo: Ref<FooModel>;
* }
* ```
*
* @param type
* @returns {Function}
* @decorator
* @mongoose
*/
export function VirtualRef(type: string, foreignField: string) {
return PropertyRegistry.decorate((propertyMetadata: PropertyMetadata) => {
propertyMetadata.store.merge(MONGOOSE_SCHEMA, {
ref: type,
localField: propertyMetadata.name,
foreignField
});
});
}
23 changes: 23 additions & 0 deletions packages/mongoose/test/decorators/virtualRef.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import {Store} from "@tsed/core";
import {descriptorOf} from "@tsed/core";
import {MONGOOSE_SCHEMA} from "../../src/constants";
import {VirtualRef} from "../../src/decorators";
import {expect} from "chai";

describe("@VirtualRef()", () => {
class Test {}
class RefTest {}

before(() => {
VirtualRef("RefTest", "foreign")(Test, "test", descriptorOf(Test, "test"));
this.store = Store.from(Test, "test", descriptorOf(Test, "test"));
});

it("should set metadata", () => {
expect(this.store.get(MONGOOSE_SCHEMA)).to.deep.eq({
ref: "RefTest",
foreignField: "foreign",
localField: "test"
});
});
});

0 comments on commit b4ff467

Please sign in to comment.