-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathverifyMongoSchema.ts
More file actions
83 lines (82 loc) · 4.06 KB
/
verifyMongoSchema.ts
File metadata and controls
83 lines (82 loc) · 4.06 KB
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
import { MongoClient } from 'mongodb'
import { getConfig } from './getConfig'
export const verifyMongoSchema = async (schema: {
properties: Record<string, unknown>
}) => {
const { mongoUri, mongoDb } = getConfig()
const client = new MongoClient(mongoUri)
try {
await client.connect()
const database = client.db(mongoDb)
await Promise.all(
Object.keys(schema.properties).map(async (collectionName) => {
try {
const firstFailedDocument = await database
.collection(collectionName)
.findOne({
$nor: [
{
$jsonSchema:
schema.properties[collectionName],
},
],
})
if (firstFailedDocument) {
try {
// In order to provide some better debug information, we try to update the first failed document in hopes of getting `schemaRulesNotSatisfied` information
await database.collection(collectionName).updateOne(
{ _id: firstFailedDocument._id },
{
$set: {
___schmaValidator: Math.random(),
},
},
)
// We shouldn't have gotten to this point, the previous update should have thrown due to failed $jsonSchema constraints.
// If it didn't, it probably means that we forgot to `apply` the schema or that the validation action is not "error"
console.warn(
'Not able to provide the full debug info, make sure that you have applied the schema with `VALIDATION_LEVEL=strict VALIDATION_ACTION=error`',
)
console.info(
`❌ Collection ${collectionName} failed validation, first failed document is: `,
firstFailedDocument,
)
// Cleanup
await database.collection(collectionName).updateOne(
{ _id: firstFailedDocument._id },
{
$unset: {
___schmaValidator: '',
},
},
)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (e: any) {
console.info(
`❌ Collection ${collectionName} failed validation, first failed document is: `,
firstFailedDocument,
)
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
if (e?.errInfo?.details?.schemaRulesNotSatisfied) {
console.log('Reason for failure:')
console.dir(
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
e.errInfo.details.schemaRulesNotSatisfied,
{ depth: null },
)
}
}
} else {
console.info(
`✅ Collection ${collectionName} passed validation`,
)
}
} catch (e) {
console.error(e, collectionName)
}
}),
)
} finally {
await client.close()
}
}