how to return the result of a mutation-deletion in graphql?

Asked

Viewed 33 times

-1

I am trying to return the value of a deletion in the api, with this value returned I will be able to do a treatment for the frontend but as I am beginner in this area, I’m having difficulties

I would like when I made the deletion to return 1 or 0 (value returned in console.log()) in response.

I’m using knex as query Builder+mariadb, the crud is working, but the custom response part I can’t do

follows a part of the code:

const users = `
    id: ID
    Nome: String
    Celular: Float
    CPF: Float
    `
const typeDefs = `
type User {
        ${users}
    }

type Mutation {
        deletUser(id: ID!): User
    }
    `
Mutation: {
        async deletUser(_, { id } ) {
            const result = await db('CrudList').delete().where({ id })
            
            console.log(result)
            return await result
        }
    }
mutation{
  deletUser(id: 4) {id}
}

Answer:

{
  "data": {
    "deletUser": {
      "id": null
    }
  }
}

thanks since you

1 answer

0


Hello, the logic would be as follows:

  1. Pass a condition for the search( usually the ID)
  2. Make a query with this condition, take the return and place in an object.
  3. Make your exclusion, and whatever logic it implies.
  4. When the database returns true to deletion, I return the object with the data. Follow an example code:
    async excluirPerfil(_, args) {
        

        try {
            // aqui pelo id passado no args, tenho o retorno dos dados armazenado 
            // em perfil( estou buscando um perfil no bd)
            const perfil = await obterPerfil(_, args)
            // se o perfil existir, ou seja, está no banco, vamos apagar
            if(perfil) {
                const { id } = perfil
                await db('usuarios_perfis')
                    .where({ perfil_id: id }).delete()
                await db('perfis')
                    .where({ id }).delete()
            }
            // aqui eu retorno os dados do objeto excluído, agora pode tratar no 
            // front
            return perfil
        } catch(e) {
            throw new Error(e.sqlMessage)
        }
    },

Return on Playground ( in case I just showed the name, but it can be any field of your returned object).

inserir a descrição da imagem aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.