URL shortener microservice

Pankajashree R
Chingu
Published in
3 min readNov 27, 2017

This is the fourth API project on FreeCodeCamp and the first project that requires the use of MongoDB.

Creating MongoDB instance on cloud

mLab offers the best service for hosting our MongoDB online with its free plan of 500 MB which is more than sufficient for this project. To create a MongoDB instance on mLab, sign up, create a new database (I named it short-url), create a new collection (say links) and add a database user in order to get the link to connect to the hosted MongoDB using the node driver. The URL will be similar to this:

mongodb://<dbuser>:<dbpassword>@ds123456.mlab.com:13936/short-url

Store this URL as environment variable in the .env file:

MONGO_URL=”mongodb://<dbuser>:dbpassword>@ds123456.mlab.com:13936/short-url”;

Creating the API using NodeJS

I started with FCC’s boilerplate and installed the following additional modules:

mongodb, shortid, valid-url

mongodb is the official driver for NodeJS. shortid is a module for generating unique IDs for our links. valid-url , as the name suggests, is used for URL validation.

API routes

Route 1 — Generating short urls:

Use case 1 requires generating short URL, given the actual URL. For this purpose, I defined this route app.route(‘/new/:url(*)’) in which the :url(*) parameter will allow us to pass in properly formatted links as URL parameter without letting the express app get confused about :,/ , etc in the parameter.

First we need to check if the URL passed as a parameter is valid using valid-urlmodule:

if (validUrl.isUri(suspect)){console.log('Looks like an URI');} else {console.log('Not a URI');}

If it is a valid URL, generate a unique code using short-id module, insert it into our database and also send an appropriate JSON response:

let shortCode = shortid.generate();shortid.characters('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$@'); // to allow only alphanumeric codescollection.insert([newUrl]);et newUrl = { url: url, short: shortCode };                      res.json({
"original_url":url,
"short_url":host + shortCode
});

Before inserting a new entry into the database, we need to check if an entry exists for the corresponding URL using collection.findOne() method and if it does, then retrieve the existing short-url.

Route 2 — Redirecting from the short code

app.route(‘/:short’) is the route for redirecting the shortcode to the actual URL. It involves simple reading of the database and retrieving the document that matches the given code from the database and finally use res.redirect to the original URL:

collection.findOne({"short": short}, {"url": 1, "_id": 0}, (err, doc) => {
if (doc != null) {
res.redirect(doc.url);
} else {
res.json({ error: "Shortlink not found in the database." });
};
});

Demo

The app is live. Github repository is here.

This is a sample output:

--

--