0

For example:

typeDefs:

type User {
  userId: ID!
  userNme: String
  userEmail: String
}

In database, users table has three columns: user_id, user_nme, user_email.

Now, the client sends a GraphQL query named userById with two fields: user_id and user_nme.

The SQL statements of my DAO layer is:

async function findUserById(id: string) {
  const sql = `
    SELECT * FROM users WHERE user_id = ?;
  `
  return db('users').raw(sql, [id]);
}

As you can see, the SQL statement selects all columns of the users table from the database.

How to map the specific fields of client sends to the SQL select statement?

Expected result:

async function findUserById(id: string) {
  const sql = `
    SELECT 
      user_id, 
      user_nme
    FROM users WHERE user_id = ?;
  `
  return db('users').raw(sql, [id]);
}

Simply say is: I just want to query the fields that the client wants to query.

Lin Du
  • 88,126
  • 95
  • 281
  • 483
  • You can check which fields are sent under an if statement and change your query accordingly. Which is more secure – weegee May 18 '19 at 12:53
  • Converting GraphQL queries to SQL efficiently is ***hard***, particularly once you start dealing with filtering, relationships and pagination. I would highly advise looking at existing tools like [join-monster](https://github.com/acarl005/join-monster), [Prisma](https://www.prisma.io), [PostGraphile](https://www.graphile.org/postgraphile) or [Hasura](https://hasura.io) rather than trying to reinvent the wheel. – Daniel Rearden May 18 '19 at 13:02
  • @DanielRearden Thanks. I know Prisma can do this, but I am using apollographql stack – Lin Du May 18 '19 at 13:05

0 Answers0