summaryrefslogtreecommitdiff
path: root/packages/backend/src/services/chart/charts/per-user-notes.ts
blob: d048c888856a329a385a1eacec344b15b02f63fb (plain)
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
import autobind from 'autobind-decorator';
import Chart, { Obj, DeepPartial } from '../core';
import { User } from '@/models/entities/user';
import { SchemaType } from '@/misc/schema';
import { Notes } from '@/models/index';
import { Note } from '@/models/entities/note';
import { name, schema } from './entities/per-user-notes';

type PerUserNotesLog = SchemaType<typeof schema>;

/**
 * ユーザーごとのノートに関するチャート
 */
// eslint-disable-next-line import/no-default-export
export default class PerUserNotesChart extends Chart<PerUserNotesLog> {
	constructor() {
		super(name, schema, true);
	}

	@autobind
	protected genNewLog(latest: PerUserNotesLog): DeepPartial<PerUserNotesLog> {
		return {
			total: latest.total,
		};
	}

	@autobind
	protected aggregate(logs: PerUserNotesLog[]): PerUserNotesLog {
		return {
			total: logs[0].total,
			inc: logs.reduce((a, b) => a + b.inc, 0),
			dec: logs.reduce((a, b) => a + b.dec, 0),
			diffs: {
				reply: logs.reduce((a, b) => a + b.diffs.reply, 0),
				renote: logs.reduce((a, b) => a + b.diffs.renote, 0),
				normal: logs.reduce((a, b) => a + b.diffs.normal, 0),
			},
		};
	}

	@autobind
	protected async fetchActual(group: string): Promise<DeepPartial<PerUserNotesLog>> {
		const [count] = await Promise.all([
			Notes.count({ userId: group }),
		]);

		return {
			total: count,
		};
	}

	@autobind
	public async update(user: { id: User['id'] }, note: Note, isAdditional: boolean): Promise<void> {
		const update: Obj = {
			diffs: {},
		};

		update.total = isAdditional ? 1 : -1;

		if (isAdditional) {
			update.inc = 1;
		} else {
			update.dec = 1;
		}

		if (note.replyId != null) {
			update.diffs.reply = isAdditional ? 1 : -1;
		} else if (note.renoteId != null) {
			update.diffs.renote = isAdditional ? 1 : -1;
		} else {
			update.diffs.normal = isAdditional ? 1 : -1;
		}

		await this.inc(update, user.id);
	}
}