Ad

Why Is My ApolloFetch Call Returning An Empty Query When Called From Within A Promise.all?

- 1 answer

I'm trying to use apolloFetch inside a Promise.all in my Node.js microservice but keep getting an error that the query is empty. The reason for using apolloFetch is to call another micro service and pass it an array of queries. Can someone give me some direction? My code is as follows:

   const uri = "dsc.xxx.yyyy.com/abc/def/graphql";
   const apolloFetch = CreateApolloFetch({uri});
  const QryAllBooks = {
    type: new GraphQLList(BookType),
    args: {},
    resolve() {
        return new Promise((resolve, reject) => {
            let sql = singleLineString`
                  select distinct t.bookid,t.bookname,t.country
                  from books_tbl t
                  where t.ship_status = 'Not Shipped'
              `;
            pool.query(sql, (err, results) => {
                if (err) {
                    reject(err);
                }
                resolve(results);
                const str = JSON.stringify(results);
                const json = JSON.parse(str);
                const promises = [];
                for (let p = 0; p < results.length; p++) {
                    const book_id = json[p].bookid;
                    const query = `mutation updateShipping
                              {updateShipping
                               (id: ${book_id}, input:{
                                  status: "Shipped"
                               })
                               { bookid
                                 bookname }}`;
                    promises.push(query);
                }
                //Below is the Promise.all function with the   
                //apolloFetch that calls another graphql endpoint
                //an array of queries
                Promise.all(promises.map(p => apolloFetch({p}))).then((result) => {
                    //this is the problem code^^^^^^^^^^^^^^^^^^^^^ 
                    resolve();
                    console.log("success!");
                }).catch((e) => {
                    FunctionLogError(29, "Error", e);
                });
            });
        });
    }
};
module.exports = {
    QryAllBooks,
    BookType
};
Ad

Answer

It looks like apolloFetch requires query - you are passing p

change

Promise.all( promises.map(p=>apolloFetch({p})) )

to

Promise.all( promises.map(query=>apolloFetch({query})) )

You also call resolve twice

To resolve all errors or success

const final_results = []
Promise.all(promises.map(query => apolloFetch({
  query,
}))).then((result) => {
  final_results.push(result)
}).catch((e) => {
  final_results.push(e)
}).then(() => {
  resolve(final_results)
});
Ad
source: stackoverflow.com
Ad