-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtemplate.bind.ts
39 lines (33 loc) · 923 Bytes
/
template.bind.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
// import ajv
import Ajv from "ajv";
import ValidationError from "ajv/dist/runtime/validation_error";
import { showAJVErrors } from "./helper";
const ajv = new Ajv();
import templates from "./templates/template";
async function bindTemplate(template: string, obj: any) {
// check if template exists
if (!templates[template]) {
return {
errors: [
{
msg: "Template not found",
},
],
};
}
const schema = templates[template]["schema"];
const templateFunc = templates[template]["template"];
const plaintextFunc = templates[template]["plaintext"];
const validate = ajv.compile(schema);
const valid = validate(obj);
// if valid, return template
if (valid) {
return {
template: templateFunc(obj),
plaintext: plaintextFunc(obj),
errors: null
}
}
throw new ValidationError(showAJVErrors(validate.errors));
}
export default bindTemplate;