Color Generator: Middleware

I had been struggling with the architecture of my project. I knew I wanted a separate web API that was secured with an API key. Where I was sort of lost was in figuring out where to go from there.

I knew that I didn’t want my Vue app to talk directly to my API because I didn’t want to expose my API key. So my next thought was to route my API requests through Express.

I set about creating two Express routes, one for each API endpoint. This was easy enough. Both functions look almost the same, so here is the one for /generate-color:

app.get("/generate-color", function(req, res, next) {
    var options = {
        host: API_HOST,
        path: "/api/v1/color"
    };
    
    var request = https.get(options, function(response) {
        var bodyChunks = [];
        response.on("data", function(chunk) {
            bodyChunks.push(chunk);
            console.log(JSON.parse(chunk));
        }).on("end", function() {
            var body = Buffer.concat(bodyChunks);
            var parsed = JSON.parse(body);
            res.status(200).send({
                status: "success",
                message: "here is your color!",
                color: parsed.color
            });
            console.log(parsed);
        }).on("error", function(err) {
            console.log(err);
        });
    });

    request.on("error", function(e) {
        console.log(e.message);
    });
});

The code is fairly self contained, but there are a few things to note. First, API_HOST appears to come out of nowhere, but is actually stored in an environment variable. The dotenv package makes it nice and easy to use environment variables in a node project; you define your variables in a .env file, and these two magical lines make them available in your app code:

const dotenv = require("dotenv");
dotenv.config();

Currently, my API doesn’t implement authentication, but if it did, I would also have an API_KEY variable in my .env file.

Second, if you’re not familiar with how requests and responses work in node, this code may look a little odd. What is being pushed to the bodyChunks array? why is there a bodyChunks array in the first place?

As you may know, Node.js is event-based. That means that there is always an event loop running to check and see what events have taken place, if any. In this example, we can see three events being used: data, end, and error. We’ll zoom in on the data event. Whenever information is being passed from one place to another in Node, you are dealing with a Stream. A stream sends small chunks of information at a time, and when it does so, it emits a data event. In my code, we are listening for that data event, and when it happens, we are grabbing that chunk of data and we are pushing it to our bodyChunks array. We call it that because the array comprises the chunks of our response body from the server.

Once our stream sends its last chunk of information, it emits the end event. Then, it’s time to put all of our chunks together into a Buffer and turn it into something we can use: an object! That’s what we send back in our response.

Next, we’ll talk about how I set up my Vue client.

Leave a Reply

Your email address will not be published. Required fields are marked *