GraphQl is a powerful tool for flexible field requests. For instance, imagine you have a user table in your database with columns like Id_User, email, and name, but only want to query the Id_User.
Your query would resemble:
{
GetUser{
id
}
}
If your resolver is set up like this:
@Resolver()
class UserResolver {
@Query(() => [User])
async GetUser(): Promise<User[]> {
return await User.find();
}
}
Typeorm will generate a query that selects all fields: "SELECT Id_User, Name, Email FROM USER". Even if you're only requesting one field, Typeorm will fetch all.
To address this issue and specifically request just the "Id_User" field, you can utilize the @Info decorator in TypeGraphQL. Learn more here.
Additonally, Typeorm offers query builder functions to assist in crafting dynamic SQL statements.
Why choose GraphQL over REST? With REST, you are limited in selecting particular fields. GraphQL excels in scenarios where you require different queries for various platforms (web, app, desktop). By using one endpoint like GetUser, you can dynamically choose fields without needing multiple endpoints as with traditional REST APIs.