'How to awoid 'SELECT *' in graphql?
I'm pulling data from database using graphql, but something is bothering me a lot.
/App.js:
import { schema } from './graphql/index.js';
...
app.post(
'/graphql',
graphqlHTTP({
schema: schema,
})
);
/graphql/index.js:
import { GraphQLObjectType, GraphQLSchema, GraphQLList } from 'graphql';
import { DB_GetAllCustomers } from '../services/database/customers.js';
import { TYPE_Customer } from './typedef/customers.js';
const RootQuery = new GraphQLObjectType({
name: 'RootQuery',
fields: {
getAllCustomers: {
type: new GraphQLList(TYPE_Customer),
resolve: async () => {
const data = await DB_GetAllCustomers();
console.log(data[0]);
return data[0];
},
},
},
});
const RootMutation = new GraphQLObjectType({
name: 'RootMutation',
fields: {
...
...
},
});
export const schema = new GraphQLSchema({
query: RootQuery,
mutation: RootMutation,
});
/graphql/typedef/customers.js:
import graphql, { GraphQLObjectType } from 'graphql';
export const TYPE_Customer = new GraphQLObjectType({
name: 'Customer',
fields: () => ({
id: { type: graphql.GraphQLString },
username: { type: graphql.GraphQLString },
email: { type: graphql.GraphQLString },
mobile: { type: graphql.GraphQLString },
password: { type: graphql.GraphQLString },
_active: { type: graphql.GraphQLInt },
_suspended: { type: graphql.GraphQLInt },
}),
});
/services/database/customers.js:
export const DB_GetAllCustomers = () => {
return db.execute('SELECT * FROM customers').catch((err) => {
throw err;
});
};
So, lets say my graphql request is
query RootQuery{
getAllCustomers{
id
}
}
here I just want to get IDs of all customers.
It works as expected:
But the problem is, as you see I debug RootQuery:
and the logs:
Here the graphql front side works as it should, but the database side you see, unnecessary data requests are made.
How can I optimize this, any best practice?
(note: I can't just "SELECT id FROM customers" because graphql scalability should not be limited.)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|




