Runner Postman with list - postman

I'm struggling to make my runner works.
Here the raw body of my method
{
"itemList": [
"{{items}}"
],
"storeType": 7,
"storeNum": [
"{{store}}"
]
}
i want to use a csv file containing line like this
store,items
115,"1097456,855591,716027"
The issue is, i don't know how to format the string i got from the file "1097456,855591,716027" to make my body works.
My body should look's like that:
{
"itemList": [1097456,855591,716027],
"storeType": 7,
"storeNum": [115]
}
If i remove the double quote from "{{ITEMS}}" i got a json error.
I'm lost and start to think this is impossible :(
Any help is welcome.
Thanks

Step 1: Change the request body
{
"itemList": {{items}},
"storeType": 7,
"storeNum": {{stores}}
}
Step 2: Write code in Pre-Request tab to convert String to a list of number.
let stores = readInput("store");
let items = readInput("item");
pm.environment.set("stores", JSON.stringify(stores));
pm.environment.set("items", JSON.stringify(items));
function readInput(header){
let input = pm.iterationData.get(header).toString();
let fields = [];
if (input.includes(",")) {
inputs = input.split(",");
fields = inputs.map(x => parseInt(x));
} else {
fields.push(parseInt(input));
}
return fields;
}
CSV file:
Sample request body:

Related

Postman = To assert that the array in the response body contains a string value in all its elements

I'm new to Postman. My Postman is failing to match test criteria. Could anyone please help! It is returning true even if there is no match
pm.test('Hourly metrics report generated to only 1 building', () => {
_.each(jsonData.attributes, (item) => {
pm.expect(item.building_ref_id).to.include('Mounting_View-EN-1-Internal_Alpha')
})
})
{
"id": "423317",
"type": "space",
"attributes": {
"name": "RM_05_030",
"space_ref_id": "RM_05_030",
"building_ref_id": "80_Fen",
"floor_ref_id": "5"
}
}
I assume that the code above is incomplete and that the response is actually and array of objects and that jsonData contains the parsed response body as a JavaScript array of objects.
The _.each() function takes an array as its first parameter, so you should not pass jsonData.attributes. This is the reason that your test passed; jsonData.attributes isn't an array, your callback will never get executed and no failing assertions means a succeeding test.
You can iterate over jsonData and assert that every item has a nested attribute item.attributes.building_ref_id containing your string:
jsonData = pm.response.json()
pm.test('Hourly metrics report generated to only 1 building', () => {
_.each(jsonData, (item) => {
pm.expect(item.attributes.building_ref_id).to.include('Mounting_View-EN-1-Internal_Alpha')
})
})

How to properly set an API call in QML using XMLHttpRequest

I am building a small weather API as exercise to use QML and properly operate an API call using OpenWeather and you can see there a typical API response.
The problem I am having is that I can't get the API call to work. After setting a minimal example with some cities that you can see below, right next to the city it should appear the symbol of the weather, but it does not happen. The list of the icon can be found here. Source code of the MVE can be found here for completeness.
The error from the compiler: qrc:/main.qml:282: SyntaxError: JSON.parse: Parse error
This is what is happening
This is what is expected
Typical API JSON response can be found both here and below:
{
"coord": {
"lon": -122.08,
"lat": 37.39
},
"weather": [
{
"id": 800,
"main": "Clear",
"description": "clear sky",
"icon": "01d"
}
],
"base": "stations",
"main": {
"temp": 282.55,
"feels_like": 281.86,
"temp_min": 280.37,
"temp_max": 284.26,
"pressure": 1023,
"humidity": 100
},
"visibility": 16093,
"wind": {
"speed": 1.5,
"deg": 350
},
"clouds": {
"all": 1
},
"dt": 1560350645,
"sys": {
"type": 1,
"id": 5122,
"message": 0.0139,
"country": "US",
"sunrise": 1560343627,
"sunset": 1560396563
},
"timezone": -25200,
"id": 420006353,
"name": "Mountain View",
"cod": 200
}
Below a snippet of code related to the API call:
main.qml
// Create the API getcondition to get JSON data of weather
function getCondition(location, index) {
var res
var url = "api.openweathermap.org/data/2.5/weather?id={city id}&appid={your api key}"
var doc = new XMLHttpRequest()
// parse JSON data and put code result into codeList
doc.onreadystatechange = function() {
if(doc.readyState === XMLHttpRequest.DONE) {
res = doc.responseText
// parse data
var obj = JSON.parse(res) // <-- Error Here
if(typeof(obj) == 'object') {
if(obj.hasOwnProperty('query')) {
var ch = onj.query.results.channel
var item = ch.item
codeList[index] = item.condition["code"]
}
}
}
}
doc.open('GET', url, true)
doc.send()
}
In order to solve this problem I consulted several sources, first of all : official documentation and the related function. I believe it is correctly set, but I added the reference for completeness.
Also I came across this one which explained how to simply apply XMLHttpRequest.
Also I dug more into the problem to find a solution and also consulted this one which also explained how to apply the JSON parsing function. But still something is not correct.
Thanks for pointing in the right direction for solving this problem.
Below the answer to my question. I was not reading properly the JSON file and after console logging the problem the solution is below. code was correct from beginning, only the response needed to be reviewed properly and in great detail being the JSON response a bit confusing:
function getCondition() {
var request = new XMLHttpRequest()
request.open('GET', 'http://api.openweathermap.org/data/2.5/weather?q=London&units=metric&appid=key', true);
request.onreadystatechange = function() {
if (request.readyState === XMLHttpRequest.DONE) {
if (request.status && request.status === 200) {
console.log("response", request.responseText)
var result = JSON.parse(request.responseText)
} else {
console.log("HTTP:", request.status, request.statusText)
}
}
}
request.send()
}
Hope that helps!
In your code, your url shows this: "api.openweathermap.org/data/2.5/weather?id={city id}&appid={your api key}". You need to replace {city id} and {your api key} with real values.
You can solve it by providing an actual city ID and API key in your request URL

