50 lines
2.5 KiB
TypeScript
50 lines
2.5 KiB
TypeScript
import Router, {Response} from 'express';
|
|
import {AuthenticatedRequest, hasRank} from "../middlewares/authenticate";
|
|
import {Rank} from "../../models/User";
|
|
import {validateSchema} from "../../util/validate";
|
|
import {shortUrl} from "../validations/linkValidation";
|
|
import {getLinkById, getLinkObjectById, listAllLinks, listLinksByUser, shortLink} from "../../controller/links";
|
|
|
|
const app = Router();
|
|
|
|
app.get("/", hasRank(Rank.TEAM_MEMBER), async (req: AuthenticatedRequest, res: Response) => {
|
|
res.json(await (req.user.rank === Rank.TEAM_MEMBER ? listLinksByUser(req.user.clientId) : listAllLinks()));
|
|
});
|
|
|
|
app.get("/:code", hasRank(Rank.TEAM_MEMBER), async (req: AuthenticatedRequest, res: Response) => {
|
|
if (!req.params.code) return res.status(400).json({message: "You need to provide the shorten id"});
|
|
|
|
const link = await getLinkById(req.params.code);
|
|
if (link == null) return res.status(404).json({message: "The provided link does not exist"});
|
|
|
|
if (!(req.user.rank === Rank.TEAM_MEMBER && link.clientId === req.user.clientId || req.user.rank === Rank.ADMIN))
|
|
return res.status(401).json({message: "You don't have the permission to show information about this link"});
|
|
|
|
res.json(link);
|
|
});
|
|
|
|
app.put("/", hasRank(Rank.TEAM_MEMBER), async (req: AuthenticatedRequest, res: Response) => {
|
|
const validationError = validateSchema(shortUrl, req.body);
|
|
if (validationError) return res.status(400).json({message: validationError});
|
|
|
|
if (await getLinkById(req.body.shortenedId) != null)
|
|
return res.status(409).json({message: "The provided id has already been taken"});
|
|
|
|
const link = await shortLink(req.body.originalUrl, req.body.shortenedId, req.user.clientId);
|
|
res.json({message: "Link successfully shortened", "shorten_url": link.shortenedId});
|
|
});
|
|
|
|
app.delete("/:code", hasRank(Rank.TEAM_MEMBER), async (req: AuthenticatedRequest, res: Response) => {
|
|
if (!req.params.code) return res.status(400).json({message: "You need to provide the shorten id"});
|
|
|
|
const link = await getLinkObjectById(req.params.code);
|
|
if (link == null) return res.status(404).json({message: "The provided link does not exist"});
|
|
|
|
if (!(req.user.rank === Rank.TEAM_MEMBER && link.clientId === req.user.clientId || req.user.rank === Rank.ADMIN))
|
|
return res.status(401).json({message: "You don't have the permission to delete this link"});
|
|
|
|
await link.delete();
|
|
res.json({message: "The provided link got successfully deleted"});
|
|
});
|
|
|
|
module.exports = app; |