0
votes


I just started using graphql with mysql, i would like to know if it is possible to use a name in the graphql query different from the column name in my data base.
For example i have a table users with the columns userName and password, when i define the type for the schema i have the following:

const unidadesMedidaInternaType = new GraphQLObjectType({
    name: 'unidadesMedidaInterna',
    fields: () => ({
        userName: { type: GraphQLID },
        password: { type:GraphQLString }
    })
});

the resolver:

resolve (parent, args) {
    return pool.query(`SELECT * FROM users`);
}

so i have to query like this:

{
  users {
     userName,
     password
  }
}

i would like to have different names in the query like this:

{
  users {
     Name,
     secret
  }
}

i tried changing the names of the fields in the type definition but the result of the query is full of nulls values.

1
map fields in resolver - xadm

1 Answers

2
votes

In order to have different names in the queries you have 2 options:

Option 1: Use aliases to run the query: You can run your query with aliases like

{
  users {
     Name: userName,
     secret: password
  }
}

In this case you are just renaming the fields name on execution time, so the original names will still be available to query.

Option 2: Map the query result to the GraphQLObject type.

First rename the fields:

const unidadesMedidaInternaType = new GraphQLObjectType({
    name: 'unidadesMedidaInterna',
    fields: () => ({
        Name: { type: GraphQLID },
        secret: { type:GraphQLString }
    })
});

Then map the result of the query to match the fields:

resolve (parent, args) {
    const result = pool.query(`SELECT * FROM users`);
    // If the result of the query is an array then you have to map its items
    return { Name: result.userName, secret: result.password }
}