Url Shortener Project link: https://www.freecodecamp.org/learn/apis-and-microservices/apis-and-microservices-projects/url-shortener-microservice
I’ve passed first 3 tests succesfully, however 4th test which is checking the input format, doesn’t work. I’ve tried many options and I think it is working as well but couldn’t pass the tests. My code as follows;
app.post('/api/shorturl/', bodyParser.urlencoded({ extended: false }) , (request, response) => {
let inputUrl = request.body['url']
let urlRegex = new RegExp(/[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)?/gi)
if(!inputUrl.match(urlRegex)){
response.json({ error: 'invalid url' })
return
} else {
let a = inputUrl.includes('https://') ? 'https://' : 'ftp:/';
let b = inputUrl.includes('repl.co') ? inputUrl.split('repl.co')[1] : '';
console.log('/v exists: ', b)
inputUrl = inputUrl.replace(a,'')
console.log("a replace :", inputUrl)
inputUrl = inputUrl.replace(b,'')
console.log(inputUrl)
dns.lookup(inputUrl, (err) => {
if (err) // Handle error
response.json({ error: 'invalid url' })
else {
// Save it to database with generate short url
// add https:// or ftp:/ again
inputUrl = a.concat(inputUrl)
inputUrl = inputUrl.concat(b)
console.log(inputUrl)
responseObject['original_url'] = inputUrl
let inputShort = 1
Url.findOne({})
.sort({short: 'desc'})
.exec((error, result) => {
if(!error && result != undefined){
inputShort = result.short + 1
}
if(!error){
Url.findOneAndUpdate(
{original: inputUrl},
{original: inputUrl, short: inputShort},
{new: true, upsert: true },
(error, savedUrl)=> {
if(!error){
responseObject['short_url'] = savedUrl.short
response.json(responseObject)
}
}
)
}
})
}
})
}
})
app.get('/api/shorturl/:inputShort', (req, res) => {
let urlSearch = Url.findOne({short: req.params.inputShort}, (error, result) => {
if (!error && urlSearch != undefined) {
res.redirect(result.original)
} else {
res.json('URL NOT FOUND')
}
})
})
You can find the project in my Github account as well: GitHub - berkesenturk/Freecodeacademy-Url-Shortener-Microservice