-
-
Notifications
You must be signed in to change notification settings - Fork 495
/
GH3988.test.ts
114 lines (83 loc) · 2.27 KB
/
GH3988.test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
import { Collection, Entity, ManyToOne, OneToMany, PrimaryKey, SimpleLogger, Type } from '@mikro-orm/core';
import { MikroORM } from '@mikro-orm/sqlite';
import { mockLogger } from '../helpers';
class Id {
readonly value: number;
constructor(value: number) {
this.value = value;
}
}
export class IdType extends Type<Id, string> {
override convertToDatabaseValue(value: any) {
if (value instanceof Id) {
return value.value;
}
return value;
}
override convertToJSValue(value: any) {
if (typeof value === 'string') {
const id = Object.create(Id.prototype);
return Object.assign(id, {
value,
});
}
return value;
}
override compareAsType() {
return 'number';
}
override getColumnType() {
return 'integer';
}
}
@Entity()
class ParentEntity {
@PrimaryKey({ type: IdType, autoincrement: false })
id!: Id;
@PrimaryKey({ type: IdType, autoincrement: false })
id2!: Id;
@OneToMany({
entity: () => ChildEntity,
mappedBy: 'parent',
})
children = new Collection<ChildEntity>(this);
}
@Entity()
class ChildEntity {
@PrimaryKey({ type: IdType, autoincrement: false })
id!: Id;
@ManyToOne(() => ParentEntity)
parent!: ParentEntity;
}
let orm: MikroORM;
beforeAll(async () => {
orm = await MikroORM.init({
entities: [ParentEntity, ChildEntity],
dbName: ':memory:',
loggerFactory: options => new SimpleLogger(options),
});
await orm.schema.createSchema();
});
afterAll(async () => {
await orm.close();
});
it('should create and persist entity along with child entity', async () => {
const parentRepository = orm.em.fork().getRepository(ParentEntity);
// Create parent
const parent = new ParentEntity();
parent.id = new Id(1);
parent.id2 = new Id(2);
// Create child
const child = new ChildEntity();
child.id = new Id(1);
// Add child to parent
parent.children.add(child);
const mock = mockLogger(orm);
await parentRepository.persistAndFlush(parent);
expect(mock.mock.calls).toEqual([
['[query] begin'],
['[query] insert into `parent_entity` (`id`, `id2`) values (1, 2) returning `id`, `id2`'],
['[query] insert into `child_entity` (`id`, `parent_id`, `parent_id2`) values (1, 1, 2) returning `id`'],
['[query] commit'],
]);
});