Tuesday, 26 January 2021

Which value should be returned by a apollo graphql mutation?

I'm using apollo graphql to call some mutation to change db data. I need some advice which value should be returned usually.

For insertOne() I would return the ID of the new document and for removing a dataset I would also return the ID, to remove the dataset on the client cache.

But what about updateOne - as it could be a very simple task as shown below, but sometimes it can do some complex update? I'm not quite sure which would be the most useful returning value.

In this simple example I'm just updating some content of a specific mongodb document. Right now the WriteResult of this method is returned. But is this really useful?

I see the follwing options:

  1. Returning writeResult object - which has the need to be defined in the backend
  2. Check writeResult and return boolean, e.g. result.nModified > 0
  3. Return the content result - which would be at the end just the input content
  4. Returning the updated document - which would need a findOne({ _id: id })
  5. Just returning true, which maybe is not very useful?!

I know there is not a single solution for all use cases, but maybe someone could explain which way to go in general...

server

async updateContent(id, name, value) {
  const Content = this.db.collection('content')
  return Content.updateOne(
    { _id: id },
    { $set: { [name]: value } }
  )
}

client

updateContent({
  variables: { id, name, value }
})
  .then((response) => {
    // response.data.updateContent
  })
  .catch((error) => console.error(error))

graphql

mutation updateContent($id: ID!, $name: String, $value: String) {
  updateContent(id: $id, name: $name, value: $value) {
    nModified
  }
}

schema

type WriteResult {
  nModified: Int,
  nRemoved: Int,
  nInserted: Int,
  n: Int
  ok: Int
}

type Mutation {
  updateContent(id: ID!, name: String, value: String): ContentString
}


from Which value should be returned by a apollo graphql mutation?

No comments:

Post a Comment