Search code examples
javascriptexpressgraphqltypeormtypegraphql

do TypeGraphQl automatic format the SQL query or not?


i use typeorm combine with TypeGraphQl. i want to know what the SQL query result provided by TypeGraphQl

for example if i have a User Table with a lot of columns and i have this simple resolver.

@Resolver()
class UserResolver {
  @Query(() => [User])
  async user(): Promise<User[]> {
    return await User.find();
  }
}

and on the client side they request the user data like this

{
  user{
    id,
    name
  }
}

what will the SQL run to the database.

is this one

"SELECT * FROM USER";

or this one

"SELECT id, name FROM USER";

if it the run the first SQL then why i need to use GraphQl in the first place ? isn't rest is better.

or how can i make a dynamic SQL based on the user request ?


Solution

  • GraphQl is used for dynamic field requests for example let say you have a user table in your database whit Id_User, email, name, and your want to query only the Id_User

    so your query looks like this

     {
      GetUser{
        id
      }
    } 
    

    if in your resolver you do this:

    @Resolver()
    class UserResolver {
      @Query(() => [User])
      async GetUser(): Promise<User[]> {
        return await User.find();
      }
    }
    

    Typeorm whit generates a query like this:

    "SELECT Id_User, Name, Email FROM USER"
    

    even if you don't select all the data and your query has only one field typeorm will select all the fields.

    if you want to avoid this and only want to make a request whit the "Id_User field" you need to know what field is returned by the resolver and you that whit the @Info decorator in typegraphql take a lot at this

    Also, typeorm has a query builder function that can help you to make dynamic SQL statement

    Why ? and REST is better ?, actually whit REST you cant select what fields you want, GraphQlwas made for these problems when you have a web, app, desktop app, and you need different queries for all the platforms you make a GraphQl API because whit one endpoint like this of GetUser, you can choose the fields dynamically and don't need two or more end points like rest api