chore: split logic to multiple functions

This commit is contained in:
anatawa12 2023-11-29 21:20:21 +09:00
parent 1ac9a1227f
commit 60a752938a
No known key found for this signature in database
GPG Key ID: 9CA909848B8E4EA6
1 changed files with 34 additions and 20 deletions

View File

@ -35,6 +35,20 @@ export class FanoutTimelineEndpointService {
noteFilter: (note: MiNote) => boolean,
dbFallback: (untilId: string | null, sinceId: string | null, limit: number) => Promise<MiNote[]>,
}): Promise<Packed<'Note'>[]> {
return await this.noteEntityService.packMany(await this.getMiNotes(ps), ps.me);
}
@bindThis
private async getMiNotes(ps: {
untilId: string | null,
sinceId: string | null,
limit: number,
me?: { id: MiUser['id'] } | undefined | null,
useDbFallback: boolean,
redisTimelines: (string | { name: string, fallbackIfEmpty: boolean })[],
noteFilter: (note: MiNote) => boolean,
dbFallback: (untilId: string | null, sinceId: string | null, limit: number) => Promise<MiNote[]>,
}): Promise<MiNote[]> {
let noteIds: string[];
let shouldFallbackToDb = false;
@ -58,9 +72,23 @@ export class FanoutTimelineEndpointService {
shouldFallbackToDb = shouldFallbackToDb || (noteIds.length === 0);
let redisTimeline: MiNote[] = [];
if (!shouldFallbackToDb) {
const redisTimeline = await this.getAndFilterFromDb(noteIds, ps.noteFilter);
// TODO: 足りない分の埋め合わせ
if (redisTimeline.length !== 0) {
return redisTimeline;
}
}
if (ps.useDbFallback) { // fallback to db
return await ps.dbFallback(ps.untilId, ps.sinceId, ps.limit);
} else {
return [];
}
}
private async getAndFilterFromDb(noteIds: string[], noteFilter: (note: MiNote) => boolean): Promise<MiNote[]> {
const query = this.notesRepository.createQueryBuilder('note')
.where('note.id IN (:...noteIds)', { noteIds: noteIds })
.innerJoinAndSelect('note.user', 'user')
@ -70,24 +98,10 @@ export class FanoutTimelineEndpointService {
.leftJoinAndSelect('renote.user', 'renoteUser')
.leftJoinAndSelect('note.channel', 'channel');
redisTimeline = await query.getMany();
const notes = (await query.getMany()).filter(noteFilter);
redisTimeline = redisTimeline.filter(ps.noteFilter);
notes.sort((a, b) => a.id > b.id ? -1 : 1);
redisTimeline.sort((a, b) => a.id > b.id ? -1 : 1);
// TODO: 足りない分の埋め合わせ
if (redisTimeline.length !== 0) {
return await this.noteEntityService.packMany(redisTimeline, ps.me);
}
}
if (ps.useDbFallback) { // fallback to db
const timeline = await ps.dbFallback(ps.untilId, ps.sinceId, ps.limit);
return await this.noteEntityService.packMany(timeline, ps.me);
} else {
return [];
}
return notes;
}
}