Enhance Graphql Queries with TypeOrm using Dynamic Filters

I am currently working on building a graphQL query system using Apollo, typescript, and TypeOrm. At the moment, I only have one table called users in my database. I am creating a getUsers GraphQL query which retrieves all users from the table. With the help of typeOrm, I retrieve users in my resolver function using the find() method. My main concern is whether it is possible to have optional filters for the users table in TypeOrm or Apollo. This way, I can pass an optional id parameter or no parameter at all to return all users within the same query. Are there any methods available to handle optional filters without needing to execute multiple queries? Thank you for your guidance.

Below are examples of the queries I would like to execute:

query noFilters {
  getUsers {
    id
    firstName
  }
}
## Return all users

query withFilters {
  getUsers (filters: {id: [1]}) {
    id
    firstName
  }
}
## Return user with ID 1 only

User entity structure:

import {Entity, PrimaryGeneratedColumn, Column, BaseEntity} from "typeorm";

@Entity()
export class User extends BaseEntity{

    @PrimaryGeneratedColumn({name: "user_id"})
    id: number;

    @Column({name: "first_name" })
    firstName: string;
}

Resolver function:

export const resolvers = {
  Query: {
    getUsers: async (_: any, args: any) => {
      const { id } = args;

      return await User.find({where: {}});
    }
  }
};

Types definition:

export const typeDefs = gql`
  type Query {
    getUsers(id: [Int!]): [User]
  }

  type User {
    id: Int!
    firstName: String!
  }
`;

Answer №1

To implement this code snippet, follow these steps:

const resolverFunctions = {
  Query: {
    fetchUsers: async (_: any, args: any) => {
      const { id, where } = args;

       if (args.where){
           where = args.where;
       }

      return await User.find({where: where});
    }
  }
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular asynchronous testing with Observable using karma

I am currently working on testing an asynchronous scenario. Here is a snippet of my component: ngOnInit(private service: MyService) { this.isLoading = true; this.service.getData().subscribe((data) => { this.data = data; this.isLoa ...

What is the procedure for sending a secondary route parameter to the angular 2 services module?

I'm a beginner with Angular 2 and I'm seeking advice on how to pass multiple parameters to Angular's service module. For instance, here is the first parameter I'm passing to the service through the router link. In the home-component.ht ...

Is there a method to retrieve the data type along with the data using Sequelize?

Can someone help me retrieve both the data type and data of an attribute using axios and sequelize? ...

Steps for updating text within an object in Angular

details = [ { event: "02/01/2019 - [Juan] - D - [Leo]", point: 72 }, { event: "02/01/2019 - [Carlo] - N - [Trish]", point: 92 } ]; I am attempting to modify the text within the titles that contain - N - or - D - The desired outcom ...

unable to send array in cookie through express isn't functioning

Currently, I am in the midst of a project that requires me to provide the user with an array. To achieve this, I have been attempting to utilize the res.cookie() function. However, each time I try to pass an array as cookie data, the browser interprets it ...

Having trouble with Angular 2 Routing and loading components?

I am facing an issue with Angular 2 where it is searching for my component in app/app/aboutus.component, but I cannot pinpoint the source of the problem. Here is my app.component.ts code: import { Component } from '@angular/core'; import { ROUT ...

Unable to receive a response from the API after invoking a function in ExpressJS

I'm currently calling the createUserData API and I expect the response to be stored in the resonse_data variable. However, when I console.log the resonse_data variable, it shows an undefined value. async createUserData(req, res) { var resonse ...

An effective way to pass an array as data to an express router from Angular

I've been attempting to retrieve more detailed information for multiple ID's from the database, but I've hit a roadblock. Below is the array of member ID's: var memberIds = ["2892056", "2894544", "2894545" ...

Guide to resolving domain names in express.js

I've been working on an expressJS script that includes a mongoDB fetch. My objective is to create an API that displays my JSON-based test list on the /api/testlist route. When I try to access the index page, everything seems to be working fine. Howev ...

When the button is pressed, the TypeScript observable function will return a value

Check out the snippet of code I'm working with: removeAlert() : Observable<boolean> { Swal.fire({ title: 'delete this file ?', text: 'sth', icon: 'warning', showCancelButton: true, ...

Express's connect-flash Node.js module is failing to work properly during redirects

I'm puzzled as to why my connect-flash functionality is not working properly. It's my understanding that connect-flash is supposed to save messages into the session. I have set up the session like this : app.use(session()); Then I have configu ...

What is the reason `addEventListener` does not work with a class method?

Recently, I discovered that the listener passed to addEventListener can actually be an object with a handleEvent function instead of just a callback function (here). However, I encountered an issue when trying to use handleEvent as a class method: class F ...

Setting up SSL/TLS certificates with Axios and Nest JS

I have a Nest JS application set up to send data from a local service to an online service. However, the requests are not working because we do not have an SSL certificate at the moment. Can anyone provide guidance on configuring Axios in Nest JS to accept ...

NodeJS/ExpressJS Image Redirection

Would it be acceptable for an img to have a src value that redirects to another page? In my view, I am using the following img tag: <img src='/images/fileName'/> In app.js app.get('/images/:fileName', subject.image); Here is ...

Utilizing generic union types for type narrowing

I am currently attempting to define two distinct types that exhibit the following structure: type A<T> = { message: string, data: T }; type B<T> = { age: number, properties: T }; type C<T> = A<T> | B<T>; const x = {} as unkn ...

Webpack bundling only a singular Typescript file rather than all of its dependencies

I'm currently facing a challenge while attempting to consolidate all the files in my Typescript project, along with their dependencies from node_modules, into a single file using Webpack. Despite trying multiple options, it seems that only the entry f ...

When attempting to utilize TypeScript with Storybook, Jest may encounter an error stating, "Incompatible types for property 'id'."

Currently, I'm exploring the use of stories in my unit tests with Jest + RTL to reduce redundancy. However, I've encountered an error stating "Types of property 'id' are incompatible" when passing arguments that are also used in my stor ...

Angular has got us covered with its latest feature - combining Async Await with an EventListener

I have been facing this issue for the past day and need help creating a specific scenario: <img [src]="userdp | async" /> In my component.ts file, I want to include only this line: this.userdp = this._userService.getUserDp(); Here is the ...

Tips for inserting and saving JSON data into an SQL server with Node.js

Attempting to execute a query in SQL Server using Windows authentication with Node.js. I have successfully implemented the GET request for select queries, but now I am facing issues with the POST request for insert queries. The problem arises when trying t ...

How do I disable split panel on Ionic 2 login page exclusively?

I have successfully implemented the split-pane feature in my app.html file. However, I am facing an issue where the split pane is being applied to every page such as login and SignUp. Can someone please guide me on how to restrict the split pane function ...