URL Shortener Microservice - challenge

the code :


require('dotenv').config();
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const shortid = require('shortid');
const { connect } = require('mongodb');
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');
});



app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());


mongoose.connect(process.env.DB_URI, { useNewUrlParser: true, useUnifiedTopology: true });

mongoose.connection.on('connected', () => {
  console.log('connected');
  console.log(mongoose.connection.readyState); //logs 1
});

const schemaUrls = new mongoose.Schema({
  original_url: { type: String, required: true },
  short_url: { type: String, required: true }
});
const UrlsIds = mongoose.model('UrlsIds', schemaUrls);


// Your first API endpoint
app.post('/api/shorturl/new', function(req, res) {
  let id = shortid.generate();
  let clientReq = req.body.url;
  let regex = new RegExp(/[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)?/gi);

  
  if(!clientReq.match(regex)){
    res.json({ error: "invalid url" });
  } else {
    let urlsIdsNew = new UrlsIds({
      original_url: clientReq,
      short_url: id
    });

    urlsIdsNew.save((err, data) => {
      if(err){
        console.error(err);
      }
    });

    res.json({ original_url: clientReq, short_url: id });
  }

});


app.get('/api/shorturl/:inputShort', (req, res) => {
  let inputShort = req.params.inputShort;

  UrlsIds.findOne({ short_url: inputShort }, (err, result) => {
    if(!err && result != undefined){
      res.redirect(result.original_url);
    } else {
      res.json('invalid url');
    }
  });
});

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

does not pass the tests:

why???

To me only last test didn’t pass (because your regex is ignoring protocol).

somebody else to help me?

I change the code, but does not pass the third test. Why???

here is my code:


require('dotenv').config();
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const shortid = require('shortid');
const app = express();
const dns = require('dns');
const url = require('url'); 

// 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');
});



app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());


mongoose.connect(process.env.DB_URI, { useNewUrlParser: true, useUnifiedTopology: true });

mongoose.connection.on('connected', () => {
  console.log('connected');
  console.log(mongoose.connection.readyState); //logs 1
});

const schemaUrls = new mongoose.Schema({
  original_url: { type: String, required: true },
  short_url: { type: String, required: true }
});
const UrlsIds = mongoose.model('UrlsIds', schemaUrls);


// Your first API endpoint
app.post('/api/shorturl/new', function(req, res) {
  let id = shortid.generate();
  let clientReq = req.body.url;
  let clientURL = url.parse(clientReq);

  dns.lookup(clientURL.hostname, (error, address, family) => {
    if(!clientURL.hostname){
      res.json({ error: "invalid url" });
    } else {
      let urlsIdsNew = new UrlsIds({
        original_url: clientReq,
        short_url: id
      });
  
      urlsIdsNew.save((err, data) => {
        if(err){
          console.error(err);
        }
      });
  
      res.json({ original_url: clientReq, short_url: id });
    }
  });
});


app.get('/api/shorturl/:inputShort', (req, res) => {
  let inputShort = req.params.inputShort;

  UrlsIds.findOne({ short_url: inputShort }, (error, result) => {
    if(error){
      res.json('URL not found');
    } else {
      res.redirect(result.original_url);
    }
  });
});

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

someone to help me???

EDIT: The timeout of the tests suggest your app is freezing/failing, or getting stuck trying to complete something.

Top tip:

  • You will likely get more information from the browser console, as to why the test/s failed, when testing a URL.

Also, would you mind providing a link to your project code? It is difficult to get a full picture and debug, with only some code of a project.

this is the link to github

I cloned your project, added my database URI, and passed the tests.

It must be an issue with your setup. How are you hosting the app?

yes, I hosting with heroku

Can you see any errors in the browser console (devtools), when you submit?

Well…there you have it. The reason for the timeout.

This is simple debugging I expect you to be doing by this point. Remember, READ, then SEARCH, then ASK.

I assume the issue is with your database configuration. Potentially, it is blocking certain operations from certain IPs/domains. Some people experience issues, when they have uncommon characters in their database usernames/passwords.

I hope this helps

I still don’t know what to do

someone to help me???

I don’t know what to do anymore, someone???

Where are you hosting the DB?

If you are using MongoDB Atlas did you white-list the IPs? (you can set it to 0.0.0.0/0 to accept all IPs).

yes, i set it, but does not work

I went to your site and submitted a url…

It doesn’t work as intended. When I visit /api/shorturl/{shorturl} it returns a string “URL invalid”.
Are you sure your database is set up correctly? Can you confirm they’re actually being saved?

On a side note. I just finished this project myself. In the FCC example, if you try to store the exact same address twice, it will return the short url address already saved instead of creating another one. In your example, it returns a new short url every time.

I finished the challenge. I tried to push the solution with repl.it and works.