Skip to content

Commit

Permalink
fix(mongoose): Ref decorator support string type for circular depende…
Browse files Browse the repository at this point in the history
…ncies

#Closes: 340
  • Loading branch information
Romakita committed Apr 30, 2018
1 parent 89d4c3a commit e6e82fb
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 16 deletions.
10 changes: 6 additions & 4 deletions src/mongoose/decorators/ref.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {PropertyMetadata, PropertyRegistry} from "@tsed/common";
import {Store} from "@tsed/core";
import {Schema} from "mongoose";
import {PropertyMetadata, PropertyRegistry} from "@tsed/common";
import {MONGOOSE_MODEL_NAME, MONGOOSE_SCHEMA} from "../constants";

export type Ref<T> = T | string;
Expand Down Expand Up @@ -32,12 +32,14 @@ export type Ref<T> = T | string;
* @decorator
* @mongoose
*/
export function Ref(type: any) {
export function Ref(type: string | any) {
return PropertyRegistry.decorate((propertyMetadata: PropertyMetadata) => {
propertyMetadata.type = type;
if (typeof type !== "string") {
propertyMetadata.type = type;
}
propertyMetadata.store.merge(MONGOOSE_SCHEMA, {
type: Schema.Types.ObjectId,
ref: Store.from(type).get(MONGOOSE_MODEL_NAME)
ref: typeof type === "string" ? type : Store.from(type).get(MONGOOSE_MODEL_NAME)
});
});
}
48 changes: 36 additions & 12 deletions test/units/mongoose/decorators/ref.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,46 @@ import {Ref} from "../../../../src/mongoose/decorators";
import {expect} from "../../../tools";

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

class RefTest {
}
describe("type is a class", () => {
class Test {
}

before(() => {
Store.from(RefTest).set(MONGOOSE_MODEL_NAME, "RefTest");
Ref(RefTest)(Test, "test", descriptorOf(Test, "test"));
this.store = Store.from(Test, "test", descriptorOf(Test, "test"));
class RefTest {
}

before(() => {
Store.from(RefTest).set(MONGOOSE_MODEL_NAME, "RefTest");
Ref(RefTest)(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({
type: Schema.Types.ObjectId,
ref: "RefTest"
});
});
});

it("should set metadata", () => {
expect(this.store.get(MONGOOSE_SCHEMA)).to.deep.eq({
type: Schema.Types.ObjectId,
ref: "RefTest"
describe("type is a string", () => {
class Test {
}

class RefTest {
}

before(() => {
Store.from(RefTest).set(MONGOOSE_MODEL_NAME, "RefTest");
Ref("RefTest")(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({
type: Schema.Types.ObjectId,
ref: "RefTest"
});
});
});
});

0 comments on commit e6e82fb

Please sign in to comment.