-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
executable file
·168 lines (162 loc) · 6.91 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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
const Ajv = require('ajv');
const AjvBsonType = require('ajv-bsontype');
const MongoMock = require('mongo-mock');
const ajv = new Ajv({ allErrors: true });
AjvBsonType(ajv);
const MongoMockUrl = 'mongodb://localhost:27017/mongo-schemer';
MongoMock.max_delay = 0;
const validationErrors = async (db, collectionName, { doc, err }) => {
const collectionInfo = await db.command({ listCollections: 1, filter: { name: collectionName } });
const schema = collectionInfo.cursor.firstBatch[0].options.validator.$jsonSchema;
if (!doc && err) {
doc = ('op' in err) ? err.op : err.getOperation(); // eslint-disable-line no-param-reassign
}
const valid = ajv.validate(schema, doc);
return { valid, errors: ajv.errors };
};
const explainSchemaErrors = (incomingDb, options = {}) => {
const db = incomingDb;
const { onError, includeValidationInError } = options;
if (onError) {
db.onValidationError = onError;
}
const explainValidationErrorLogic = async (...args) => {
const { valid, errors } = await validationErrors(...args);
if (!valid && db.onValidationError) {
db.onValidationError(errors);
}
return errors;
};
// If returning validation errors, wait for them
const explainValidationError = (...args) => {
const explanationP = explainValidationErrorLogic(...args);
if (includeValidationInError) return explanationP;
return Promise.resolve(null);
};
const originalCollection = db.collection;
db.collection = function replacementCollection(...args) {
const collectionName = args[0];
const col = originalCollection.call(this, ...args);
const originalInsertOne = col.insertOne;
const originalInsertMany = col.insertMany;
const originalUpdateOne = col.updateOne;
const originalUpdateMany = col.updateMany;
const originalfindOneAndUpdate = col.findOneAndUpdate;
col.insertOne = async function replacementInsertOne(...ioArgs) {
try {
return await originalInsertOne.call(this, ...ioArgs);
} catch (err) {
if (err && err.code === 121) {
err.validationErrors = await explainValidationError(db, collectionName, { doc: ioArgs[0] });
}
throw err;
}
};
col.insertMany = async function replacementInsertMany(...imArgs) {
try {
return await originalInsertMany.call(this, ...imArgs);
} catch (err) {
if (err && err.code === 121) {
err.validationErrors = await explainValidationError(db, collectionName, { err });
}
throw err;
}
};
col.updateOne = async function replacementUpdateOne(...uoArgsIncoming) {
const uoArgs = uoArgsIncoming;
try {
return await originalUpdateOne.call(this, ...uoArgs);
} catch (err) {
if (err && err.code === 121) {
// Get doc we're trying to update
const currentDoc = await col.findOne(uoArgs[0]);
// If doc created & updated in same MongoDB transaction enhanced validation details cannot be provided as
// validation errors roll back transactions leaving us with no knowledge of the originally created valid doc
if (currentDoc) {
// Load current doc into mock mongo
const mockDb = await MongoMock.MongoClient.connect(MongoMockUrl);
const mockCol = mockDb.collection('mock');
await mockCol.insertOne(currentDoc);
// Apply updates to our mock version of the current doc
await mockCol.updateOne(...uoArgs);
// Get updated doc from mock mongo to compare against schema
const doc = await mockCol.findOne(uoArgs[0]);
// Explain schema errors
err.validationErrors = await explainValidationError(db, collectionName, { doc });
// Clean up MongoMock
await mockCol.removeOne(...uoArgs);
// close MongoMock DB connection
mockDb.close();
}
}
throw err;
}
};
col.updateMany = async function replacementUpdateMany(...umArgsIncoming) {
const umArgs = umArgsIncoming;
try {
return await originalUpdateMany.call(this, ...umArgs);
} catch (err) {
if (err && err.code === 121) {
// Get docs we're trying to update
const currentDocs = await col.find(umArgs[0]).toArray();
// If all docs created & updated in same MongoDB transaction enhanced validation details cannot be provided as
// validation errors roll back transactions leaving us with no knowledge of the originally created valid docs
if (currentDocs.length > 0) {
// Load current docs into mock mongo
const mockDb = await MongoMock.MongoClient.connect(MongoMockUrl);
const mockCol = mockDb.collection('mock');
await mockCol.insertMany(currentDocs);
// Apply updates to our mock version of the current docs
await mockCol.updateMany(...umArgs);
// Get updated docs from mock mongo to compare against schema
const docs = await mockCol.find(umArgs[0]).toArray();
const errorLists = await Promise.all(docs.map(doc => explainValidationError(db, collectionName, { doc })));
err.validationErrors = [].concat(...errorLists);
// Clean up MongoMock
await mockCol.removeMany(...umArgs);
// close MongoMock DB connection
mockDb.close();
}
}
throw err;
}
};
col.findOneAndUpdate = async function replacementfindOneAndUpdate(...uoArgsIncoming) {
const uoArgs = uoArgsIncoming;
try {
return await originalfindOneAndUpdate.call(this, ...uoArgs);
} catch (err) {
if (err && err.code === 121) {
// Get doc we're trying to update
const currentDoc = await col.findOne(uoArgs[0]);
// If doc created & updated in same MongoDB transaction enhanced validation details cannot be provided as
// validation errors roll back transactions leaving us with no knowledge of the originally created valid doc
if (currentDoc) {
// Load current doc into mock mongo
const mockDb = await MongoMock.MongoClient.connect(MongoMockUrl);
const mockCol = mockDb.collection('mock');
await mockCol.insertOne(currentDoc);
// Apply updates to our mock version of the current doc
await mockCol.findOneAndUpdate(...uoArgs);
// Get updated doc from mock mongo to compare against schema
const doc = await mockCol.findOne(uoArgs[0]);
// Explain schema errors
err.validationErrors = await explainValidationError(db, collectionName, { doc });
// Clean up MongoMock
await mockCol.removeOne(...uoArgs);
// close MongoMock DB connection
mockDb.close();
}
}
throw err;
}
};
return col;
};
return db;
};
module.exports = {
explainSchemaErrors,
validationErrors,
};