How to put a buffer in an HTTP request? - javascript

I’m trying to put a buffer in a request because I have a list of data to import. I want to have success request after one another. The problem I’m encountering is that it waits to upload all data of the request.
Here is the sample data:
[
{
"contacts": "dsds#dsd.com",
"recipient": "dsd#dsd.com",
"date_sent": "07/08/2020 17:05:04",
"subject": "repurchase"
},
{
"contacts": "asd#ret.com",
"recipient": "test#yahoo.com",
"date_sent": "07/10/2020 17:31:51",
"subject": "biz"
},
{
"contacts": "we#sdf.com",
"recipient": "abc#yahoo.com",
"date_sent": "07/09/2020 13:02:54",
"subject": "rock"
}
];
const createEngage = async(body) => {
const BASE_URL = '/api/import'
var requestOptions = {
method: 'POST',
headers: {
'Accept': 'application/json',
"Content-Type": "application/json"
},
body: body
};
fetch(BASE_URL, requestOptions)
.then(response => response.text())
.then(async result => {
console.log(result);
})
.catch(error => console.log('error', error));
}

What you probably want to do is to loop over your data and use async / await to wait at each iteration. Your implementation of your asynchronous function currently does not await anything. Instead it should await the fetch request and the decoding of the body with response.text().
Check the response for errors and wrap the fetch request in a try...catch block. If an error occurs then the catch block will be executed. Otherwise check the response object for any states or errors you want to include.
const data = [
{
"contacts": "dsds#dsd.com",
"recipient": "dsd#dsd.com",
"date_sent": "07/08/2020 17:05:04",
"subject": "repurchase"
},
{
"contacts": "asd#ret.com",
"recipient": "test#yahoo.com",
"date_sent": "07/10/2020 17:31:51",
"subject": "biz"
},
{
"contacts": "we#sdf.com",
"recipient": "abc#yahoo.com",
"date_sent": "07/09/2020 13:02:54",
"subject": "rock"
}
];
const BASE_URL = '/api/import'
/**
* Sends a request for each individual item.
*/
const createEngage = async body => {
const requestOptions = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body
};
try {
const response = await fetch(BASE_URL, requestOptions);
if (!response.ok) {
alert('Your request has failed');
return null;
}
const text = await response.text();
return text;
} catch(error) {
alert('Your request caused an error');
}
};
/**
* Loop over each item and call createEngage.
* Wait for the request to finish and continue.
*/
const createMultipleEngages = async data => {
for (const item of data) {
const result = await createEngage(item); // This will make the loop wait every time.
console.log(result);
}
};
// Call the function and start looping.
createMultipleEngages(data);

Related

CustomHook with multiple functions doesn't work

