Skip to content

Instantly share code, notes, and snippets.

@muhsin-k
Created April 11, 2018 08:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save muhsin-k/e54a6182c63d2ce9ceea41eedcda1d71 to your computer and use it in GitHub Desktop.
Save muhsin-k/e54a6182c63d2ce9ceea41eedcda1d71 to your computer and use it in GitHub Desktop.
URL-Shortener
const mongoose = require("mongoose");
const validUrl = require("valid-url");
const UrlShorten = mongoose.model("UrlShorten");
const shortid = require("shortid");
const errorUrl='http://localhost/error';
module.exports = app => {
app.get("/api/item/:code", async (req, res) => {
const urlCode = req.params.code;
const item = await UrlShorten.findOne({ urlCode: urlCode });
if (item) {
return res.redirect(item.originalUrl);
} else {
return res.redirect(errorUrl);
}
});
app.post("/api/item", async (req, res) => {
const { originalUrl, shortBaseUrl } = req.body;
if (validUrl.isUri(shortBaseUrl)) {
} else {
return res
.status(401)
.json(
"Invalid Base Url"
);
}
const urlCode = shortid.generate();
const updatedAt = new Date();
if (validUrl.isUri(originalUrl)) {
try {
const item = await UrlShorten.findOne({ originalUrl: originalUrl });
if (item) {
res.status(200).json(item);
} else {
shortUrl = shortBaseUrl + "/" + urlCode;
const item = new UrlShorten({
originalUrl,
shortUrl,
urlCode,
updatedAt
});
await item.save();
res.status(200).json(item);
}
} catch (err) {
res.status(401).json("Invalid User Id");
}
} else {
return res
.status(401)
.json(
"Invalid Original Url"
);
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment