diff --git a/api/routes/links.ts b/api/routes/links.ts new file mode 100644 index 0000000..f75cd8d --- /dev/null +++ b/api/routes/links.ts @@ -0,0 +1,21 @@ +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 {ShortenedLink} from "../../models/ShortenedLink"; + +const app = Router(); + +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 ShortenedLink.findOne({shortenedId: req.body.shortenedId}) != null) + return res.status(409).json({message: "The provided id has already been taken"}); + + const link = await ShortenedLink.create({originalUrl: req.body.originalUrl, shortenedId: req.body.shortenedId, clientId: req.user.clientId}); + res.json({message: "Link successfully shortened", "shorten_url": link.shortenedId}); +}); + +module.exports = app; \ No newline at end of file