concept http request in category docker

appears as: HTTP request, HTTP requests, HTTP request
Bootstrapping Microservices with Docker, Kubernetes and Terraform

This is an excerpt from Manning's book Bootstrapping Microservices with Docker, Kubernetes and Terraform.

Listing 4.3 shows the changes we are making to the video streaming microservice. You can type these in yourself or load the file from example-2 into Visual Studio Code. Read through the code in listing 4.3 to see how we are forwarding the HTTP request for a video through to the new video storage microservice.

Listing 4.3 - Updated video streaming microservice that forwards the request to the video storage microservice (chapter-4/example-2/video-streaming/src/index.js)
const express = require("express");
const http = require("http"); #A
 
const app = express();
 
const PORT = process.env.PORT;
const VIDEO_STORAGE_HOST = process.env.VIDEO_STORAGE_HOST; #B
const VIDEO_STORAGE_PORT = parseInt(process.env.VIDEO_STORAGE_PORT); #B
 
app.get("/video", (req, res) => {
    const forwardRequest = http.request( #C
        {
            host: VIDEO_STORAGE_HOST, #D
            port: VIDEO_STORAGE_PORT, #D
            path:'/video?path=SampleVideo_1280x720_1mb.mp4', #E
            method: 'GET', #F
            headers: req.headers #G
        },
        forwardResponse => { #H
            res.writeHeader(forwardResponse.statusCode, forwardResponse.headers); #I
            forwardResponse.pipe(res); #J
        } #I
    ); #C
   
    req.pipe(forwardRequest); #L
});
 
app.listen(PORT, () => {
    console.log(`Microservice online`);
});
 

In listing 4.3 we are using the Node.js built-in http library to forward a HTTP request from one microservice to another. The response that is returned is then streamed to the client. The way this works might be difficult to understand, but don’t worry too much about it right now. In the next chapter, we’ll explore this more because communication between microservices is so important that it deserves its own chapter.

It’s extremely useful to be able to correlate strings of requests through your cluster. We do this by generating a unique correlation ID that we can attach to our requests to relate them to each other.

Listing 10.4 - Implementation of a retry function in JavaScript
async function sleep(timeMS) { #A
    return new Promise((resolve, reject) => { #B
        setTimeout( #C
            () => { resolve(); }, #D
            timeMS #E
        );
    }); #B
}
 
async function retry(operation, maxAttempts, waitTimeMS) { #F
 
    while (maxAttempts-- > 0) { #G
        try {
            const result = await operation(); #H
            return result; #I
        }
        catch (err) { #K
            lastError = err; #K
 
            if (maxAttempts >= 1) {
                await sleep(waitTimeMS); #L
            }
        }
    }
   
    throw lastError; #M
}