简体   繁体   中英

Making sequential rest calls using Javascript and Node

Before you read this please consider that I know the basics of Javascript and Node. But it appears that I need to write simple Javascript solution to help other guys with testing. Solution contains a number of JS scripts that are going to be executed in Jenkins with Node.

Most of the scripts are sending a rest call which are dependent on each other.

I'm using node requests modules to execute these calls.

So the problem I'm facing is asynchronous execution.

So let's imagine, we have one object that contains a dependent object inside.

parentObject = {'name': 'someName', 'id': 1, 'childObjects': [{'name': someName', 'id': 1},{'name': someName', 'id': 2}...]}

Both, parentObject and childObjects , have its own endpoint. So we can CRUD childObjects .

And here comes a problem. Based on childObject name I need to delete this object. I'm using the following code to do that:

var request = require('request');

...

const objectToPreserve = ['someName1','someName2'...]
var options = {'method': 'GET', 'url': baseUrl + '/childObject'+urlParam + '&parentObejctid=' + parentObjectId, 'headers': {'Authorization': token}};
    request(options,function(error,response){
        if (error) throw new Error(error);
        var childObjects = JSON.parse(response.body);
        for (i of childObjects) {
            var name = i.name;
            var childObjectId = i.id;
            if (objectToPreserve.indexOf(name) > -1 ) {
                console.log(name,' preserved')
            } else {
                var options = {'method': 'DELETE', 'url': baseUrl + '/childObject' + urlParam + '&id=' + childObjectId, 'headers': {'Authorization': token}};
                request(options,function(error,response){
                    if(error) throw new Error(error);
                    console.log(JSON.parse(response.statusCode));
                });
            }
        }
    })

After delete happens I need to update objectToPreserve with an additional attribute or put that code inside if (objectToPreserve.indexOf(name) > -1 ) {... block.

Also, childObject has its own childObject inside and after initial deletion and update I need to add attributes to that second level child object too.

The parentObject structure looks like:

parentObject
|-childObject1
||-childobject1.1
|-childObject2
||-childObject2.1

Due to the reason that parentObject can contain over 100 child objects, some delete requests are failing with 500 or 504 status code. That is why I would like to make these calls sequential.

Can someone help to resolve that and maybe explain for dummy how to rewrite that code with requests module?

Enclose the request callback function inside an async function so that it would wait for a success response or error before continuing.

 const request = require('request'); const objectToPreserve = ['someName1', 'someName2']; /** Async function which would return the response or throw an error from request endpoint */ const requestAsync = async(options) => { request(options, function(error, response) { if (error) { throw new Error(error); } return response; }); }; /** Main function */ const execute = async() => { const options = { 'method': 'GET', 'url': baseUrl + '/childObject' + urlParam + '&parentObejctid=' + parentObjectId, 'headers': { 'Authorization': token } }; const response = await requestAsync(options); const childObjects = JSON.parse(response.body); for (const i of childObjects) { const name = i.name; const childObjectId = i.id; if (objectToPreserve.indexOf(name) > -1) { console.log(name, ' preserved') } else { const deleteOptions = { 'method': 'DELETE', 'url': baseUrl + '/childObject' + urlParam + '&id=' + childObjectId, 'headers': { 'Authorization': token } }; const deleteResponse = await requestAsync(deleteOptions); console.log(JSON.parse(deleteResponse.statusCode)); } } } // Execute main function await execute();

I recommend that you use const and let instead of var for variable declaration, and also use another library such as axios instead of request since request is deprecated .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM