-
Notifications
You must be signed in to change notification settings - Fork 1
/
create-validator.mjs
48 lines (44 loc) · 1.33 KB
/
create-validator.mjs
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
import Ajv from "ajv"
import { readFile, writeFile } from "fs/promises"
import standaloneCode from "ajv/dist/standalone/index.js"
function compileSchema(schema) {
const ajv = new Ajv({
schemas: [schema],
allowUnionTypes: true,
code: { source: true, esm: true, lines: true },
})
return standaloneCode(ajv, {
Validator: schema["$id"],
})
}
function withId(json, id) {
return {
$id: id,
...json,
}
}
function writeOutputFiles(outputFile, code, type) {
return Promise.all([
writeFile(outputFile + ".js", code),
writeFile(
outputFile + ".d.ts",
`import { ValidatorFunction } from "./validator"
import { ${type} } from "./context-types"
export const Validator: ValidatorFunction<${type}>`
),
])
}
if (process.argv.length >= 6) {
const id = process.argv[2]
const inputFile = process.argv[3]
const outputFile = process.argv[4]
const type = process.argv[5]
readFile(inputFile)
.then((txt) => compileSchema(withId(JSON.parse(txt), id)))
.then((code) => writeOutputFiles(outputFile, code, type))
.then(() => console.log("Validator created successfully!"))
.catch((e) => console.error(e))
} else {
console.log("create-validator <id> <json-schema> <validator-js>")
process.exit(1)
}