Hi Coding Enthusiasts,
I’ve been working on the Url Shortener Microservice Project for the last 1 week. I tried almost everything from refactoring to debugging but not sure why it is not getting passed during the tests.
It is working fine and to me, the results look exactly the same.
Here’s the working app link - Urlshortener-by-nitesh
If you like to read the code, then please go ahead and feel free to find the bug:
server.js
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const app = express();
const connectDB = require('./db.js');
const ShortUrl = require('./models/ShortUrl.js');
const shortId = require('shortid');
const dns = require('dns');
const nodeUrl = require('url');
// Connect to MongoDB
connectDB();
// Init Middleware
app.use(express.json({ extended: false }));
// Middleware Function to parse form-data
const parseData = (req, res, next) => {
if (req.method === 'POST') {
const formData = {};
req.on('data', (data) => {
// Decode and parse data
const parsedData = decodeURIComponent(data).split('&');
for (let data of parsedData) {
decodedData = decodeURIComponent(data.replace(/\+/g, '%20'));
const [key, value] = decodedData.split('=');
// Accumulate submitted
// data in an object
formData[key] = value;
}
// Attach form data in request object
req.body = formData;
next();
});
} else {
next();
}
};
app.use(cors());
app.use('/public', express.static(`${process.cwd()}/public`));
app.get('/', (req, res) => {
res.sendFile(process.cwd() + '/views/index.html');
});
// Greeting API Endpoint
app.get('/api/hello', (req, res) => {
res.json({ greeting: 'hello API' });
});
// Send Original Url And Short Url;
// @route POST /api/shorturl
// @desc SEND Shorten URL
// @access Public
app.post('/api/shorturl', parseData, async (req, res) => {
// Get the form url
const url = req.body.url;
const urlId = shortId.generate();
const parsedUrl = nodeUrl.parse(url, true);
try {
if (parsedUrl.hostname !== null) {
dns.lookup(parsedUrl.hostname, { all: true }, async (err, addresses) => {
if (addresses === undefined || parsedUrl.hostname === 'localhost') {
return res.json({ error: 'Invalid url' });
} else {
let findUrl = await ShortUrl.findOne({
original_url: url,
});
if (findUrl) {
return res.json({
original_url: findUrl.original_url,
short_url: findUrl.short_url,
});
} else {
findUrl = new ShortUrl({
original_url: url,
short_url: urlId,
});
const result = await findUrl.save();
return res.json({
original_url: result.original_url,
short_url: result.short_url,
});
}
}
});
}
// return error if the URL is not valid
else {
return res.json({ error: 'Invalid Url' });
}
} catch (err) {
console.error(err.message);
res.status(500).send('Server Failed to Respond!');
}
});
app.get('/api/shorturl/:short_url', async (req, res) => {
try {
const shortUrl = await ShortUrl.findOne({
short_url: req.params.short_url,
});
if (shortUrl) {
return res.redirect(shortUrl.original_url);
} else {
return res.status(404).send('No Url Found');
}
} catch (err) {
console.error(err.message);
res.status(500).send('Server Failed to Respond!');
}
});
app.get('/test', (req, res) => {
res.redirect('http://localhost:5000/?v');
});
// Basic Configuration
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`Server Started on the PORT ${PORT}`);
});
ShortUrl.js MongoDB Model
const mongoose = require('mongoose');
const { Schema } = mongoose;
const ShortUrlSchema = new Schema({
original_url: {
type: String,
required: true,
},
short_url: {
type: String,
required: true,
unique: true,
},
date: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model('ShortUrl', ShortUrlSchema);
Please let me know what am I doing wrong?
Best Regards,
Nitesh