summary refs log tree commit diff
path: root/api/src/util/route.ts
blob: 1e2beb5d8d5c16e3da83b393fb43cfb72d568a50 (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
import { DiscordApiErrors, Event, EventData, getPermission, PermissionResolvable, Permissions, Webhook } from "@fosscord/util";
import { NextFunction, Request, Response } from "express";
import fs from "fs";
import path from "path";
import Ajv from "ajv";
import { AnyValidateFunction } from "ajv/dist/core";
import { FieldErrors } from "..";
import addFormats from "ajv-formats";

const SchemaPath = path.join(__dirname, "..", "..", "assets", "schemas.json");
const schemas = JSON.parse(fs.readFileSync(SchemaPath, { encoding: "utf8" }));
export const ajv = new Ajv({
	allErrors: true,
	parseDate: true,
	allowDate: true,
	schemas,
	messages: true,
	strict: true,
	strictRequired: true
});
addFormats(ajv);

declare global {
	namespace Express {
		interface Request {
			permission?: Permissions;
		}
	}
}

export type RouteSchema = string; // typescript interface name
export type RouteResponse = { status?: number; body?: RouteSchema; headers?: Record<string, string> };

export interface RouteOptions {
	permission?: PermissionResolvable;
	body?: RouteSchema;
	response?: RouteResponse;
	example?: {
		body?: any;
		path?: string;
		event?: EventData;
		headers?: Record<string, string>;
	};
}

export function route(opts: RouteOptions) {
	var validate: AnyValidateFunction<any>;
	if (opts.body) {
		// @ts-ignore
		validate = ajv.getSchema(opts.body);
		if (!validate) throw new Error(`Body schema ${opts.body} not found`);
	}

	return async (req: Request, res: Response, next: NextFunction) => {
		if (opts.permission) {
			const required = new Permissions(opts.permission);
			if (req.params.webhook_id) {
				const webhook = await Webhook.findOneOrFail({ id: req.params.webhook_id });
				req.params.channel_id = webhook.channel_id;
				req.params.guild_id = webhook.guild_id;
			}
			const permission = await getPermission(req.user_id, req.params.guild_id, req.params.channel_id);

			if (!permission.has(required)) {
				throw DiscordApiErrors.MISSING_PERMISSIONS.withParams(opts.permission as string);
			}

			if (validate) {
				const valid = validate(req.body);
				if (!valid) {
					const fields: Record<string, { code?: string; message: string }> = {};
					validate.errors?.forEach((x) => (fields[x.instancePath] = { code: x.keyword, message: x.message || "" }));
					throw FieldErrors(fields);
				}
			}
		}
		next();
	};
}