I am not sure why this customhook doesn't work , I am trying to make a payment Integration to my website but it doesn't return the frame to the other component so i can get the link , here is the code
import React , {useState} from 'react'
import { useEffect } from 'react';
export async function usePayment(data) {
const API = process.env.PAYMOB_API;
const integrationID = 2874212;
const [frame,setFrame] = useState('');
async function firstStep (datas) {
let data = {
"api_key": API
}
let request = await fetch('https://accept.paymob.com/api/auth/tokens' , {
method : 'post',
headers : {'Content-Type' : 'application/json'} ,
body : JSON.stringify(data)
})
let response = await request.json()
let token = response.token
await secondStep(token , datas)
}
async function secondStep (token , datas) {
let data = {
"auth_token": token,
"delivery_needed": "false",
"amount_cents": datas.amount * 100,
"currency": "EGP",
"items": [],
}
let request = await fetch('https://accept.paymob.com/api/ecommerce/orders' , {
method : 'post',
headers : {'Content-Type' : 'application/json'} ,
body : JSON.stringify(data)
})
let response = await request.json()
let id = response.id
await thirdStep(datas , token , id)
}
async function thirdStep (datas , token , id) {
let data = {
"auth_token": token,
"amount_cents": datas.amount * 100,
"expiration": 3600,
"order_id": id,
"billing_data": {
"apartment": "803",
"email": datas.email,
"floor": "42",
"first_name": datas.name,
"street": "Ethan Land",
"building": "8028",
"phone_number": "00000000000",
"shipping_method": "PKG",
"postal_code": "01898",
"city": "Jaskolskiburgh",
"country": "CR",
"last_name": "Nicolas",
"state": "Utah"
},
"currency": "EGP",
"integration_id": integrationID
}
let request = await fetch('https://accept.paymob.com/api/acceptance/payment_keys' , {
method : 'post',
headers : {'Content-Type' : 'application/json'} ,
body : JSON.stringify(data)
})
let response = await request.json()
let TheToken = response.token
let iframURL = `https://accept.paymob.com/api/acceptance/iframes/377194?payment_token=${TheToken}`
setFrame(iframURL)
console.log(frame)
}
useEffect(() =>{
firstStep(data)
},[])
return { frame };
}
export default usePayment;`
I am not sure what is missing here , please need someone to guide me why multiple functions in customhook doesn't work , error message is
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1 - You might have mismatching versions of React and the renderer (such as React DOM)
2 - You might be breaking the Rules of Hooks
3 - You might have more than one copy of React in the same app
and this is the code i use to call the function :
const handleSubmit = async (event) => {
event.preventDefault();
try {
if ( !name || !email || !amount ) {
generateError("Please Fill The Form !")
} else {
const { frame } = await usePayment(datas);
console.log(frame)
// location.href = pay.iframURL;
}
} catch (err) {
console.log(err);
}
};
I expect to get a url to the frame state then pass it to another component
NOTE : that this functions works fine when i add it to the component but its not working as a customhook , i am not sure why
For this use case it would be better not to use a hook, rather just write this as a js function. There's no advantage I can see to using a hook, since you're just waiting for data in useEffect and invoking the 3 api calls after that. Instead just send the payload directly to the async function when needed.
const API = process.env.PAYMOB_API;
const integrationID = 2874212;
async function firstStep (data) {
let data = {
"api_key": API
}
let request = await fetch('https://accept.paymob.com/api/auth/tokens' , {
method : 'post',
headers : {'Content-Type' : 'application/json'} ,
body : JSON.stringify(data)
})
const { token } = await request.json()
return token
}
async function secondStep ({token , data}) {
let data = {
"auth_token": token,
"delivery_needed": "false",
"amount_cents": data.amount * 100,
"currency": "EGP",
"items": [],
}
let request = await fetch('https://accept.paymob.com/api/ecommerce/orders' , {
method : 'post',
headers : {'Content-Type' : 'application/json'} ,
body : JSON.stringify(data)
})
const { id } = await request.json()
return id
}
async function thirdStep ({data , token , id}) {
let data = {
"auth_token": token,
"amount_cents": data.amount * 100,
"expiration": 3600,
"order_id": id,
"billing_data": {
"apartment": "803",
"email": data.email,
"floor": "42",
"first_name": data.name,
"street": "Ethan Land",
"building": "8028",
"phone_number": "00000000000",
"shipping_method": "PKG",
"postal_code": "01898",
"city": "Jaskolskiburgh",
"country": "CR",
"last_name": "Nicolas",
"state": "Utah"
},
"currency": "EGP",
"integration_id": integrationID
}
let request = await fetch('https://accept.paymob.com/api/acceptance/payment_keys' , {
method : 'post',
headers : {'Content-Type' : 'application/json'} ,
body : JSON.stringify(data)
})
let response = await request.json()
let TheToken = response.token
let iframURL = `https://accept.paymob.com/api/acceptance/iframes/377194?payment_token=${TheToken}`
return frame;
}
}
export async function handlePayment(data) => {
const token = await firstStep(data);
const id = await secondStep({ data, token });
return await thirdStep({ data, token, id })
}
export default handlePayment;`

JavaScript skip await on pending fetch [duplicate]

This question already has answers here:
Fetch API request timeout?
(14 answers)
Closed 8 months ago.
I have an API fetch await code that fetches list of nodes in an array. The problem is, some of the nodes don't respond for whatever reason (being offline, wrong port, being programmed NOT to respond, ... ) and my code is stuck awaiting a reply from that node.
Is there any way to stop awaiting a fetch for example after 3 seconds if no response comes?
I tried using try and catch, but the nodes that don't respond don't return anything, the code is simply sitting there with no error or response.
Thank you!!
// list of nodes
let nodes = [{
"address": {
"hostname": "192.168.1.1",
"port": 31350
}
}, {
"address": {
"hostname": "192.168.1.2",
"port": 31350
}
}
]
// api fetch function
async function fetchNodes(hostname, port) {
const response = await fetch(`https://${hostname}:${port}/getstatus`, {
method: 'post',
body: JSON.stringify(body),
headers: {'Content-Type': 'application/json'}
});
const data = response.json();
console.log(data);
}
// loop to call api fetch function with all array entries
nodes.forEach(function(entry) {
fetchNodes(entry.address.hostname, entry.address.port);
}
)
try this
async function fetchWithTimeout(resource, options = {}) {
const { timeout = 8000 } = options;
const controller = new AbortController();
const id = setTimeout(() => controller.abort(), timeout);
const response = await fetch(resource, {
...options,
signal: controller.signal
});
clearTimeout(id);
return response;
}
and use this function in you fetchNodes function
async function fetchNodes() {
try {
const response = await fetchWithTimeout(
`https://${hostname}:${port}/getstatus`,
{
timeout: 6000,
method: "post",
body: JSON.stringify(body),
headers: { "Content-Type": "application/json" },
}
);
const data = await response.json();
return data;
} catch (error) {
// Timeouts if the request takes
// longer than 6 seconds
console.log(error.name === "AbortError");
}
}

Zapier You did not define output error when return and call included

