summaryrefslogtreecommitdiff
path: root/src/chart/per-user-drive.ts
blob: 3decedeb3b263d015050c8969184557a917dd04d (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
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
import autobind from 'autobind-decorator';
import Chart, { Obj } from './';
import DriveFile, { IDriveFile } from '../models/drive-file';

/**
 * ユーザーごとのドライブに関するチャート
 */
type PerUserDriveLog = {
	/**
	 * 集計期間時点での、全ドライブファイル数
	 */
	totalCount: number;

	/**
	 * 集計期間時点での、全ドライブファイルの合計サイズ
	 */
	totalSize: number;

	/**
	 * 増加したドライブファイル数
	 */
	incCount: number;

	/**
	 * 増加したドライブ使用量
	 */
	incSize: number;

	/**
	 * 減少したドライブファイル数
	 */
	decCount: number;

	/**
	 * 減少したドライブ使用量
	 */
	decSize: number;
};

class PerUserDriveChart extends Chart<PerUserDriveLog> {
	constructor() {
		super('perUserDrive', true);
	}

	@autobind
	protected async getTemplate(init: boolean, latest?: PerUserDriveLog, group?: any): Promise<PerUserDriveLog> {
		const calcSize = () => DriveFile
			.aggregate([{
				$match: {
					'metadata.userId': group,
					'metadata.deletedAt': { $exists: false }
				}
			}, {
				$project: {
					length: true
				}
			}, {
				$group: {
					_id: null,
					usage: { $sum: '$length' }
				}
			}])
			.then(res => res.length > 0 ? res[0].usage : 0);

		const [count, size] = init ? await Promise.all([
			DriveFile.count({ 'metadata.userId': group }),
			calcSize()
		]) : [
			latest ? latest.totalCount : 0,
			latest ? latest.totalSize : 0
		];

		return {
			totalCount: count,
			totalSize: size,
			incCount: 0,
			incSize: 0,
			decCount: 0,
			decSize: 0
		};
	}

	@autobind
	public async update(file: IDriveFile, isAdditional: boolean) {
		const update: Obj = {};

		update.totalCount = isAdditional ? 1 : -1;
		update.totalSize = isAdditional ? file.length : -file.length;
		if (isAdditional) {
			update.incCount = 1;
			update.incSize = file.length;
		} else {
			update.decCount = 1;
			update.decSize = file.length;
		}

		await this.inc(update, file.metadata.userId);
	}
}

export default new PerUserDriveChart();