如何构建一个循环,为 postman 中的数组的每个值执行 POST

问题描述 投票:0回答:1

我必须执行 POST 来检索具有唯一 ID“queueCallManagerID”的所有关联数据。 我的queueCallManagerID 环境中有一个queueCallManagerID 数组。如何构建循环来执行环境中每个queueCallManagerID 值的请求。

Api to execute

Environment with required values

我能够手动生成预期的响应,但我对邮递员中的循环经验较少。

Expected response but for all queueCallManagerIDs

我必须解析结果来组织 mixmonFileName 列表。

这是我通过前脚本得到的最远的值,但它似乎没有将值作为数组读取。错误:“TypeError:queueCallManagerID.forEach 不是函数”

// Define authorization keys
const cKey1 = '12345;
const cKey2 = '6789';
const uKey = '8765';

// Retrieve the array of queueCallManagerIDs from the environment
const queueCallManagerID = pm.environment.get('queueCallManagerID');

// Loop through each queueCallManagerID value and send a POST request
queueCallManagerID.forEach(queueCallManagerID => {
    const requestBody = {
        "cKey1": cKey1,
        "cKey2": cKey2,
        "uKey": uKey,
        "queueCallManagerID": queueCallManagerID
    };

    // Send the POST request
    pm.sendRequest({
        url: 'https://api.fathomvoice.com/V2/queues/getInteraction/',
        method: 'POST',
        header: {
            'Content-Type': 'application/json'
        },
        body: {
            mode: 'raw',
            raw: JSON.stringify(requestBody)
        }
    }, function(err, res) {
        if (err) {
            console.error(err);
            return;
        }
        console.log(res);
        console.log("queueCallManagerID:", queueCallManagerID);
    });
});
arrays loops post environment-variables postman
1个回答
0
投票

Postman 的

Run Collection
shift()
JavaScript 将解决您的循环调用问题。

pm.environment.set("queueCallManagerID", ids.shift())

用于两次 POST 调用的模拟服务器。

另存为

server.js

const express = require('express');
const fs = require('fs');
const multer = require('multer')
const cors = require('cors');

const app = express();

// for form-data
const forms = multer();
app.use(forms.array()); 

app.use(cors());
const PORT = 3000;

// Function to generate random 5-digit number
function generateRandomNumber() {
    return Math.floor(10000 + Math.random() * 90000);
}

// Define GET endpoint for /data
app.post('/V2/queues/data', (req, res) => {
    fs.readFile('data.json', 'utf8', (err, data) => {
        if (err) {
            console.error('Error reading file:', err);
            res.status(500).send('Internal Server Error');
            return;
        }

        try {
            const jsonData = JSON.parse(data);
            
            res.json(jsonData);
        } catch (error) {
            console.error('Error parsing JSON:', error);
            res.status(500).send('Internal Server Error');
        }
    });
});

app.post('/V2/queues/getInteraction', (req, res) => {
    const { cKey1, cKey2, uKey, queueCallManagerID } = req.body;
    // Form data print
    console.log(`cKey1: ${cKey1}`);
    console.log(`cKey2: ${cKey2}`);
    console.log(`uKey: ${uKey}`);
    console.log(`queueCallManagerID: ${queueCallManagerID}`);
    fs.readFile('data-result.json', 'utf8', (err, data) => {
        if (err) {
            console.error('Error reading file:', err);
            res.status(500).send('Internal Server Error');
            return;
        }

        try {
            const jsonData = JSON.parse(data);

            // Generate random number
            const randomNumber = generateRandomNumber();
            jsonData.data.queueCDR.mixmonFileName = jsonData.data.queueCDR.mixmonFileName.replace(/\d{5}\.wav$/, randomNumber + '.wav');
            jsonData.data.queueCDR.queueCallManagerID = queueCallManagerID;
            res.json(jsonData);
        } catch (error) {
            console.error('Error parsing JSON:', error);
            res.status(500).send('Internal Server Error');
        }
    });
});

// Start the server
app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});

模拟响应数据

保存

data.json

{
    "count": 3386,
    "status": "Complete",
    "description": "",
    "data": [
        {
            "endTime": "2024-02-23 05:07:52",
            "queueCallManagerID": "79768757",
            "mixmonFileName": "con2526-797309501.wav"
            
        },
        {
            "endTime": "2024-02-23 05:08:18",
            "queueCallManagerID": "79766443",
            "mixmonFileName": "q-con2526-us1-vp-4008-1708664701.1269429.wav"
          
        },
        {
            "endTime": "2024-02-23 05:09:52",
            "queueCallManagerID": "79767811",
            "mixmonFileName": "con2526-797309502.wav"
            
        },
        {
            "endTime": "2024-02-23 05:10:18",
            "queueCallManagerID": "79761324",
            "mixmonFileName": "q-con2526-us1-vp-4008-1708664701.1234.wav"
          
        }
    ]
}

保存

data-result.json

{
    "status": "Complete",
    "description": "",
    "data": {
        "queueCDR": {
            "uKey": "1234",
            "queueCDRID": "79566979",
            "queueCallManagerID": "79566979",
            "queueID": "9576",
            "vbxName": "some name",
            "channel": "some channel",
            "uniqueID": "us1-vp-4055-1708356420.43542",
            "mixmonFileName": "q-con2526-us1-vp-4055-43542.wav"
        }
    }
}

安装依赖项

npm install express fs multer cors

运行模拟服务器

node server.js

邮递员零件

通过两次 POST 调用收集

#1 拨打 1

POST http://localhost:3000/V2/queues/data

Tests
选项卡

const jsonData = pm.response.json();
const queueCallManagerIDs = jsonData.data.map(item => item.queueCallManagerID);
pm.environment.set('queueCallManagerIDs', JSON.stringify(queueCallManagerIDs));
console.log("all data: " + pm.environment.get("queueCallManagerIDs"));

#2 拨打 2

POST http://localhost:3000/V2/queues/getInteraction

Pre-request Script
标签

let ids = JSON.parse(pm.environment.get("queueCallManagerIDs"));
console.log(ids);

pm.environment.set("queueCallManagerID", ids.shift())

pm.environment.set("queueCallManagerIDs", JSON.stringify(ids));

Body
标签

cKey1 : Key 1 - top secret 6789
cKey2 : Key 1 - key 2 - second key 6789
uKey : Key 1 - uKey - third key 8765
queueCallManagerID : {{queueCallManagerID}}

Tests
标签

const jsonData = pm.response.json();

console.log("queueCallManagerID: " + pm.environment.get("queueCallManagerID"));
console.log("mixmonFileName: " + jsonData.data.queueCDR.mixmonFileName);

let ids = JSON.parse(pm.environment.get("queueCallManagerIDs"));
if (ids.length > 0){
    postman.setNextRequest("Get Interaction A");
}

const mixmonFileName = jsonData.data.queueCDR.mixmonFileName;

pm.test('mixmonFileName length is greater than 0', function () {
    pm.expect(mixmonFileName.length).to.be.above(0);
});

运行集合

结果

此 POST 由数字

queueCallManagerIDs
数组调用。
http://localhost:3000/V2/queues/getInteraction

© www.soinside.com 2019 - 2024. All rights reserved.