Skip to content

Commit

Permalink
feat(core): add Reference.set() method
Browse files Browse the repository at this point in the history
Issue: #264
  • Loading branch information
B4nan committed Dec 10, 2019
1 parent ab7b9cd commit 08cbead
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 4 deletions.
6 changes: 6 additions & 0 deletions docs/docs/entity-references.md
Expand Up @@ -111,6 +111,12 @@ book.author = Reference.create(repo.getReference(2));
await orm.em.flush();
```

If the reference already exist, you can also re-assign to it via `set()` method:

```typescript
book.author.set(new Author(...));
```

## What is IdentifiedReference?

`IdentifiedReference` is an intersection type that adds primary key property to the `Reference`
Expand Down
15 changes: 12 additions & 3 deletions lib/entity/Reference.ts
Expand Up @@ -6,19 +6,20 @@ export type IdentifiedReference<T extends AnyEntity<T>, PK extends keyof T = 'id

export class Reference<T extends AnyEntity<T>> {

constructor(private readonly entity: T) {
constructor(private entity: T) {
this.set(entity);
const wrapped = wrap(this.entity);

Object.defineProperty(this, wrapped.__meta.primaryKey, {
get() {
return wrapped.__primaryKey;
return wrap(this.entity).__primaryKey;
},
});

if (wrapped.__meta.serializedPrimaryKey && wrapped.__meta.primaryKey !== wrapped.__meta.serializedPrimaryKey) {
Object.defineProperty(this, wrapped.__meta.serializedPrimaryKey, {
get() {
return wrapped.__serializedPrimaryKey;
return wrap(this.entity).__serializedPrimaryKey;
},
});
}
Expand All @@ -45,6 +46,14 @@ export class Reference<T extends AnyEntity<T>> {
return this.entity[prop];
}

set(entity: T | IdentifiedReference<T>): void {
if (entity instanceof Reference) {
entity = entity.unwrap();
}

this.entity = entity;
}

unwrap(): T {
return wrap(this.entity);
}
Expand Down
8 changes: 7 additions & 1 deletion tests/EntityManager.mongo.test.ts
Expand Up @@ -1579,7 +1579,8 @@ describe('EntityManagerMongo', () => {

test('reference wrapper', async () => {
const author = new Author('God', 'hello@heaven.god');
await orm.em.persistAndFlush(author);
const author2 = new Author('God 2', 'hello2@heaven.god');
await orm.em.persistAndFlush([author, author2]);
orm.em.clear();

const ref = orm.em.getReference<Author, 'id' | '_id'>(Author, author.id, true);
Expand All @@ -1596,6 +1597,11 @@ describe('EntityManagerMongo', () => {
const ref3 = Reference.create(ref2);
expect(ref2).toBe(ref3);

expect(ref3.unwrap()).toBe(author);
ref3.set(author2);
expect(ref3.unwrap()).toBe(author2);
expect(ref3.id).toBe(author2.id);

const ent = await ref.load();
expect(ent).toBeInstanceOf(Author);
expect(wrap(ent).isInitialized()).toBe(true);
Expand Down

0 comments on commit 08cbead

Please sign in to comment.