summary refs log tree commit diff
path: root/src/util/util/imports/Checks.ts
blob: 19a841713dcb9ac6e1cccd8994c0e9982d096794 (plain) (blame)
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
//source: https://github.com/Flam3rboy/-server/blob/master/src/check.ts
import { NextFunction, Request, Response } from "express";
import { HTTPError } from ".";

const OPTIONAL_PREFIX = "$";
const EMAIL_REGEX =
	/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

export function check(schema: any) {
	return (req: Request, res: Response, next: NextFunction) => {
		try {
			const result = instanceOf(schema, req.body, { path: "body" });
			if (result === true) return next();
			throw result;
		} catch (error) {
			next(new HTTPError((error as any).toString(), 400));
		}
	};
}
export class Tuple {
	public types: any[];
	constructor(...types: any[]) {
		this.types = types;
	}
}

export class Email {
	constructor(public email: string) {}
	check() {
		return !!this.email.match(EMAIL_REGEX);
	}
}
export function instanceOf(
	type: any,
	value: any,
	{ path = "", optional = false }: { path?: string; optional?: boolean } = {}
): boolean {
	if (!type) return true; // no type was specified

	if (value == null) {
		if (optional) return true;
		throw `${path} is required`;
	}

	switch (type) {
		case String:
			if (typeof value === "string") return true;
			throw `${path} must be a string`;
		case Number:
			value = Number(value);
			if (typeof value === "number" && !isNaN(value)) return true;
			throw `${path} must be a number`;
		case BigInt:
			try {
				value = BigInt(value);
				if (typeof value === "bigint") return true;
			} catch (error) {}
			throw `${path} must be a bigint`;
		case Boolean:
			if (value == "true") value = true;
			if (value == "false") value = false;
			if (typeof value === "boolean") return true;
			throw `${path} must be a boolean`;
		case Object:
			if (typeof value === "object" && value !== null) return true;
			throw `${path} must be a object`;
	}

	if (typeof type === "object") {
		if (Array.isArray(type)) {
			if (!Array.isArray(value)) throw `${path} must be an array`;
			if (!type.length) return true; // type array didn't specify any type

			return value.every((val, i) => instanceOf(type[0], val, { path: `${path}[${i}]`, optional }));
		}
		if (type?.constructor?.name != "Object") {
			if (type instanceof Tuple) {
				if (
					(<Tuple>type).types.some((x) => {
						try {
							return instanceOf(x, value, { path, optional });
						} catch (error) {
							return false;
						}
					})
				) {
					return true;
				}
				throw `${path} must be one of ${type.types}`;
			}
			if (type instanceof Email) {
				if ((<Email>type).check()) return true;
				throw `${path} is not a valid E-Mail`;
			}
			if (value instanceof type) return true;
			throw `${path} must be an instance of ${type}`;
		}
		if (typeof value !== "object") throw `${path} must be a object`;

		const diff = Object.keys(value).missing(
			Object.keys(type).map((x) => (x.startsWith(OPTIONAL_PREFIX) ? x.slice(OPTIONAL_PREFIX.length) : x))
		);

		if (diff.length) throw `Unkown key ${diff}`;

		return Object.keys(type).every((key) => {
			let newKey = key;
			const OPTIONAL = key.startsWith(OPTIONAL_PREFIX);
			if (OPTIONAL) newKey = newKey.slice(OPTIONAL_PREFIX.length);

			return instanceOf(type[key], value[newKey], {
				path: `${path}.${newKey}`,
				optional: OPTIONAL,
			});
		});
	} else if (typeof type === "number" || typeof type === "string" || typeof type === "boolean") {
		if (value === type) return true;
		throw `${path} must be ${value}`;
	} else if (typeof type === "bigint") {
		if (BigInt(value) === type) return true;
		throw `${path} must be ${value}`;
	}

	return type == value;
}