response.map is not a function - arrays

I'm trying to loop a request to extract the ID's from a previous request. I followed the steps in this video https://www.youtube.com/watch?v=4wuvgX-egdc but i can't get it to work. As I see it the problem is that {} is not an array but I would like to search within "campaigns" which seems to be an array. (As you probably understand I'm new to this)
Here's the request I've sent and would like to loop through to extract the ID's that I wish to use in the next request. (there are several hundreds of ID's)
{
"campaigns": [
{
"id": 373894,
"name": "Benriach",
"created_at": "2022-01-21 13:37:34",
"sent_at": "2022-01-21 13:37:53",
"status": "sent",
"type": "text_message"
},
Here's the test that I'm trying to run.
const response = pm.response.json();
const campaignids = response.map (campaignid => campaigns.id);
console.log(campaignids);
pm.variables.set('campaignids', campaignids);
Here's how it looks>>
Screenshot
The end goal is to use Postman to extract campaign statistics from an e-mail marketing tool and then send it on into Google Data Studio where I want to create a dashboard for e-mail-campaigns using both data from the e-mail marketing tool as well as website data.

const campaignids = response.map (campaignid => campaigns.id); here is the problem
space between map (
const response = pm.response.json();
const campaignids = response.map(campaign => campaign.id);
console.log(campaignids);
pm.variables.set('campaignids', campaignids);
and make sure response should be an array

Related

OCAPI Batch request to get all Orders after a Certain Date

I'm New to SFCC OCAPI. My purpose is to Export all Orders from "development.demandware.net" after certain date and this can happen Quite frequently like once in every 2 days. I'm currently using Python to achieve this using the endpoint "s/{{SITEID}}/dw/shop/v18_1/order_search". The problem is One call is getting me only 25 Records. Again i have change the query from dynamically to start from RecordNo 26 for the next call. So, If I have like 10,000 records, it makes upto 400 calls everytime the scirpt runs. The alternative options i'm aware of is:
OCAPI Batch requests
OCAPI Export job (Tried this, but haven't got enough knowledge to set this up)
So, I'd like to know if my purposed is achievable using the batch request. I tried to do this using the documentation. And, the response was 200 with no response body using the below code.
url = f"https://{DOMAIN}/s/-/dw/batch"
url_param = {'client_id': CLIENT_ID}
header = {'Authorization': 'Bearer ' + token,
'Origin': f'https://{DOMAIN}',
'Content-Type': 'multipart/mixed;boundary=23dh3f9f4',
'x-dw-http-method': 'POST',
'x-dw-resource-path': 's/{{SITEID}}/dw/shop/v18_8/order_search'}
body = """
{
"query" :
{
"filtered_query": {
"query": { "match_all_query": {} },
"filter": {
"range_filter": {
"field": "creation_date",
"from": "%s",
"from_inclusive": true
}
}
}
},
"select" : "(**)",
"sorts": [{
"field": "order_no",
"sort_order": "asc"
}],
"start": %s
}""" %(RETRIVE_RECORDS_FROM, startRecordFrom)
response = requests.post(url, params = url_param, headers = header, data = body)
My code doesn't have a x-dw-content-id as the above is an initial request. If its possible to achieve my purpose,
how should my sub-request looks like.?
And after that how do i retrieve the data of my request.? is there any endpoint i should use to get the batch results.?
I maybe asking for too much information. But, i couldn't find much information about this online so had to ask every question i have in one post.
My question might look similar to this question "Salesforce Commerce Cloud/Demandware - OCAPI query orders by date range", But I'm looking for information about batch requests and also to reduce the number of API calls.
Thanks in advance.

Turn JS Object into FormData before submitting the data in Server with React

So let's say we do have this object that has an array on it, also includes some files and other types.
const state = {
"name": "Coffe",
"description": "..."
"visibilty": true,
"tags": ["Chill", "Not Healthy"],
"photos": [File, File] // those are File objects from upload
}
So because we are sending images we need to convert all the fields into form data when we send it on the server and I don't know something that works also with the complexity of the object when it also includes an array.

what is the most efficient way of making multiple APIs calls in ReactJS?

what is the most efficient way of making multiple APIs calls in ReactJS?
I have one API (say API 1) which give me DataID.
passing this DataID I need to call another API (say API 2) which will give me list of vehiclesId. like calling Get ../api/{DataID}/vehicles/ gives below
{
"vehicleIds": [
603285889,
1328361472,
1333092761,
1595876995,
799206723
]
}
By Passing DataID and VehicleID to another API (say API 3) I will get Vehicle details along with DealerId. Like calling Get ../api/{DataId}/vehicles/{VehicleId} gives below
{
"vehicleId": 2063928446,
"year": 2004,
"make": "MINI",
"model": "Cooper",
"dealerId": 1508315732
}
Now passing DataId and DealerId to another API (say API 4) I will get Dealer Name .
Like calling Get ../api/{DataId}/dealers/{DealerId} gives below
{
"dealerId": 1508315732,
"name": "Bob's Cars"
}
Now what is the most efficient ways to make multiple API calls to retrieves all vehicles and dealers for that DataID ?
Any pointers will be helpful.
You could store intermediates ids using useState, with an init value of null, then use something like
const [dataId, setDataId] = useState<number>(null);
// this effect will be triggered on component mount
useEffect(() => {
// launch request to get dataId, then store it into the component state
fetch(...).then(setDataId);
}, []); // notice the empty dependencies array
// each time dataId changes, this effect will be triggered
useEffect(() => {
if(!!dataId) {
fetch(...).then(...); // request using dataId value to get other values
}
}, [dataId]);
But this could grow in size and become hard to maintain I guess. I would suggest to consider 3rd party libraries like the awesome react-query to handle your server state. To perform dependent queries with react-query : https://react-query.tanstack.com/guides/dependent-queries

Getting shareable link to document in react app

I am currently making an app that generates Itineraries and I am able to convert the html to pdf using PDFjs using something like this:
var doc = new jsPDF();
doc.fromHTML(html);
doc.save("YourItinerary.pdf");
How should I proceed about making a shareable link to this pdf on client-side preferably using an API such as Google Drive?
Getting the shareable link would be to get the webViewLink which you can try by passing webViewLink as parameter in the 'fields' property in Files.get. This returns a link you can open in any browser. However, you also have to deal with permissions.
To make the webViewLink (your shareable link) work for anyone you can use in Permissions.create:
{
"role": "writer",
"type": "anyone",
}
To make the webViewLink available to certain users only you'll have a request body like:
{
"role": "writer",
"type": "user",
"emailAddress": "someuser#gmail.com"
}

GMail v1 API Users.messages results differ from Web UI on logical AND/OR

I'm using the following query:
No Man's Sky
I get different results from the Web UI compared with the API Explorer and my C# application.
GMail Web UI
Note, conversation view is disabled:
If I enable conversation view, I get 9 threads returned by the Web UI; using the thread API, I get 7 threads.
API Explorer at https://developers.google.com/gmail/api/v1/reference/users/messages/list:
{
"messages": [
{
"id": "15686dcf7989e60f"
},
{
"id": "1566bce4412a439d"
},
{
"id": "156327e51b979f48"
},
{
"id": "1560f0caf9297ab9"
},
{
"id": "155f01dba1c3ad77"
},
{
"id": "1538bce006a95a84"
},
{
"id": "15342e9d99b4d3f6"
}
]
}
I see the same results as the API explorer in my C# application. There seems to be a disconnect here between the API and Web UI. The Web UI returns 10 results, which the API returns only 7 of those 10 (I have verified that they're a subset of the 10 manually).
UPDATE:
It turns out that the API treats the query as a literal. Surrounding the query in the Web UI with quotation marks gives the same results as the API.
This does leave the question of how to replicate the original search using the API; does one have to run 3 queries and then take only the results returned in all 3? When you start getting into complex queries that becomes a bit of a parsing chore.
UPDATE 2
I've tried to replicate the Web UI results by running the 3 ANDed terms individually and then pulling results where the message ID is the result set of all 3 queries and I get the same 7 results as the API call.
Code used to test:
var service = GMailServiceManager.Instance.Service;
var resultsNo = GMailUtils.GetItems(service, null, "No", true);
var resultsMans = GMailUtils.GetItems(service, null, "Man's", true);
var resultsSky = GMailUtils.GetItems(service, null, "Sky", true);
var anded = from nos in resultsNo.Items
from manses in resultsMans.Items
from skys in resultsSky.Items
where nos.Id == manses.Id && nos.Id == skys.Id
select nos.Id;
GMailUtils.GetItems() simply handles batching of the API requests and some other app-specific routines. It uses the following to retrieve each group of items in the batch:
UsersResource.MessagesResource.ListRequest request = service.Users.Messages.List("me");
request.Q = search;
request.Fields = "messages(id),nextPageToken";
request.PageToken = pageToken;
// Logging and batching here
...
request.Execute();
...
I now have no idea how the Web UI comes up with the other hits; the hit highlighting is on www.no-mans-sky.com in two instances (they're in the same thread):
The other hits on No Man and Sky individually in an e-mail (note not Man's).
Update 3
Going back to the Web UI I decided to do a little testing on the search term Man's.
In the web UI, I get several hundred hits:
For "Man's" I get 11 hits:
The API matches the quoted Web UI:
{
"messages": [
{
"id": "15686dcf7989e60f"
},
{
"id": "1566bce4412a439d"
},
{
"id": "156327e51b979f48"
},
{
"id": "1560f0caf9297ab9"
},
{
"id": "155f01dba1c3ad77"
},
{
"id": "1538bce006a95a84"
},
{
"id": "15342e9d99b4d3f6"
},
{
"id": "13da4a6d7a4159b2"
},
{
"id": "13da4a502eca7dff"
},
{
"id": "12e70fbf3d655ac8"
},
{
"id": "1278adc3ed72f6a8"
}
]
}
Based on this it would appear that the API's query is treated as a string literal rather than Web-UI-style query. Seems like a bug to me, as I cannot find a way to reproduce the Web UI's results using the API.
I tried it with my own Gmail, and I observed that some emails are found in a single thread.
Here is my example:
I used the word time tracker as my subject, and the Gmail UI gives me a result of 4 emails. But if you count the total results, it gives me a total of 12 results. 6 from A, 3 from B, 2 from C and 1 email from D.
So if I use the request
GET https://www.googleapis.com/gmail/v1/users/example%40google.com/messages?q=subject%3A(time+tracker)&fields=messages(id%2CthreadId)&key={YOUR_API_KEY}
or the Try it part in the Gmail API,
It will give me a result of 12 IDs like in the GMail UI.
Looking at the illustration above, you will notice that all emails belonging to the same thread have identical threadId.
So try to use the threadId to determine the number of emails found in your request. Please someone tell me if I misunderstood this question.

Resources