Flutter upload list to Google Firestore

I would like to add a list from my flutter test app to my Google Firestore.
This is my method, which adds all the data:
void postToFireStore(
{String mediaUrl, String location, String description}) {
var reference = Firestore.instance.collection('insta_posts');
reference.add({
"marked_friends": [chipstuete.toString()],
"username": currentUserModel.username,
"location": location,
"likes": {},
"mediaUrl": mediaUrl,
"description": description,
"ownerId": googleSignIn.currentUser.id,
"timestamp": new DateTime.now().toString(),
}).then((DocumentReference doc) {
String docId = doc.documentID;
reference.document(docId).updateData({"postId": docId});
});
}
Everything is working fine, expect the list "marked_friends"...
The list "chipstuete" has multiple strings:
[Martin Seubert, Lena Hessler, Vivien Jones]
But my Firestore looks like that:
At the moment the whole list is stored in marked_friends[0]...
What do I need to change, that every entry of my list "chipstuete" is stored in a seperate field of my array "marked_friends" in Firestore?
Best regards!
You have to add a method in your AppProfile class that serializes it to a List.
So in your AppProfile class:
class AppProfile {
... // Whatever fields/methods you have
// Add this method
List<String> getFriendList() {
// Somehow implement it so it returns a List<String> based on your fields
return ['name1','name2','name3'];
}
}
Then you can do
"marked_friends": chipstuete.getFriendList(),
I have the solution.
Like SwiftingDuster said, I needed a new method which serializes it to a List:
List<String> toList() {
chipstuete.forEach((item) {
newtuete.add(item.toString());
});
return newtuete.toList();
}
After that I just call toList() in my postToFirestore() Method and add "marked_friends": newtuete. Thats it!

Extracting global variable value from brackets

I am sending a POST request, which I'm getting in the response an attribute named "value" that its value is a number with brackets. I need to use the number without the brackets for my next API request.
Here is what I get in the response of my request:
{
"additionalAttributes": {
"map": [
{
"key": "RESULT_IDS",
"value": "[26913648997439042205288611421953968843]"
}
]
}
Here is what I've updated in Tests tab of the request in order to save it as a global variable:
tests["Status code is 200"] = responseCode.code === 200;
if (responseCode.code === 200) {
try {
var campaign_data = JSON.parse(responseBody),
campaignValue = campaign_data.additionalAttributes.map[0].value;
} catch(e) {
console.log(e);
}
postman.setGlobalVariable("campaignValue",campaignValue);
}
Can you explain please how can I have the value 26913648997439042205288611421953968843 without the brackets saved into a global variable?
Many thanks.
You can use the integrated lodash lib of the Postman sandbox:
var campaignValueRaw = campaign_data.additionalAttributes.map[0].value;
var campaignValue = _.trimRight(_.trimLeft(campaignValueRaw, '[') , ']');

Mongo database: search for text escaping some characters

I'm looking for a way to search text on my MongoDB escaping some characters.
For example:
In the collection contacts there is a document with "john.doe" in field name
{
_id: ID
...
name : "john.doe",
...
}
("john.doe" could be "j.ohndoe" or "j.o.h.n.d.o.e" or "jo.hn.do.e", you name it)
I want to find it searching for "johndoe", not only "john.doe" (ignoring "."). It would be great to use directly findOne.
Is there a way to do this?
Thank you very much :)
I don't think it's possible using purely MongoDB queries. However, you can you MongoDB map reduce to get filtered documents or perform such actions on client side. I know it will not be an elegant solution but at least will work.
Please see https://docs.mongodb.org/manual/core/map-reduce/
Example
function findByKey(key)
{
var keys =
db.contacts.mapReduce(function(){
var re = /\./igm;
var txt = this.name.replace(re,"");
var re = new RegExp(u_name);
if(re.exec(txt)!= null)
{
emit(1, this._id);
}
}, function(k, v){
return {keys: v};
},
{
out:{inline:true},
scope: {u_name:key}
});
if(keys.results.length > 0)
{
var arKeys = keys.results[0].value.keys;
return db.contacts.find({_id:{$in: arKeys}});
}
else
{
return null;
}
};
var data = findByKey("john doe");
After running above script, variable data will hold all documents having "john doe" including j.ohn.doe or john.doe so ignoring all periods.