update mongoose and change the validation url process

This commit is contained in:
unurled 2022-09-01 09:31:07 +02:00
parent fe1417851d
commit 4e7c327966
4 changed files with 34 additions and 7 deletions

2
.gitignore vendored
View file

@ -2,3 +2,5 @@
node_modules
package-lock.json
start.sh
yarn.lock
yarn-error.log

View file

@ -12,11 +12,11 @@
"dependencies": {
"dotenv": "^16.0.0",
"express": "^4.17.1",
"mongoose": "^6.0.5",
"mongoose": "^6.5.4",
"node-uri": "^1.1.1",
"prom-client": "^14.0.1",
"short-id": "^0.1.0-1",
"shortid": "^2.2.16",
"valid-url": "^1.0.9"
"shortid": "^2.2.16"
},
"devDependencies": {
"autoprefixer": "^10.4.0",

View file

@ -17,8 +17,10 @@ router.get('/:code', async (req, res) => {
})
if (url) {
// when valid we perform a redirect
console.log("Redirecting to: " + url.longUrl);
return res.redirect(url.longUrl)
} else {
console.log("Redirecting to Home.")
return res.sendFile(path.join(__dirname + `../../../public/index.html`))
// else return a not found 404 status
//return res.status(404).json('No URL Found')

View file

@ -1,7 +1,7 @@
require('dotenv').config()
// packages needed in this file
const express = require('express')
const validUrl = require('valid-url')
const uri = require('node-uri')
const shortid = require('shortid')
// creating express route handler
@ -16,13 +16,34 @@ const Url = require('../models/url')
// The API base Url endpoint
const baseUrl = process.env.BASEURL
function validUrl(url) {
let valid
try {
uri.checkHttpURL(url)
valid = true;
} catch {
valid = false;
}
if (!valid) {
try {
uri.checkHttpsURL(url)
valid = true;
} catch {
valid = false;
}
}
return valid;
}
router.post('/shorten', async (req, res) => {
const {
longUrl
} = req.body // destructure the longUrl from req.body.longUrl
// check base url if valid using the validUrl.isUri method
if (!validUrl.isUri(baseUrl)) {
if (!validUrl(baseUrl)) {
console.log("Invalid url " + baseUrl)
return res.status(401).json('Invalid base URL')
}
@ -30,7 +51,7 @@ router.post('/shorten', async (req, res) => {
const urlCode = shortid.generate()
// check long url if valid using the validUrl.isUri method
if (validUrl.isUri(longUrl)) {
if (validUrl(longUrl)) {
try {
/* The findOne() provides a match to only the subset of the documents
in the collection that match the query. In this case, before creating the short URL,
@ -42,6 +63,7 @@ router.post('/shorten', async (req, res) => {
// url exist and return the response
if (url) {
console.log("Return " + url)
res.json(url)
} else {
// join the generated short code the the base url
@ -55,6 +77,7 @@ router.post('/shorten', async (req, res) => {
date: new Date()
})
await url.save()
console.log("Return " + url)
res.json(url)
}
}