URL Shortener Working but Failing 2/4 tests

My code is working perfectly when I test it myself but failing the automated tests. I think it’s because the automated tests are calling the GET request immediately after the POST and my MongoDB hasn’t update yet. I’m lost as to how to make sure my code waits for the new Site model to initialize before preforming the GET

'use strict';

var express = require('express');
var mongo = require('mongodb');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var cors = require('cors');
const dns = require('dns');
var app = express();

var port = process.env.PORT || 3000;

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


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

app.use('/public', express.static(process.cwd() + '/public'));

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

const Schema = mongoose.Schema;

var siteSchema = new mongoose.Schema({
  url : String,
  url_id : Number

var Site = mongoose.model('Site', siteSchema)
app.post("/api/shorturl/new", function (req, res) {
	var siteUrl = req.body.url
	var replacedUrl;
	const REPLACE_REGEX = /^https?:\/\//i;
	if (REPLACE_REGEX.test(siteUrl)) {
		var replacedUrl = siteUrl.replace(REPLACE_REGEX, '')
	} else {
		res.json({error: "invalid url"});
	dns.lookup(replacedUrl, (err,address) => {
	err ? 
	res.json({error: "invalid url"}) :
	Site.exists({url: siteUrl}, (err,result) => {
		if (err) { console.log(err) }
		if (result) {
			Site.findOne({url: siteUrl}, (err,data)=> {
				res.json({original_url: data.url, short_url: data.url_id});
				console.log(`${data.url_id} - ${data.url} *** returned`)
		} else {
			Site.countDocuments({}, (err,data) => { 
				var site = new Site({url: siteUrl, url_id: (data+1)})
				res.json({original_url: site.url, short_url: site.url_id});

app.get("/api/shorturl/:route", function (req, res) {
	var route = req.params.route;
	/^[0-9]*$/i.test(route) ?
	Site.findOne({url_id: route}, (err,result) => {
		if (err) { console.log(error) }
		result === undefined || !result ? 
		res.json({error: "No short URL found for the given input"}) : 
	}) :
	res.json({error: "Wrong format"});

app.listen(port, function () {
  console.log('Node.js listening ...');

Browser information:

Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:82.0) Gecko/20100101 Firefox/82.0.

Challenge: URL Shortener Microservice


Could you share your code in repl.it or glitch.com?

I found a problem though. You need to extract the host name from the URL so that the following routes work:

Test your URL verification process in isolation (unit test). I would make it a function.

Take a look at the URL module of nodejs: https://nodejs.org/api/url.html#url_the_whatwg_url_api.

Keep in mind the version of node you’re using (I’m using version 12.x).

Thank you, I was able to fix it by using the URL module before the dns lookup.

1 Like