-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.js
109 lines (92 loc) · 2.82 KB
/
index.js
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
102
103
104
105
106
107
108
109
"use strict";
const fastifyPlugin = require("fastify-plugin");
const mongoose = require("mongoose");
const fixReferences = (decorator, schema) => {
Object.keys(schema).forEach((key) => {
if (schema[key].type === "ObjectId") {
schema[key].type = mongoose.Schema.Types.ObjectId;
if (schema[key].validateExistance) {
delete schema[key].validateExistance;
schema[key].validate = {
validator: async (v, cb) => {
try {
await decorator[schema[key].ref].findById(v);
} catch (e) {
/* istanbul ignore next */
throw new Error(
`${schema[key].ref} with ID ${v} does not exist in database!`
);
}
},
};
}
} else if (schema[key].length !== undefined) {
schema[key].forEach((member) => {
if (member.type === "ObjectId") {
member.type = mongoose.Schema.Types.ObjectId;
if (member.validateExistance) {
delete member.validateExistance;
member.validate = {
validator: async (v, cb) => {
try {
await decorator[member.ref].findById(v);
} catch (e) {
/* istanbul ignore next */
throw new Error(
`Post with ID ${v} does not exist in database!`
);
}
},
};
}
}
});
}
});
};
let decorator;
async function mongooseConnector(
fastify,
{ uri, settings, models = [], useNameAndAlias = false }
) {
await mongoose.connect(uri, settings);
decorator = {
instance: mongoose,
};
if (models.length !== 0) {
models.forEach((model) => {
fixReferences(decorator, model.schema);
const schema = new mongoose.Schema(model.schema, model.options);
if (model.class) schema.loadClass(model.class);
if (model.virtualize) model.virtualize(schema);
if (useNameAndAlias) {
/* istanbul ignore next */
if (model.alias === undefined)
throw new Error(`No alias defined for ${model.name}`);
decorator[model.alias] = mongoose.model(
model.alias,
schema,
model.name
);
} else {
decorator[
model.alias
? model.alias
: `${model.name[0].toUpperCase()}${model.name.slice(1)}`
] = mongoose.model(model.name, schema);
}
});
}
// Close connection when app is closing
fastify.addHook("onClose", (app, done) => {
app.mongoose.instance.connection.on("close", function () {
done();
});
app.mongoose.instance.connection.close();
});
fastify.decorate("mongoose", decorator);
}
module.exports = {
plugin: fastifyPlugin(mongooseConnector),
decorator: () => decorator,
};