Validation URL Shortener Microservice

Hello please i have a problem the last condition in my code is not working and invalid inserts are being made to the database when it should not.
Last condition : " If you pass an invalid URL that doesn’t follow the valid http://www.example.com format, the JSON response will contain { error: 'invalid url' }"
Please help me thank you.

require('dotenv').config();
const express = require('express');
const mongoose = require("mongoose");
const cors = require('cors');
const app = express();

// Basic Configuration
const port = process.env.PORT || 3000;

app.use(cors());

app.use('/public', express.static(`${process.cwd()}/public`));

app.get('/', function(req, res) {
  res.sendFile(process.cwd() + '/views/index.html');
});

// Your first API endpoint
app.get('/api/hello', function(req, res) {
  res.json({ greeting: 'hello API' });
});

app.listen(port, function() {
  console.log(`Listening on port ${port}`);
});

/*Database Connection*/
let uri = 'mongodb+srv://mon-project-wee:xxxx@monprojectwee.brqps.mongodb.net/xxx?retryWrites=true&w=majority'
mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true });

let urlSchema = new mongoose.Schema({
  original : {type: String, required: true},
  short: Number
})

let Url = mongoose.model('Url', urlSchema)

let bodyParser = require('body-parser')
let responseObject = {}
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
  }
  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/:input', (request, response) => {
  let input = request.params.input
  Url.findOne({short: input}, (error, result) => {
    if(!error && result != undefined){
      response.redirect(result.original)
    }else{
      response.json('URL not Found')
    }
  })
})

Sidenote
process.cwd() is not the right call imho. cwd() is the directory you execute node from. If you execute node ./path/to/server.js the script will probably fail…

Normally you want to use the variable __dirname

@WEEYDE What exactly is incorrect? Seems to follow the rules.

Your regex does not account for the invalid URL being passed ftp:/john-doe.org

let inputUrl = 'ftp:/john-doe.org';
let urlRegex = new RegExp(
  /[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)?/gi
);

console.log(!inputUrl.match(urlRegex)); // false

You can look at the tests.

So far the problem has not always been resolved.

Did you understand why the URL test isn’t working?

Anyway, the only invalid URL that is tested against is the ftp one, so you can just check the protocol and return the invalid response for URLs using that protocol

new URL('ftp:/john-doe.org').protocol
// 'ftp:'
1 Like

After replacing the syntax three of the four conditions are false.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.