Retrieve a single user using a query in the GraphQL platform

I've been struggling to create a GraphQL query in Express that retrieves only one user instead of all users every time.

This is the query I'm using, incorporating TypeORM as my ORM:

import { GraphQLList, GraphQLID } from 'graphql';
import { UserType } from '../TypeDefs/User';
import { Users } from '../../Entities/Users';

export const GET_ALL_USERS = {
    type: new GraphQLList(UserType),
    resolve() {
        return Users.find();
    },
};

export const GET_USER = {
    type: GraphQLList(UserType),
    args: {
        userId: { type: GraphQLID },
    },
    async resolve(userId: any) {
        // const { userId } = args;
        const user = await Users.find({
            where: {
                userId: userId,
            },
        });

        return user;
    },

};

Here's the output displayed in Graphiql:

query{
  getUser(userId:"2"){
    name
    email
    userId
  }
}
{
  "data": {
    "getUser": [
      {
        "name": "James",
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="365c575b534576515b575f5a1855595b">[email protected]</a>",
        "userId": "1"
      },
      {
        "name": "Alicia",
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5534393c363c34153238343c397b363a38">[email protected]</a>",
        "userId": "2",
      }
    ]
  }
}

It appears to be retrieving all users instead of just Alicia as intended.

Answer №1

It's possible that the issue lies in your implementation of GET_USER. Instead of specifying type: GraphQLList(UserType) as the return type, consider returning a single item such as GraphQLNonNull if you are certain it won't be null.

Best regards

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

Enhancing the utilization of the express.js module

It can be quite frustrating that when you need to use a node module, you have to manually install it, require it, and add it to the package.json file. Conversely, if you decide not to use it, you have to go through the same process in reverse. Is there an ...

Node and Backbone server facing CORS issue: POST requests unsuccessful despite receiving Options response with 200 OK status code, due to Access-Control-Allow

I'm currently facing an unusual issue. My app uses Backbone on the front end and Node/Express on the back end. After adding a middleware in my Node server to allow CORS requests, the OPTIONS request returns a 200 OK status, but the POST request does ...

How to handle non-selected columns in PostgreSQL using TypeORM with Node.js

TypeOrm "typeorm": "^0.3.11" nodejs/typeorm postgresql doesn't return non-selected column test logs display: query: SELECT "Test"."name" AS "Test_name", "Test"."id" AS "Test_ ...

When the file is active on a local machine, the bot commands run smoothly. However, these commands do not execute on a remote

Lately, while working on coding a discord bot using discord.js, I came across an issue. Whenever I run my bot on my local machine, all the commands work perfectly fine. However, after committing and pushing the code to GitHub, and then allowing buddy.works ...

angular http fails to verify authorization header

My backend is set up in Node.js with Express and Sequelize. When I make a request to retrieve all my product types using Postman, everything works fine as shown in this image: postman http request and header However, when I try to make the same request f ...

Leveraging async/await within a model function and then integrating it into a controller function within an Express MVC architecture with node-pg

I am currently working on getting a model method (specifically dealing with 'Read' from CRUD) to function correctly with a controller in the node app that I am constructing. The goal is to render a list of cars retrieved from a Postgres database ...

Struggling with inserting data into MongoDB within my MERN application

I am currently developing a MERN app that allows users to create tasks and collaborate with others. To start my backend, I ran the nodemon index.js command in the git bash terminal. However, every time I try to send POST requests for data, I encounter an e ...

Booking.com's embedded content is experiencing display issues

My current project involves adding a booking.com embedded widget. Initially, when accessing the main page, everything works perfectly - the map and booking widget are visible for ordering. However, if you switch views without leaving the page or closing th ...

Error: Angular2 RC5 | Router unable to find any matching routes

I am currently encountering an issue with my setup using Angular 2 - RC5 and router 3.0.0 RC1. Despite searching for a solution, I have not been able to find one that resolves the problem. Within my component structure, I have a "BasicContentComponent" whi ...

Storing values globally in NodeJS from request headers

What is the most effective way to store and access the value from a request header in multiple parts of my application? One approach could be as shown in the following example from app.js: app.get('*', (req, res) => { global.exampleHeader ...

Issue encountered during the installation of express

Encountered the following error during express installation. Currently running node 0.10.17 and npm 1.3.8 Tried npm install express Seems to be a version compatibility issue. What is the recommended version? npm ERR! Error: shasum check failed for C:&b ...

What is the best way to launch Nuxt on Heroku?

I am currently working on deploying a nuxt/express build to Heroku. Following the guidelines provided by Nuxt, I configured my Heroku settings as below: heroku config:set NPM_CONFIG_PRODUCTION=false heroku config:set HOST=0.0.0.0 heroku config:set NODE_ ...

What is the process for sending a GET request using express.js to access a JSON file stored locally?

I am seeking to perform a GET request on a local JSON file using express. In my server.js, I have the following setup: var data = {}; app.get('/src/assets/data.json', (req, res) => { console.log(res) res.writeHead(200, { 'Conten ...

Error message: "Uncaught TypeError in NextJS caused by issues with UseStates and Array

For quite some time now, I've been facing an issue while attempting to map an array in my NextJS project. The particular error that keeps popping up is: ⨯ src\app\delivery\cart\page.tsx (30:9) @ map ⨯ TypeError: Cannot read pr ...

Stop WebStorm from automatically importing code from a different Angular project within the same workspace

I currently have an angular repository that consists of two projects: a library and an Angular application. To link the library to my project, I utilized the npm link command. Within the package.json file, I specified the entry as follows: ... "my-lib ...

What imports are needed for utilizing Rx.Observable in Angular 6?

My goal is to incorporate the following code snippet: var map = new google.maps.Map(document.getElementById('map'), { zoom: 4, center: { lat: -25.363, lng: 131.044 } }); var source = Rx.Observable.fromEventPattern( function (han ...

Guide on importing and exporting functions in Express.js using ES modules

I've been working on exporting functions from one module to another by following this structure: import bcrypt from 'bcrypt' const saltRounds = 10 function hashPassword(password) { let passwordHash = bcrypt.hash(password, saltRounds) ...

Creating layers of object declarations

Looking for assistance on the code snippet below. type Item = { id: number; size: number; } type Example = { name: string; items: [ Item ]; } var obj: Example = { name: "test", items: [ { i ...

What is the best way to resolve the "unknown" type using AxiosError?

I'm currently working on developing a customized hook for axios, but I've encountered the following error: Argument of type 'unknown' is not assignable to parameter of type 'SetStateAction<AxiosError<unknown, any> | unde ...

Leveraging a Mongoose Schema Method within a Exported Mongoose Model

Lately, I've been developing an authentication system that is designed to either create a new user if no user with a specific ID exists OR retrieve a user with an existing ID. Through my exploration, I discovered that it's possible to determine w ...