summary refs log tree commit diff
path: root/api/src/routes/channels/#channel_id/invites.ts
blob: cc77df266647171972d22d42daa52ddc7ebaeff9 (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
import { Router, Request, Response } from "express";
import { HTTPError } from "lambert-server";

import { check } from "../../../util/instanceOf";
import { random } from "../../../util/RandomInviteID";

import { InviteCreateSchema } from "../../../schema/Invite";

import { getPermission, Channel, InviteModel, InviteCreateEvent, toObject, emitEvent } from "@fosscord/util";

const router: Router = Router();

router.post("/", check(InviteCreateSchema), async (req: Request, res: Response) => {
	const { user_id } = req;
	const { channel_id } = req.params;
	const channel = await Channel.findOneOrFail({ id: channel_id });

	if (!channel.guild_id) {
		throw new HTTPError("This channel doesn't exist", 404);
	}
	const { guild_id } = channel;

	const permission = await getPermission(user_id, guild_id);
	permission.hasThrow("CREATE_INSTANT_INVITE");

	const expires_at = new Date(req.body.max_age * 1000 + Date.now());

	const invite = {
		code: random(),
		temporary: req.body.temporary,
		uses: 0,
		max_uses: req.body.max_uses,
		max_age: req.body.max_age,
		expires_at,
		created_at: new Date(),
		guild_id,
		channel_id: channel_id,
		inviter_id: user_id
	};

	await new InviteModel(invite).save();

	await emitEvent({ event: "INVITE_CREATE", data: invite, guild_id } as InviteCreateEvent);
	res.status(201).send(invite);
});

router.get("/", async (req: Request, res: Response) => {
	const { user_id } = req;
	const { channel_id } = req.params;
	const channel = await Channel.findOneOrFail({ id: channel_id });

	if (!channel.guild_id) {
		throw new HTTPError("This channel doesn't exist", 404);
	}
	const { guild_id } = channel;
	const permission = await getPermission(user_id, guild_id);
	permission.hasThrow("MANAGE_CHANNELS");

	const invites = await Invite.find({ guild_id });

	res.status(200).send(invites);
});

export default router;