Created the channels.ts routes

This commit is contained in:
Mathias Wagner 2023-11-11 19:23:12 +01:00
parent 82eb156712
commit 90f93a6a20
Signed by: Mathias
GPG Key ID: B8DC354B0A1F5B44

67
api/routes/channels.ts Normal file
View File

@ -0,0 +1,67 @@
import {Response, Router} from "express";
import {AuthenticatedRequest} from "../middlewares/authenticate";
import {canEditGuild} from "../../controller/discord";
import {getChannelById, listChannels} from "../../controller/channel";
import {validateSchema} from "../../util/validate";
import {patchChannel} from "../validations/channelValidation";
const app = Router();
const checkChannel = async (req: AuthenticatedRequest, res: Response) => {
if (!req.params.channelId) {
res.status(400).json({message: "Missing channelId parameter"});
return;
}
const channel = await getChannelById(req.params.channelId as string);
if (!channel) {
res.status(404).json({message: "Channel not found"});
return;
}
if (!await canEditGuild(req.user.refreshDate!, req.user.refreshToken, req.user.accessToken, channel.guildId.toString())) {
res.status(403).json({message: "You are not allowed to edit this guild"});
return;
}
return channel;
}
app.get("/", async (req: AuthenticatedRequest, res: Response) => {
if (!req.query.guildId)
return res.status(400).json({message: "Missing guildId query parameter"});
if (!await canEditGuild(req.user.refreshDate!, req.user.refreshToken, req.user.accessToken, req.query.guildId as string))
return res.status(403).json({message: "You are not allowed to edit this guild"});
res.json((await listChannels(req.query.guildId as string)).map(channel => ({
...channel.dataValues,
id: undefined, webhookToken: undefined, guildId: undefined
})));
});
app.delete("/:channelId", async (req: AuthenticatedRequest, res: Response) => {
const channel = await checkChannel(req, res);
if (!channel) return;
await channel.destroy();
res.json({message: "Channel deleted"});
});
app.patch("/:channelId", async (req: AuthenticatedRequest, res: Response) => {
let channel = await checkChannel(req, res);
if (!channel) return;
const validationError = validateSchema(patchChannel, req.body);
if (validationError) return res.status(400).json({message: validationError});
if (Object.keys(req.body).length === 0)
return res.status(400).json({message: "Please select at least one field to update"});
await channel.update(req.body);
res.json({message: "Channel updated"});
});
module.exports = app;