Added the Sheepstar API to the Archive
This commit is contained in:
51
SheepstarAPIV1/routes/link.js
Normal file
51
SheepstarAPIV1/routes/link.js
Normal file
@ -0,0 +1,51 @@
|
||||
const app = require('express').Router();
|
||||
const crypto = require("crypto");
|
||||
const checkPermission = require("../middlewares/checkPermission");
|
||||
const ShortenedLink = require("../models/ShortenedLink");
|
||||
const linkValidation = require("../validation/linkValidation");
|
||||
|
||||
app.put("/", checkPermission("url.create"), async (req, res) => {
|
||||
// Validate request
|
||||
const {error} = linkValidation.short.validate(req.body);
|
||||
if (error) return res.status(400).json({message: error.details[0].message});
|
||||
|
||||
// Set optional fields
|
||||
req.body.shorten_url = req.body.custom_url || crypto.randomBytes(3).toString('hex');
|
||||
|
||||
// Check if shorten url exists
|
||||
const {count} = await ShortenedLink.findAndCountAll({where: {shorten_url: req.body.shorten_url}});
|
||||
if (count === 1) return res.status(400).json({message: "URL already exists"});
|
||||
|
||||
// Create the link
|
||||
await ShortenedLink.create(req.body);
|
||||
|
||||
// Return the response
|
||||
res.status(200).json({message: "Link successfully created", "shorten_url": req.body.shorten_url});
|
||||
});
|
||||
|
||||
app.delete("/:code", checkPermission("url.delete"), async (req, res) => {
|
||||
if (!req.params.code) return res.status(400).json({message: "You need to provide the shorten url code"});
|
||||
|
||||
// Search for the link
|
||||
const link = await ShortenedLink.findOne({where: {shorten_url: req.params.code}});
|
||||
if (link) {
|
||||
// Destroy the link
|
||||
await ShortenedLink.destroy({where: {shorten_url: req.params.code}});
|
||||
|
||||
// Return response
|
||||
res.status(200).json({message: "Link successfully deleted"});
|
||||
} else res.status(404).json({message: "Link not found"});
|
||||
});
|
||||
|
||||
app.get("/:code", checkPermission("url.info"), async (req, res) => {
|
||||
if (!req.params.code) return res.status(400).json({message: "You need to provide the shorten url code"});
|
||||
|
||||
// Search the link
|
||||
const link = await ShortenedLink.findOne({where: {shorten_url: req.params.code}});
|
||||
if (link) {
|
||||
// Return response
|
||||
res.status(200).json(link);
|
||||
} else res.status(404).json({message: "Link not found"});
|
||||
})
|
||||
|
||||
module.exports = app;
|
Reference in New Issue
Block a user