簡體   English   中英

當響應正文包含錯誤消息時重試 Array.forEach 獲取請求

[英]Retry Array.forEach fetch request when response body includes an error message

我已經構建了一個基本的 web 應用程序,它從本地數據庫中檢索發票數據並將數據發布到 Wave Accounting。

我發現來自 api 的錯誤包含在響應正文中。

如果來自 api 的響應正文包含錯誤,我正在嘗試找出重試請求的解決方案。 (它總是返回 200 作為狀態)。

我嘗試了在 stackexchange 上找到的其他解決方案(將限制參數傳遞給函數)並在獲取請求失敗時重試,直到達到限制數量。 邏輯和數據都工作正常——只是偶爾會在 api 端發生內部服務器錯誤,我需要想辦法解決這個問題。

function postInvoicesToWave(data, limit = Number.MAX_VALUE) {
let query = `mutation ($input: InvoiceCreateInput!){invoiceCreate(input: $input){didSucceed inputErrors {code message path} invoice {id title invoiceNumber invoiceDate items {product {id name} description quantity price subtotal {value currency { symbol }} total { value currency { symbol } } taxes { amount { value } salesTax { id name} } } } } }`;
fetch('https://gql.waveapps.com/graphql/public', {
    method: 'POST',
    headers: {
        'Authorization': 'Bearer <access token>',
        'Content-Type': 'application/json',
        'Accept': 'application/json',
    },
    body: JSON.stringify({
        query,
        variables: {
            input: {
                "businessId": `${data.businessId}`,
                "customerId": `${data.customerId}`,
                "status": "SAVED",
                "invoiceNumber": `${data.invoice}`,
                "poNumber": `${data.po}`,
                "invoiceDate": data.date,
                "currency": "EUR",
                "items": [
                    {
                        "description": `${data.description}`,
                        "quantity": 1,
                        "unitPrice": data.price,
                        "productId": `${data.productId}`,
                        "taxes": { "amount": 0, "salesTaxId": `${data.salesTaxId}`} //taxes normally get paid - this is just testing :)
                    }
                ]
            }
        }
    })
}).then(r => r.json())
  .then(res => {
    if(res.hasOwnProperty("errors") && --limit){
      console.log(limit);  //console logs random numbers  6, 18, 5 for example on the last test
      return postInvoicesToWave(data, limit);  
    }  
    else {
       //update the database with posted success value
    }  
  });
}

這是調用 function 的地方 - 在從數據庫中獲取數據之后:

.then(data => {  //this is returned from the db
  const waveButton = document.getElementById('waveButton');
  waveButton.addEventListener("click", (e) => {
  e.preventDefault();
  data.forEach(postInvoicesToWave);  //I have tried data.forEach(postInvoicesToWave.bind(5)); I have also tried data.forEach(postInvoicesToWave, 5);        
  });
})

基本上我想要實現的是將參數傳遞給array.forEach function,如果 api 響應正文包含錯誤,則使用此參數作為最大重試次數。

請原諒我可能包含的問題措辭和任何語法錯誤 - 如果提出任何建議,我將編輯問題

提前致謝。

首先,在不知道錯誤是什么的情況下盲目地重試 api 調用似乎很奇怪?

但是在forEach的主體中將參數傳遞給 function 的最簡單方法是:

const retries = 3;
data.forEach((data) => postInvoicesToWave(data, retries));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM