DEV Community

Setup express with Typescript - querying database adding services

Arsalan Ahmed Yaldram on July 12, 2022

Introduction In this series we will setup an express server using Typescript, we will be using TypeOrm as our ORM for querying a Postgre...
Collapse
 
moonseeker profile image
Moon Seeker

Is there a way to select from the query builder just the fields the client selected?
E.g. if the client wants just the “type” from the todo entity, but not the text, then we shouldn’t select the entire object from the Db

Collapse
 
yaldram profile image
Arsalan Ahmed Yaldram

Hey thanks for your comment, yes we do have the .select method on the querybuilder. You can check the documentation here - orkhan.gitbook.io/typeorm/docs/sel...

Collapse
 
moonseeker profile image
Moon Seeker

Thanks, but that is not what I meant.
If you have a query that selects the user, and does an inner join on an entity ‘profile’ that query will always return both the user and the profile. Regardless of what the client actually want’s.

What I want to do is make sure that if the client only wants the user.id, then the server doesn’t fetch the entire user object + the join from the databases

Thread Thread
 
yaldram profile image
Arsalan Ahmed Yaldram

I would create two separate endpoints for such a use case. OR Introduce a field param like directus - docs.directus.io/reference/query/#... and see if the profile field exists if yes then call the join query, else just run a simple query on the user entity without a join, I would only do this field param filtering if there is no other solution.

And for this decision I would also consider the number of times this API is been called, if it is low then fine I will go ahead with the join query and whenever I need the user.id in my client I will take it from the redux state / client state as opposed to fetching it again. If the app has user login and all auth related stuff.

If say in your app, you are fetching a list of users and there are 2 pages, one needs all the join data and other just the user name and id, we can say fetch all the user info with join once store it in our client / redux state and manipulate the data for both the pages. Else have 2 separate endpoints, in my opinion its totally fine having 2 separate endpoints.