Search code examples
javascriptapisuperagent

Multipart Form Upload using POST API


I need help trying to upload items to an API using superagent.

The limit for items in a single upload is 500. So if I've to send more than 500 items, I've to break the request down into 3 separate requests if the upload size is 500, for example.

I've broken the request down, but now I'm wondering how make multiple requests to the API.

Any idea how to chain this using superagent? I've looked into multi-part uploads, but I don't know if this is the same thing.


Solution

  • You can use Array.prototype.shift(), .then() to schedule call to a function if array containing arrays .length evaluates to true, else return array of responses. Which performs the process in sequence.

    const requests = [[..], [..], [..]];
    let results = [];
    let request = requests.shift();
    let handleRequests = (data) => fetch("/path/to/server", {
      method:"POST", body:data
    })
    .then(response => response.text())   
    .then(res => {
      results.push(res);
      return requests.length ? handleRequest(requests.shift()) : results
    });
    
    handleRequest(request)
    .then(res => console.log(res)
    , (err) => console.log(err));
    

    Note, if order is not a part of requirement, you can substitute Promise.all(), Array.prototype.map() for .shift().

    let handleRequests = (data) => fetch("/path/to/server", {
      method:"POST", body:data
    })
    .then(response => response.text());
    Promise.all(requests.map(handleRequests))
    .then(res => console.log(res)
    , (err) => console.log(err));