-
Notifications
You must be signed in to change notification settings - Fork 87
/
form_statistics_total.server.model.ts
99 lines (88 loc) · 2.38 KB
/
form_statistics_total.server.model.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
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
import { Mongoose, Schema } from 'mongoose'
import { ExtractTypeFromArray } from 'shared/types'
import {
AggregateFormCountResult,
IFormStatisticsTotalModel,
IFormStatisticsTotalSchema,
} from '../../types'
import { FORM_SCHEMA_ID } from './form.server.model'
const FORM_STATS_TOTAL_SCHEMA_ID = 'FormStatisticsTotal'
const FORM_STATS_COLLECTION_NAME = 'formStatisticsTotal'
const compileFormStatisticsTotalModel = (db: Mongoose) => {
const FormStatisticsTotalSchema = new Schema<
IFormStatisticsTotalSchema,
IFormStatisticsTotalModel
>(
{
formId: {
type: Schema.Types.ObjectId,
ref: FORM_SCHEMA_ID,
required: true,
},
totalCount: {
type: Number,
required: true,
min: 1,
},
lastSubmission: {
type: Date,
required: true,
},
},
{
read: 'secondary',
},
)
// Indices
FormStatisticsTotalSchema.index({ totalCount: 1 })
FormStatisticsTotalSchema.index({ formId: 1 })
// Hooks
FormStatisticsTotalSchema.pre<IFormStatisticsTotalSchema>(
'save',
function (next) {
next(new Error('FormStatisticsTotal schema is read only'))
},
)
// Static functions
FormStatisticsTotalSchema.statics.aggregateFormCount = function (
minSubCount: number,
): Promise<AggregateFormCountResult> {
return this.aggregate<ExtractTypeFromArray<AggregateFormCountResult>>([
{
$match: {
totalCount: {
$gt: minSubCount,
},
},
},
{
$count: 'numActiveForms',
},
]).exec()
}
const FormStatisticsTotalModel = db.model<
IFormStatisticsTotalSchema,
IFormStatisticsTotalModel
>(
FORM_STATS_TOTAL_SCHEMA_ID,
FormStatisticsTotalSchema,
FORM_STATS_COLLECTION_NAME,
)
return FormStatisticsTotalModel
}
/**
* Retrieves the FormStatisticsTotal model on the given Mongoose instance. If
* the model is not registered yet, the model will be registered and returned.
* @param db The mongoose instance to retrieve the FormStatisticsTotal model from
* @returns The FormStatisticsTotal model
*/
const getFormStatisticsTotalModel = (
db: Mongoose,
): IFormStatisticsTotalModel => {
try {
return db.model(FORM_STATS_TOTAL_SCHEMA_ID) as IFormStatisticsTotalModel
} catch {
return compileFormStatisticsTotalModel(db)
}
}
export default getFormStatisticsTotalModel