-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalidator.ts
86 lines (76 loc) · 2.14 KB
/
validator.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
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
import * as v from "valibot";
/*
API REFERENCE:
https://developers.notion.com/docs/working-with-databases
https://developers.notion.com/reference/property-value-object
*/
// S: Schema
// never throws error, purely for logging purpose.
export function check<S extends v.BaseSchema<unknown, unknown, v.BaseIssue<unknown>>>(
varName: string,
val: unknown,
schema: S,
): {
val: v.InferOutput<S>;
err?: string;
} {
type O = v.InferOutput<S>; // output
const result = v.safeParse(schema, val);
if (result.success) return { val: result.output satisfies O };
const error = result.issues.map((issue) => issue.message).join(", ");
console.error(`WARNING: Failed to parse schema of ${varName}: ${error}`);
return {
err: error,
val: val as O, // just let it go until it crashes for `cannot access property of undefined` or worse, sends undefined to slack };
};
}
export class TypeChecker {
check<S extends v.BaseSchema<unknown, unknown, v.BaseIssue<unknown>>>(name: string, val: unknown, schema: S) {
const { val: parsed, err } = check(name, val, schema);
if (err) {
this.failedCount++;
this.errors += `\n- ${err}`;
}
return parsed;
}
failedCount = 0;
errors = "";
hasFailed() {
return this.failedCount > 0;
}
}
export const Url = v.pipe(v.string(), v.url());
const NotionDate = v.object({
type: v.literal("date"),
date: v.object({
start: v.pipe(v.string(), v.regex(/\d{4}-\d{2}-\d{2}/) /* yyyy-MM-dd */),
}),
});
const NotionText = v.object({
type: v.literal("text"),
text: v.object({
content: v.string(),
}),
plain_text: v.string(),
});
const NotionTitle = v.object({
type: v.literal("title"),
title: v.array(v.union([NotionText])),
});
// API REFERENCE[user]: https://developers.notion.com/reference/user
const NotionUser = v.object({
object: v.literal("user"),
id: v.pipe(v.string(), v.uuid()),
name: v.union([v.string(), v.undefined()]),
});
const NotionPeople = v.object({
type: v.literal("people"),
people: v.array(NotionUser),
});
export const NotionTypes = {
date: NotionDate,
text: NotionText,
title: NotionTitle,
user: NotionUser,
people: NotionPeople,
};