-
Notifications
You must be signed in to change notification settings - Fork 1
/
noteRelations.ts
248 lines (220 loc) · 6.36 KB
/
noteRelations.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
import type { CreationOptional, InferAttributes, InferCreationAttributes, ModelStatic, Sequelize } from 'sequelize';
import { QueryTypes } from 'sequelize';
import { Op } from 'sequelize';
import { NoteModel } from '@repository/storage/postgres/orm/sequelize/note.js';
import type Orm from '@repository/storage/postgres/orm/sequelize/index.js';
import type { NoteInternalId } from '@domain/entities/note.js';
import type { Note } from '@domain/entities/note.js';
import { Model, DataTypes } from 'sequelize';
/**
* Class representing a note relations in database
*/
export class NoteRelationsModel extends Model<InferAttributes<NoteRelationsModel>, InferCreationAttributes<NoteRelationsModel>> {
/**
* Relation id
*/
public declare id: CreationOptional<number>;
/**
* Id of current note
*/
public declare noteId: Note['id'];
/**
* Id of parent note
*/
public declare parentId: Note['id'];
}
/**
* Class representing a table storing of Note relationship
*/
export default class NoteRelationsSequelizeStorage {
/**
* Note relationship model in database
*/
public model: typeof NoteRelationsModel;
/**
* Note model instance
*/
private noteModel: typeof NoteModel | null = null;
/**
* Database instance
*/
private readonly database: Sequelize;
/**
* Table name
*/
private readonly tableName = 'note_relations';
/**
* Constructor for note relatinship storage
* @param ormInstance - ORM instance
*/
constructor({ connection }: Orm) {
this.database = connection;
/**
* Initiate note relationship model
*/
this.model = NoteRelationsModel.init({
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
},
noteId: {
type: DataTypes.INTEGER,
allowNull: false,
references: {
model: NoteModel.tableName,
key: 'id',
},
},
parentId: {
type: DataTypes.INTEGER,
allowNull: false,
references: {
model: NoteModel.tableName,
key: 'id',
},
},
}, {
tableName: this.tableName,
sequelize: this.database,
timestamps: false,
});
}
/**
* Insert note relation to database
* @param noteId - id of the current note
* @param parentId - id of the parent note
*/
public async createNoteRelation(noteId: NoteInternalId, parentId: NoteInternalId): Promise<boolean> {
const newRelation = await this.model.create({
noteId,
parentId,
});
return newRelation.id !== undefined;
}
/**
* Gets parent note id by note id
* @param noteId - note id
*/
public async getParentNoteIdByNoteId(noteId: NoteInternalId): Promise<NoteInternalId | null> {
const found = await this.model.findOne({
where: {
noteId: noteId,
},
});
const parentNoteId = found?.parentId;
return parentNoteId !== undefined ? parentNoteId : null;
};
/**
* Update note content by id
* @param noteId - id of the current note
* @param parentId - parent note id
* @returns Note on success, null on failure
*/
public async updateNoteRelationById(noteId: NoteInternalId, parentId: NoteInternalId): Promise<boolean> {
const [affectedRowsCount] = await this.model.update({
parentId,
}, {
where: {
noteId,
},
returning: true,
});
return affectedRowsCount === 1;
}
/**
* Delete all note relations contains noteId
* @param noteId - id of the current note
*/
public async deleteNoteRelationsByNoteId(noteId: NoteInternalId): Promise<boolean> {
const affectedRows = await this.model.destroy({
where: {
[Op.or]: [{
noteId: noteId,
}, {
parentId: noteId,
}],
},
});
/**
* If the relation was not found return false
*/
return affectedRows > 0;
}
/**
* Unlink parent note from the current note
* @param noteId - id of note to unlink parent
*/
public async unlinkParent(noteId: NoteInternalId): Promise<boolean> {
const affectedRows = await this.model.destroy({
where: {
noteId,
},
});
/**
* We need to delete only one relation because note can only have one parent
*/
return affectedRows === 1;
}
/**
* Creates association with note model to make joins
* @param model - initialized note model
*/
public createAssociationWithNoteModel(model: ModelStatic<NoteModel>): void {
this.noteModel = model;
/**
* Make one-to-one association with note model
* We can not create note relations without note
*/
this.model.belongsTo(model, {
foreignKey: 'noteId',
as: 'note',
});
}
/**
* Checks if the note has any relation
* @param noteId - id of the current note
*/
public async hasRelation(noteId: NoteInternalId): Promise<boolean> {
const foundNote = await this.model.findOne ({
where: {
[Op.or]: [{
noteId: noteId,
}, {
parentId: noteId,
}],
},
});
return foundNote !== null;
};
/**
* Get all parent notes of a note that a user has access to,
* where the user has access to.
* @param noteId - the ID of the note.
*/
public async getNoteParentsIds(noteId: NoteInternalId): Promise<NoteInternalId[]> {
// Query to get all parent notes of a note.
// The query uses a recursive common table expression (CTE) to get all parent notes of a note.
// It starts from the note with the ID :startNoteId and recursively gets all parent notes.
// It returns a list of note ID and parent ID of the note.
const query = `
WITH RECURSIVE note_parents AS (
SELECT np.note_id, np.parent_id
FROM ${String(this.database.literal(this.tableName).val)} np
WHERE np.note_id = :startNoteId
UNION ALL
SELECT nr.note_id, nr.parent_id
FROM ${String(this.database.literal(this.tableName).val)} nr
INNER JOIN note_parents np ON np.parent_id = nr.note_id
)
SELECT np.note_id AS "noteId", np.parent_id AS "parentId"
FROM note_parents np;`;
const result = await this.model.sequelize?.query(query, {
replacements: { startNoteId: noteId },
type: QueryTypes.SELECT,
});
let noteParents = (result as { noteId: number; parentId: number }[])?.map(note => note.parentId) ?? [];
noteParents.reverse();
return noteParents;
}
}