Sending parameters in GraphQL with Typescript results in an empty set of curly braces being returned

I am new to learning GraphQL with Typescript and I am trying to pass an argument in a GraphQL function to return something dynamically. I have been struggling with this issue for the past hour and could not find any solutions. Here are the relevant code snippets from my project.

schema.ts

export default gql`
type Query {
    fetchCourse(courseId: String!): String
}
`

resolver.ts

export default {
    Query: {
        fetchCourse: (courseId: string): string => {
            console.log(courseId)
            return 'test'
            // I want to do someting like this when the argument is working
            // const data = await db('course').select('*').where('c_id', courseId).first()
            // return data.toString()
        }
    }
}

GraphQL query on GraphiQL

{
  fetchCourse(courseId: "1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed")
}

Currently, the Console.log() is outputting just an empty curly bracket ({}) or an empty object in JavaScript. I expected it to display the actual argument (

1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed
) instead.

Your responses would be greatly appreciated. Thank you.

Answer №1

It took me a while to figure it out, but I finally found the solution. Perhaps my initial explanation was lacking. I was working with Fastify and Mercurius.

The fix is actually quite simple - just add an underscore (_) with unknown type as the first argument, and an object of the desired type as the second argument. For example, if your query looks like this :

type Query {
    add(x: Int, y: Int): Int
}

Then your resolver should look something like this

Query: {
    add: (_: unknown, { x, y }: { x: number, y: number }): number => {
        console.log(x, y)
        return x + y
    }
}

Therefore, the altered query for my specific question would be

Query: {
        fetchCourse: async (_: unknown, { courseId }: { courseId: string }): Promise<string> => {
        const data = await db('course').select('*').where('c_id', courseId)
        return JSON.stringify(data)
    }
}

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

ways to validate the calling function in jquery

One of the challenges I'm facing is identifying which function is calling a specific error function that is used in multiple places within my code. Is there a method or technique to help determine this? ...

Node.js OTP Verification: Secure your app with one-time

How can the accuracy of OTPs received from clients be verified effectively in a Node environment without relying on additional storage methods? ...

Adjust the size of every card in a row when one card is resized

At the top of the page, I have four cards that are visible. Each card's height adjusts based on its content and will resize when the window size is changed. My goal is to ensure that all cards in the same row have equal heights. To see a demo, visit: ...

Tips for evaluating an array of objects in JavaScript

Welcome to the world of coding! Here's a scenario with an array: [ { "question1": "Apple", "question2": 5, "question3": "Item 1" }, { "question1": ...

When I click the button, it deletes the DOM element and hides it, preventing me from

I'm facing a simple issue that I can't quite wrap my head around. Whenever I input a value into the form and click the button to run the function, the 'loading' element disappears and doesn't reappear. Here is the JavaScript code ...

React/NextJS: Firebase Realtime Database displaying the message "Error: Client is offline"

Encountering an occasional error when using React with NextJS to fetch data from a Firebase Realtime Database. Unhandled Runtime Error Error: Error: Client is offline. Currently utilizing Firebase version 9.0.1 for React. The initialisation and configura ...

Is there cause for worry regarding the efficiency issues of utilizing Object.setPrototypeOf for subclassing Error?

My curiosity is piqued by the Object.setPrototypeOf(this, new.target.prototype) function and the cautionary note from MDN: Warning: Modifying an object's [[Prototype]] is currently a slow operation in all browsers due to how modern JavaScript engines ...

What is the best way to update the value of a preact signal from a different component?

export const clicked = signal(false); const handleClickDay = (date) => { const day = date.getDate().toString().padStart(2,'0') const month = (date.getMonth()+1).toString().padStart(2,'0') const year = da ...

Enable next-i18next to handle internationalization, export all pages with next export, and ensure that 404 error pages are displayed on non-generated pages

After carefully following the guidelines provided by i18next/next-i18next for setting up i18n and then referring to the steps outlined in this blog post on locize on how to export static sites using next export, I have managed to successfully generate loca ...

Guide on Implementing jQuery UI Autocomplete with Chrome's Speech Input Feature

I have recently discovered a cool feature in Chrome that allows users to dictate into any input field using speech input. Learn more here. It's easy to add this feature in Chrome: <input type="text" x-webkit-speech="x-webkit-speech" /> <!-- ...

Utilize S3 to host images and implement via Express in a Lambda-based project

I store all my user-related files in a bucket and I want users to be able to download those files. The issue I'm facing is that I need to proxy the request through an API URL like https://myproject.com/api/file/:key where :key corresponds to the obj ...

Nested solution object populated with promises

Looking for a solution similar to the npm libraries p-props and p-all, but with the added functionality of recursively resolving promises. const values = { a: () => Promise.resolve(1), b: [() => Promise.resolve(2)], c: { d: () =&g ...

Enhance your data retrieval from XPATH using Javascript

Here is the layout of an HTML template I am working with: <div class="item"> <span class="light">Date</span> <a class="link" href="">2018</a> (4pop) </div> <div class="item"> <span class="light">From</sp ...

Convert JSON response date format to a format specified by the user

The following code snippet is currently returning the dates for $("#dob") and $("#anniversery") as 2014-04-01T00:00:00 This is my current code: <script> $(function() { function log(message) { $("<div>").text(message).p ...

Guide to interacting with the Li element using JavaScript in Selenium

Is there a way to click on the item inside the li element using a Selenium script with JavaScript? I've tried different methods like By.cssSelector or by css, but I keep getting an ElementClickInterceptedError: element click intercepted:Other element ...

Tips on transmitting form information from client-side JavaScript to server-side JavaScript with Node.js

Having created an HTML page with a form, my goal is to capture user input and store it in a JSON file. However, I've run into some confusion... In the process, I utilized the express module to set up a server. My mind is juggling concepts such as AJA ...

Where should the logic for the Redux app be implemented for optimal performance?

My react-redux app features an action-creator that filters a list of objects based on a specified title: export const filterItems = (title) => dispatch => { axios.get(`/api/items/?title=${title}`) .then(res => { dispatch({ ...

Sending a JWT token to a middleware with a GET request in Express Node.js - the proper way

Struggling with Js and web development, I've scoured the web for a solution to no avail... After completing a project for a small lab, my current challenge is creating a login page and generating a web token using JWT... I successfully created a use ...

Using React Material UI icon within an auto complete feature

https://i.stack.imgur.com/W3CmF.png I am struggling to incorporate the target icon into the autoComplete component. After reviewing the documentation, I have been unable to find a solution. In TextInput, a similar outcome can be achieved by implementing ...

Add up the duplicate elements in two arrays

I have dynamically created two arrays with the same number of cells (where array.length is the same, representing a key and value association). Below are the arrays: barData.labels["Food", "Food", "Food", "Food", "Food", "Food", "Food", "Food", "Food", "F ...