-
Notifications
You must be signed in to change notification settings - Fork 1
/
note.ts
349 lines (311 loc) · 8.28 KB
/
note.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
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
import type { CreationOptional, InferAttributes, InferCreationAttributes, ModelStatic, NonAttribute, Sequelize } from 'sequelize';
import { DataTypes, Model, Op } from 'sequelize';
import type Orm from '@repository/storage/postgres/orm/sequelize/index.js';
import type { Note, NoteCreationAttributes, NoteInternalId, NotePublicId } from '@domain/entities/note.js';
import { UserModel } from '@repository/storage/postgres/orm/sequelize/user.js';
import type { NoteSettingsModel } from './noteSettings.js';
import type { NoteVisitsModel } from './noteVisits.js';
import type { NoteHistoryModel } from './noteHistory.js';
/* eslint-disable @typescript-eslint/naming-convention */
/**
* Class representing a note model in database
*/
export class NoteModel extends Model<InferAttributes<NoteModel>, InferCreationAttributes<NoteModel>> {
/**
* Id used for internal relations
*/
public declare id: CreationOptional<Note['id']>;
/**
* Id visible for users. Used to query Note by public API
*/
public declare publicId: Note['publicId'];
/**
* Note content
*/
public declare content: Note['content'];
/**
* Note creator, user identifier, who created this note
*/
public declare creatorId: Note['creatorId'];
/**
* Time when note was created
*/
public declare createdAt: CreationOptional<Note['createdAt']>;
/**
* Last time when note was updated
*/
public declare updatedAt: CreationOptional<Note['updatedAt']>;
/**
* Editor tools, which note contains
*/
public declare tools: Note['tools'];
/**
* Joined note settings model
*/
public declare noteSettings?: NonAttribute<NoteSettingsModel>;
}
/**
* Class representing a table storing Notes
*/
export default class NoteSequelizeStorage {
/**
* Note model in database
*/
public model: typeof NoteModel;
/**
* Notes settings model in database
*/
public settingsModel: typeof NoteSettingsModel | null = null;
/**
* Note visits model in database
*/
public visitsModel: typeof NoteVisitsModel | null = null;
public historyModel: typeof NoteHistoryModel | null = null;
/**
* Database instance
*/
private readonly database: Sequelize;
/**
* Table name
*/
private readonly tableName = 'notes';
/**
* Constructor for note storage
* @param ormInstance - ORM instance
*/
constructor({ connection }: Orm) {
this.database = connection;
/**
* Initiate note model
*/
this.model = NoteModel.init({
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
},
publicId: {
type: DataTypes.STRING,
allowNull: false,
},
content: DataTypes.JSON,
creatorId: {
type: DataTypes.INTEGER,
allowNull: false,
references: {
model: UserModel,
key: 'id',
},
},
tools: DataTypes.JSONB,
createdAt: DataTypes.DATE,
updatedAt: DataTypes.DATE,
}, {
tableName: this.tableName,
sequelize: this.database,
});
}
/**
* Creates association with note settings model
* @param model - initialized note settings model
*/
public createAssociationWithNoteSettingsModel(model: ModelStatic<NoteSettingsModel>): void {
this.settingsModel = model;
/**
* Create association with note settings, one-to-one
*/
this.model.hasOne(this.settingsModel, {
foreignKey: 'noteId',
as: 'noteSettings',
});
}
/**
* create association with note visits model
* @param model - initialized note visits model
*/
public createAssociationWithNoteVisitsModel(model: ModelStatic<NoteVisitsModel>): void {
this.visitsModel = model;
/**
* Create association with note visits, one-to-many
*/
this.model.hasMany(this.visitsModel, {
foreignKey: 'noteId',
as: 'noteVisits',
});
};
/**
* Insert note to database
* @param options - note creation options
* @returns - created note
*/
public async createNote(options: NoteCreationAttributes): Promise<Note> {
return await this.model.create({
publicId: options.publicId,
content: options.content,
creatorId: options.creatorId,
tools: options.tools,
});
}
/**
* Update note content by id
* @param id - note internal id
* @param content - new content
* @param tools - tools which are used in note
* @returns Note on success, null on failure
*/
public async updateNoteContentAndToolsById(id: NoteInternalId, content: Note['content'], tools: Note['tools']): Promise<Note | null> {
const [affectedRowsCount, affectedRows] = await this.model.update({
content,
tools,
}, {
where: {
id,
},
returning: true,
});
if (affectedRowsCount !== 1) {
return null;
}
return affectedRows[0];
}
/**
* Gets note by id
* @param id - internal id
*/
public async getNoteById(id: NoteInternalId): Promise<Note | null> {
return await this.model.findOne({
where: {
id,
},
});
}
/**
* Deletes note by id
* @param id - internal id
*/
public async deleteNoteById(id: NoteInternalId): Promise<boolean> {
const affectedRows = await this.model.destroy({
where: {
id,
},
});
/**
* If note not found return false
*/
return affectedRows > 0;
}
/**
* Gets note list by creator id
* @param userId - id of certain user
* @param offset - number of skipped notes
* @param limit - number of notes to get
* @returns list of the notes
*/
public async getNoteListByUserId(userId: number, offset: number, limit: number): Promise<Note[]> {
if (this.visitsModel === null) {
throw new Error('NoteStorage: NoteVisit model should be defined');
}
if (!this.settingsModel) {
throw new Error('NoteStorage: Note settings model not initialized');
}
const reply = await this.model.findAll({
offset: offset,
limit: limit,
where: {
'$noteVisits.user_id$': userId,
},
order: [[
{
model: this.visitsModel,
as: 'noteVisits',
},
'visited_at',
'DESC',
]],
include: [{
model: this.visitsModel,
as: 'noteVisits',
duplicating: false,
}, {
model: this.settingsModel,
as: 'noteSettings',
attributes: ['cover'],
duplicating: false,
}],
});
/**
* Convert note model data to Note entity with cover property
*/
return reply.map((note) => {
return {
id: note.id,
/**
* noteSettings is required to be, because we make join
*/
cover: note.noteSettings!.cover,
content: note.content,
updatedAt: note.updatedAt,
createdAt: note.createdAt,
publicId: note.publicId,
creatorId: note.creatorId,
tools: note.tools,
};
});
}
/**
* Gets note by id
* @param hostname - custom hostname
* @returns found note
*/
public async getNoteByHostname(hostname: string): Promise<Note | null> {
if (!this.settingsModel) {
throw new Error('NoteStorage: Note settings model not initialized');
}
/**
* select note which has hostname in its settings
*/
return await this.model.findOne({
where: {
'$noteSettings.custom_hostname$': hostname,
},
include: {
model: this.settingsModel,
as: 'noteSettings',
required: true,
attributes: [],
},
});
}
/**
* Gets note by public id
* @param publicId - note public id
* @returns found note
*/
public async getNoteByPublicId(publicId: NotePublicId): Promise<Note | null> {
return await this.model.findOne({
where: {
publicId,
},
});
};
/**
* Get all notes based on their ids in the same order of passed ids
* @param noteIds - list of note ids
*/
public async getNotesByIds(noteIds: NoteInternalId[]): Promise<Note[]> {
if (noteIds.length === 0) {
return [];
}
const notes: Note[] = await this.model.findAll({
where: {
id: {
[Op.in]: noteIds,
},
},
order: [
this.database.literal(`ARRAY_POSITION(ARRAY[${noteIds.map(id => `${id}`).join(',')}], id)`),
],
});
return notes;
}
}