User.ts
1.99 KB
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
import {
BelongsTo,
BelongsToCreateAssociationMixin,
BelongsToGetAssociationMixin,
BelongsToSetAssociationMixin,
DataTypes,
FindOptions,
Model,
ModelCtor
} from 'sequelize';
import { sequelize } from '../connection';
export class User extends Model {
public static associations: {
group: BelongsTo<User, UserGroup>;
};
public id!: number;
public username!: string;
public firstName!: string;
public lastName!: string;
public createdAt!: Date;
public updatedAt!: Date;
// mixins for association (optional)
public groupId!: number;
public group?: UserGroup;
public getGroup!: BelongsToGetAssociationMixin<UserGroup>;
public setGroup!: BelongsToSetAssociationMixin<UserGroup, number>;
public createGroup!: BelongsToCreateAssociationMixin<UserGroup>;
}
User.init(
{
firstName: DataTypes.STRING,
lastName: DataTypes.STRING,
username: DataTypes.STRING,
},
{
version: true,
getterMethods: {
a() {
return 1;
},
},
setterMethods: {
b(val: string) {
(<User>this).username = val;
},
},
scopes: {
custom(a: number) {
return {
where: {
firstName: a,
},
};
},
custom2() {
return {}
}
},
sequelize,
}
);
// Hooks
User.afterFind((users, options) => {
console.log('found');
});
// TODO: VSCode shows the typing being correctly narrowed but doesn't do it correctly
User.addHook('beforeFind', 'test', (options: FindOptions) => {
return undefined;
});
// associate
// it is important to import _after_ the model above is already exported so the circular reference works.
import { UserGroup } from './UserGroup';
export const Group = User.belongsTo(UserGroup, { as: 'group', foreignKey: 'groupId' });
// associations refer to their Model
const userType: ModelCtor<User> = User.associations.group.source;
const groupType: ModelCtor<UserGroup> = User.associations.group.target;
User.scope([
'custom2',
{ method: [ 'custom', 32 ] }
])