From fed04ef5aedc7facf677180e45e92ae6137199a5 Mon Sep 17 00:00:00 2001 From: syuilo Date: Sun, 21 Oct 2018 10:05:15 +0900 Subject: [PATCH] Reduce network traffic of API response --- src/services/stats.ts | 55 ++++++++++++++++++++++++++++++++++++++----- 1 file changed, 49 insertions(+), 6 deletions(-) diff --git a/src/services/stats.ts b/src/services/stats.ts index 0b4106e28c..9d00541236 100644 --- a/src/services/stats.ts +++ b/src/services/stats.ts @@ -1,3 +1,4 @@ +const nestedProperty = require('nested-property'); import * as mongo from 'mongodb'; import db from '../db/mongodb'; import { INote } from '../models/note'; @@ -11,8 +12,13 @@ type Partial = { [P in keyof T]?: Partial; }; +type ArrayValue = { + [P in keyof T]: T[P] extends number ? Array : ArrayValue; +}; + type Span = 'day' | 'hour'; +//#region Chart Core type ChartDocument = { _id: mongo.ObjectID; @@ -119,17 +125,18 @@ abstract class Chart { protected inc(inc: Partial, group?: Obj): void { const query: Obj = {}; - const dive = (path: string, x: Obj) => { + const dive = (x: Obj, path?: string) => { Object.entries(x).forEach(([k, v]) => { + const p = path ? `${path}.${k}` : k; if (typeof v === 'number') { - query[path == null ? `data.${k}` : `data.${path}.${k}`] = v; + query[`data.${p}`] = v; } else { - dive(path == null ? k : `${path}.${k}`, v); + dive(v, p); } }); }; - dive(null, inc); + dive(inc); this.getCurrentStats('day', group).then(stats => { this.collection.findOneAndUpdate({ @@ -148,7 +155,7 @@ abstract class Chart { }); } - public async getStats(span: Span, range: number, group?: Obj): Promise { + public async getStats(span: Span, range: number, group?: Obj): Promise> { const chart: T[] = []; const now = new Date(); @@ -196,9 +203,45 @@ abstract class Chart { } } - return chart; + const res: ArrayValue = {} as any; + + /** + * [{ + * x: 1, + * y: 5 + * }, { + * x: 2, + * y: 6 + * }, { + * x: 3, + * y: 7 + * }] + * + * を + * + * { + * x: [1, 2, 3], + * y: [5, 6, 7] + * } + * + * にする + */ + const dive = (x: Obj, path?: string) => { + Object.entries(x).forEach(([k, v]) => { + if (typeof v == 'object') { + dive(v, p); + } else { + nestedProperty.set(res, p, chart.map(s => nestedProperty.get(s, p))); + } + }); + }; + + dive(chart[0]); + + return res; } } +//#endregion //#region Users stats /**