docs-example.ts
4.64 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
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
// This file is used as example.
import {BuildOptions, DataTypes, Model, Sequelize} from 'sequelize';
import {
Association,
HasManyAddAssociationMixin,
HasManyCountAssociationsMixin,
HasManyCreateAssociationMixin,
HasManyGetAssociationsMixin,
HasManyHasAssociationMixin
} from '../../lib/associations';
import QueryTypes = require("../../lib/query-types");
class User extends Model {
public id!: number; // Note that the `null assertion` `!` is required in strict mode.
public name!: string;
public preferredName!: string | null; // for nullable fields
// timestamps!
public readonly createdAt!: Date;
public readonly updatedAt!: Date;
// Since TS cannot determine model association at compile time
// we have to declare them here purely virtually
// these will not exist until `Model.init` was called.
public getProjects: HasManyGetAssociationsMixin<Project>;
public addProject: HasManyAddAssociationMixin<Project, number>;
public hasProject: HasManyHasAssociationMixin<Project, number>;
public countProjects: HasManyCountAssociationsMixin;
public createProject: HasManyCreateAssociationMixin<Project>;
// You can also pre-declare possible inclusions, these will only be populated if you
// actively include a relation.
public readonly projects?: Project[];
public static associtations: {
projects: Association<User, Project>;
};
}
const sequelize = new Sequelize('mysql://root:asd123@localhost:3306/mydb');
class Project extends Model {
public id!: number;
public ownerId!: number;
public name!: string;
public readonly createdAt!: Date;
public readonly updatedAt!: Date;
}
class Address extends Model {
public userId!: number;
public address!: string;
public readonly createdAt!: Date;
public readonly updatedAt!: Date;
}
Project.init({
id: {
type: new DataTypes.INTEGER.UNSIGNED(), // you can omit the `new` but this is discouraged
autoIncrement: true,
primaryKey: true,
},
ownerId: {
type: new DataTypes.INTEGER.UNSIGNED(),
allowNull: false,
},
name: {
type: new DataTypes.STRING(128),
allowNull: false,
}
}, {
sequelize,
tableName: 'projects',
});
User.init({
id: {
type: new DataTypes.INTEGER.UNSIGNED(),
autoIncrement: true,
primaryKey: true,
},
name: {
type: new DataTypes.STRING(128),
allowNull: false,
},
preferredName: {
type: new DataTypes.STRING(128),
allowNull: true
}
}, {
tableName: 'users',
sequelize: sequelize, // this bit is important
});
Address.init({
userId: {
type: new DataTypes.INTEGER.UNSIGNED(),
},
address: {
type: new DataTypes.STRING(128),
allowNull: false,
}
}, {
tableName: 'users',
sequelize: sequelize, // this bit is important
});
// Here we associate which actually populates out pre-declared `association` static and other methods.
User.hasMany(Project, {
sourceKey: 'id',
foreignKey: 'ownerId',
as: 'projects' // this determines the name in `associations`!
});
Address.belongsTo(User, {targetKey: 'id'});
User.hasOne(Address,{sourceKey: 'id'});
async function stuff() {
// Please note that when using async/await you lose the `bluebird` promise context
// and you fall back to native
const newUser = await User.create({
name: 'Johnny',
preferredName: 'John',
});
console.log(newUser.id, newUser.name, newUser.preferredName);
const project = await newUser.createProject({
name: 'first!',
});
const ourUser = await User.findByPk(1, {
include: [User.associations.Project],
rejectOnEmpty: true, // Specifying true here removes `null` from the return type!
});
console.log(ourUser.projects![0].name); // Note the `!` null assertion since TS can't know if we included
// the model or not
const user = await sequelize.query('SELECT * FROM users WHERE name = :userName',{
type: QueryTypes.SELECT,
replacements: {
userName: 'Johnny'
},
mapToModel: true,
model: User
})
}
// Legacy models
// We need to declare an interface for our model that is basically what our class would be
interface MyModel extends Model {
readonly id: number;
}
// Need to declare the static model so `findOne` etc. use correct types.
type MyModelStatic = typeof Model & {
new (values?: object, options?: BuildOptions): MyModel;
}
// TS can't derive a proper class definition from a `.define` call, therefor we need to cast here.
const MyDefineModel = <MyModelStatic>sequelize.define('MyDefineModel', {
id: {
primaryKey: true,
type: DataTypes.INTEGER.UNSIGNED,
}
});
function stuffTwo() {
MyDefineModel.findByPk(1, {
rejectOnEmpty: true,
})
.then(myModel => {
console.log(myModel.id);
});
}