Smol changes

This commit is contained in:
oitsjustjose 2021-06-22 10:18:26 -05:00
commit 8a6645f560
9 changed files with 68 additions and 23 deletions

View file

@ -1,4 +1,5 @@
import { Request, Response } from "express";
import shortid from "shortid";
import URLs from "../../db/url.schema";
const isUrlValid = (url: string) => {
@ -8,11 +9,33 @@ const isUrlValid = (url: string) => {
export default async (req: Request, res: Response) => {
try {
if (!isUrlValid(req.body.url)) {
return res.status(422).send("INVALID URL");
return res.status(422).send({ error: "URL Provided is Invalid" });
}
// Validate that there isn't a conflict
if (req.body.slug) {
const conflict = await URLs.findById(req.body.slug);
if (!!conflict) {
return res
.status(409)
.send({ error: `Slug '${req.body.slug}' is already registered.` });
}
} else {
// Only return existing matches if the slug isn't custom
// Custom ones can continue to conflict :)
const existing = await URLs.findOne({
url: req.body.url,
isSlugCustom: false,
});
if (existing) {
return res.status(200).send(existing._id);
}
}
const url = new URLs();
url.url = req.body.url;
url.isSlugCustom = !!req.body.slug;
url._id = req.body.slug || shortid.generate();
await url.save();
return res.status(200).send(url._id);

View file

@ -7,11 +7,16 @@ const UrlSchema: Schema = new Schema({
default: shortid.generate,
},
url: String,
isSlugCustom: {
type: Boolean,
default: false,
},
});
export type UrlModel = Document & {
_id: string;
url: string;
isSlugCustom: boolean;
};
export default mongoose.model<UrlModel>("urls", UrlSchema, "urls");