Storing Colors in MongoDB

Photo by Magda Ehlers from Pexels

I wanted to practice my database skills with this project, so I decided to incorporate a feature that logged each random color generated by a user request to a Mongo database. I chose MongoDB because my experience with relational databases is fairly limited, and I didn’t want to introduce too much complexity all at once. I knew I’d be comfortable (or at least something adjacent to comfortable) with Mongo’s documents.

This commit has the code I’ll be talking about in this post.

First, I had to install the correct driver from npm. I chose the official driver because it seemed like the obvious option for someone who’s never done this before. Next, I had to establish a connection between my app and Mongo. This part of the docs was very helpful to me. I instantiated a new MongoClient object as they instructed and then called client.connect():

client.connect(function(err, database) {
	assert.equal(null, err);
	console.log("Connected successfully to database server");

	app.listen(PORT, () => {
		console.log(`server running on port ${PORT}`);
	});
});

Initially, I hard-coded my PORT value, but eventually I wised up and installed dotenv.

I need to test and see if app.listen() needs to be inside the client.connect() callback. I put it there because I didn’t want my app to start until after the connection to the database had been made, but maybe that doesn’t matter. I’ll come back to that another day.

I was expecting to have to create a database and a collection in the shell before I could start coding, but it turns out you can run an insert command on a nonexistent collection in a nonexistent database and both the database and the collection will be created as soon as you insert the data. That’s handy.

My app has two get() handlers, one of which is for the endpoint that generates the random color. In addition to calling my generateColor() function, it takes the returned object and inserts it into the colors collection. Here’s what that get() looks like:

app.get("/api/v1/color", function handleRequest(req, res) {
	console.log("getting a request");
	var color = generateColor();
	db = client.db(dbName);
	var collection = db.collection("colors");
	collection.insertOne(color)
	res.status(200).send({
		success: "true",
		message: "color retrieved successfully",
		color
	});
});

Looking at the code now, I’m wishing that I used the return value of collection.insertOne() to inform what kind of response I sent to the user. According to the docs, the method returns a boolean value indicating the write concern, which indicates whether the insert command was successful. If I had continued with MongoDB, I’d go and change that now, but because I decided to switch to MySQL, it’ll have to wait.

Next up: retrieving the stored colors and serving them up to the user.

Let’s Get Colorful

colorful sequins in ROYGBIV order
Photo by Sharon McCutcheon from Pexels

The people who say you should be working on a personal side project are right and wrong at the same time. They’re wrong because it’s a bad practice to expect people to work a full time job and then do more work in their free time in order to be considered viable in the industry. They’re right because it’s what potential employers will always ask you about, particularly if your current full-time role is something they perceive as nontechnical, like teaching or managing.

I’ve always felt paralyzed by the prospect of coming up with an idea for a side project. I don’t have any business ideas. I don’t have any interest in business, period. And the problems in my life that could be improved by technology are usually things that require a small tool, usually something to make repetitive tasks easier.

I love making tools. I wilt in the oppressive doldrums of repetitive mundanity, and I don’t even mind if building and using the tool doesn’t save me time. Breaking even is a win as long as I’m taking on a challenge.

Another thing that sparks joy for me is thinking about how can I make this colorful? Life can be so boring. Where are the rainbow sprinkles? This was the inspiration for Roy, a tool that just makes coloring your Node.js stdout output a little bit easier.

function generateColor() {
	let r = Math.random();
	r = Math.floor(r * 256);
	let g = Math.random();
	g = Math.floor(g * 256);
	let b = Math.random();
	b = Math.floor(b * 256);
	let rString = r.toString(16).toUpperCase();
	let rHex = rString.length == 2 ? rString : `0${rString}`;
	let gString = g.toString(16).toUpperCase();
	let gHex = gString.length == 2 ? gString : `0${gString}`;
	let bString = b.toString(16).toUpperCase();
	let bHex = bString.length == 2 ? bString : `0${bString}`;
	let color = {
		rgb: {r, g, b},
		hex: `${rHex}${gHex}${bHex}`,
		timestamp: Date.now()
	}
	return client.db(dbName).collection("colors").insertOne(color);
}

Recently, a human I trust and respect suggested that I Work On A Personal Project. She was right, so I started wracking my brain about what I should make. I hate this stage because I JUST WANT TO MAKE THINGS! I don’t want to pull an idea out of thin air. So I decided on the simplest concept I could think of: a web app that just served up a random RGB color. And thus, an app was born.

This is it … this function is the whole idea. I’m going to create a web service and deploy it to increasingly complex environments and learn stuff. I’m also going to build a client because, well, I’m primarily a front-end dev right now. I should probably have a client.

Next step: Heroku.