-
-
Notifications
You must be signed in to change notification settings - Fork 100
/
Copy pathsimple.ts
81 lines (63 loc) · 1.99 KB
/
simple.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
import { Entity, PrimaryGeneratedColumn, Column, Connection, BaseEntity, LessThan } from "typeorm";
import { newDb } from '../../src/db';
import { expect } from 'bun:test';
// Declare an entity
@Entity()
export class User extends BaseEntity {
@PrimaryGeneratedColumn({ type: 'integer' })
id!: number;
@Column({ type: 'text' })
firstName!: string;
@Column({ type: 'text' })
lastName!: string;
@Column({ type: 'int' })
age!: number;
}
export async function typeormSimpleSample() {
//==== create a memory db
const db = newDb({
// 👉 Recommended when using Typeorm .synchronize(), which creates foreign keys but not indices !
autoCreateForeignKeyIndices: true,
});
//==== create a Typeorm connection
const got: Connection = await db.adapters.createTypeormConnection({
type: 'postgres',
entities: [User]
});
try {
//==== create tables
await got.synchronize();
const users = got.getRepository(User);
//==== create entities
await users.create({
firstName: 'john',
lastName: 'doe',
age: 18,
}).save();
await users.create({
firstName: 'john',
lastName: 'lennon',
age: 99,
}).save();
const duck = await users.create({
firstName: 'donald',
lastName: 'duck',
age: 12,
}).save();
//==== query entities
const youngJohns = await users.find({
firstName: 'john',
age: LessThan(30)
});
expect(youngJohns.map(x => x.lastName)) // outputs 'doe' !
.toEqual(['doe']);
//==== modify entities
duck.firstName = 'daisy';
await duck.save();
} finally {
// do not forget to close the connection once done...
// ... typeorm stores connections in a static object,
// and does not like opening 'default connections.
await got.close();
}
}