When testing my Run Javascript action, I receive the following error
string: You did not define `output`! Try `output = {id: 1, hello:
await Promise.resolve("world")};`
I don't understand why this is happening when my function includes a return and my code calls that function.
const updateAccount = async function(z, bundle) {
const data = [{
"accountId": inputData.accountId,
"values": {
"Became Customer": inputData.becameCustomer,
"Total MRR": inputData.totalMRR,
"Company Owner": inputData.companyOwner
}
}];
const promise = await fetch("https://app.pendo.io/api/v1/metadata/account/custom/value", {
method: "POST",
body: JSON.stringify(data),
headers: {
"content-type": "application/json",
"x-pendo-integration-key": "<my integration key>"}
});
return promise.then((response) => {
if (response.status != 200) {
throw new Error(`Unexpected status code ${response.status}`);
} else {
return response;
}
});
}
updateAccount()
Though your updateAccount() function correctly waits for the request to finish in itself, there's nothing to tell the Code by Zapier function to wait for updateAccount() to finish.
You also don't have to write a function at all here - the "Run Javascript" action in Code by Zapier already wraps your code in in an async function. Try the following:
const data = [
{
accountId: inputData.accountId,
values: {
"Became Customer": inputData.becameCustomer,
"Total MRR": inputData.totalMRR,
"Company Owner": inputData.companyOwner,
},
},
];
const response = await fetch(
"https://app.pendo.io/api/v1/metadata/account/custom/value",
{
method: "POST",
body: JSON.stringify(data),
headers: {
"content-type": "application/json",
"x-pendo-integration-key": "<my integration key>",
},
}
);
if (response.status !== 200) {
throw new Error(`Unexpected status code ${response.status}`);
} else {
return response;
}

How can I get the same content in my react native app as in my postman GET?

I'm communicating with a REST server, which should return ( and this is what I get when I use Postman to request it):
{
"organizer": "Fontysgroup2",
"eventStart": "2019-11-25T11:00:00Z",
"eventStop": "2019-11-25T11:00:00Z",
"room": {
"roomName": "Test Room",
"roomEmail": null,
"password": null
}
},
{
"organizer": "Fontysgroup2",
"eventStart": "2019-11-25T11:00:00Z",
"eventStop": "2019-11-25T11:00:00Z",
"room": {
"roomName": "Test Room",
"roomEmail": null,
"password": null
}
}
]
but this block of code of mine :
await fetch('https://gitroom-backend.azurewebsites.net/api/Event', {
headers: {
Authorization: 'Bearer eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSNobWFjLXNoYTI1NiIs',
}
})
.then(res => {
console.log("content"+JSON.stringify(res))
})
}
is returning:
content{"type":"default","status":200,"ok":true,"headers":{"map":{"cache-control":"public, max-age=0","date":"Mon, 25 Nov 2019 13:14:09 GMT","set-cookie":"ARRAffinity=84e8f0e39af3bde1a8c7117e525b046a8722dc904bb8684ace19b555cc8f3590;Path=/;HttpOnly;Domain=gitroom-backend.azurewebsites.net","x-powered-by":"ASP.NET","request-context":"appId=cid-v1:65c12a05-4adc-4521-b71d-69ccdcb78d9f","server":"Microsoft-IIS/10.0","vary":"Accept-Encoding","content-type":"application/json; charset=utf-8","transfer-encoding":"chunked"}},"url":"https://gitroom-backend.azurewebsites.net/api/Event","_bodyInit":{"_data":{"size":331,"offset":0,"blobId":"7592c623-fb09-415e-92f7-a97e75b08d37"}},"_bodyBlob":{"_data":{"size":331,"offset":0,"blobId":"7592c623-fb09-415e-92f7-a97e75b08d37"}}}
How can I access the actual content that I want and which Postman is giving me?
EDIT:
MY Postman:
fetchData = async () => {
const response = await fetch(
"YOUR_URL"
);
const json = await response.json();
}
Now render items iterative using constructor of your data set.
and call in your view by,
{item.YOUR_KEY}

Node fetch JSON data is not iterable [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I am getting an error of TypeError: data.events is not iterable when using fetch to retrieve JSON data from an API.
I am pretty sure it is in my handling of the JSON in for (const event of data.events) from the below code but I am pulling short on finding a fix.
const data = fetch(url, {
method: 'post',
headers: new Headers({
Authorization: 'Bearer ' + bearerToken,
'Content-Type': 'application/json'
})
});
for (const event of data.events) {
let fileNode;
try {
fileNode = await createRemoteFileNode({
url: logo.original.url,
cache,
store,
createNode,
createNodeId
});
} catch (error) {
console.warn('error creating node', error);
}
}
The JSON when requested in Postman is returned as
{
"pagination": {
...
},
"events": [
{
"name": "Example One",
"logo": {
"original": {
"url": "exampleURL"
}
}
},
{
"name": "Example Two",
"logo": {
"original": {
"url": "exampleURL"
}
}
}
],
"location": {
...
}
}
The goal is to createRemoteFileNode for each event from logo.original.url
fetch() returns a promise so data.events does not exist until the fetch promised is resolved. Edit your code this way:
fetch(url, {
method: 'post',
headers: new Headers({
Authorization: 'Bearer ' + bearerToken,
'Content-Type': 'application/json'
})
}).then(function(data){
for (const event of data.events) {
let fileNode;
try {
fileNode = await createRemoteFileNode({
url: logo.original.url,
cache,
store,
createNode,
createNodeId
});
} catch (error) {
console.warn('error creating node', error);
}
}
});

Categories

Resources