/
model.hits.controller.ts
45 lines (40 loc) · 1.58 KB
/
model.hits.controller.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
import { DynamicConfigModel } from './../dynamic/dynamicconfig.model';
import { ModelHitsModel } from './model.hits.model';
import { Deco } from '../../';
import { Request, Response, NextFunction } from 'express';
let debug = require('debug')('app:middlewares:controllers:model.hits');
export class ModelHitsMiddleware {
static singleHit(modelId: string | 'dynamic') {
return (req: Request, res: Response, next: NextFunction) => {
ModelHitsMiddleware.modelId(modelId, res).then((modelId) => {
return ModelHitsModel.singleHit(req, res, modelId);
}).then(() => {
next();
}).catch(next);
}
}
static singleStats(modelId: string | 'dynamic') {
return (req: Request, res: Response, next: NextFunction) => {
ModelHitsMiddleware.modelId(modelId, res).then((modelId) => {
return ModelHitsModel.singleStats(req, res, modelId);
}).then((stats) => {
res.send({stats: stats});
}).catch(next);
}
}
private static modelId(modelId: string | 'dynamic', res: Response): Promise<string> {
if (modelId && modelId !== 'dynamic') return Promise.resolve(modelId);
if (modelId === 'dynamic') {
// find modelId in dynamic deco
let deco: Deco = res.locals.dynamicDeco;
if (deco && deco.modelId) return Promise.resolve(deco.modelId.toString());
else {
return DynamicConfigModel.getOneWithQuery({slug: deco.modelName}).then((config) => {
if (!config) throw new Error('Model not found');
return config._id.toHexString();
});
}
}
throw new Error('Model not found');
}
}