How to pass array in Lokka mutation?

224 views Asked by At

I am working on a project having GraphCool, Lokka and Nodejs. I had to pass itemsIds: [ID!], now when an array of strings is passed into string literal the array becomes [id1, id2, id3] and the mutation needs ["id1", "id2", "id3"]. The problem is also same for Apollo GraphQL. I somehow solved the problem using the below code. Am I doing something wrong? Is there a simple solution? -

            let cc = '';
            data.allCarts[0].items.map(item => cc = cc.concat(`'${item.id}',`));

            cc = cc.concat(`'${itemid}'`);
            console.log('mogg ', cc);
            cc = cc.replace(/'/g, '"');
            console.log('gogg ', cc);

            let nodeid = data.allCarts[0].id;
            console.log('Node:: ', nodeid, 'items:: ', cc);

            client.mutate(`{
                uo: updateCart(id: "${nodeid}", itemsIds: [${cc}]){
                    id
                    }
            }`
            ).then(
                (response) => {
                    console.log('cart update:: ', response.uo);
                    sendTextMessage(user, 'Done adding to cart, choose to add more');
                }
                )
                .catch(error => console.error(error));
1

There are 1 answers

0
Daniel Rearden On BEST ANSWER

Inserting the values of your arguments directly into the query string is clunky -- that's what variables are for.

itemsIds is looking for an array of IDs so let's give them that:

const cc = data.allCarts[0].items.map(item => item.id).concat(itemid);

Then... with lokka:

const mutation = `($nodeid: ID, $cc: [ID!]){
  uo: updateCart(id: $nodeid, itemsIds: $cc){
    id
  }
}`

const variables = { nodeid, cc }

client.mutate(mutation, variables)

Or... with Apollo:

const mutation = gql`mutation UpdateCart($nodeid: ID, $cc: [ID!]){
  updateCart(id: $nodeid, itemsIds: $cc){
    id
  }
}`

const variables = { nodeid, cc }

client.mutate({mutation, variables})