What is the method for incorporating a variable into a fragment when combining schemas using Apollo GraphQL?

In my current project, I am working on integrating multiple remote schemas within a gateway service and expanding types from these schemas. To accomplish this, I am utilizing the `mergeSchemas` function from `graphql-tools`. This allows me to specify necessary fragments and custom resolvers to delegate to the appropriate schemas. One crucial part of this implementation involves:

const typeExtensions = `
extend type VsStatistics {
  commonCompetitors(filter: DateRangeFilter): [Player!]!
}
`

const mergedSchema = mergeSchemas({
  schemas: [ playerSchema, resultsSchema, typeExtensions ],
  resolvers: {
    VsStatistics: {
      commonCompetitors: {
        fragment: `fragment CommonCompetitorsFragment on VsStatistics { commonCompetitionIds }`,
        resolve (parent, _args, context, info) {
          return info.mergeInfo.delegateToSchema({
            schema: playerSchema,
            operation: 'query',
            fieldName: 'players',
            args: { idArray: parent.commonCompetitionIds },
            context,
            info
          })
        }
      }
    }
  }
})

The attribute `commonCompetitionIds` is an array of IDs found in the VsStatistics object. Everything works smoothly when I don't need to pass any parameters to the fragment as illustrated above. However, I recently introduced a new filter argument of type `DateRangeFilter` to `commonCompetitionIds`. The extension `commonCompetitors` now accepts this filter as an argument, and I must find a way to pass it into the fragment to apply the filter to `commonCompetitionIds`. I attempted the following...

      commonCompetitors: {
        fragment: `fragment CommonCompetitorsFragment on VsStatistics { commonCompetitionIds(filter: $filter) }`
        ...

...hoping that the parent's arguments would automatically be accessible to the fragment. Unfortunately, I received an error stating `Variable "$filter" is not defined`. How can I successfully pass this filter into the fragment to retrieve the filtered `commonCompetitionIds` for use in the resolver?

Answer №1

Recently, there has been a renewed conversation surrounding this topic within the GraphQL Tools repository. You can find more information here: https://github.com/ardatan/graphql-tools/discussions/1709. It's worth noting that the necessary features to support this functionality were introduced in version 6.0.15.

UPDATED RESPONSE:

To address this issue, I have found a workaround by leveraging two separate delegateToSchema requests within my field resolver. The initial request is used to retrieve plain IDs with dynamic arguments, while the second request is responsible for performing standard record stitching. While this approach solves the problem temporarily, it is not without its drawbacks. It introduces an additional request for IDs, leading to synchronization issues with other batch requests sent to the same service. Hopefully, we will see built-in GraphQL Tools support for this feature in the near future.

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

What causes the jQuery mouseenter events to be activated in a random sequence?

I currently have a setup of 3 nested divs, resembling the concept of a Matryoshka doll. Each div has a mouseenter event function bound to it. When moving the mouse slowly from the bottom and entering layer three, the events occur in the following sequence ...

Perform a Fetch API request for every element in a Jinja2 loop

I've hit a roadblock with my personal project involving making Fetch API calls to retrieve the audio source for a list of HTML audio tags. When I trigger the fetch call by clicking on a track, it always calls /play_track/1/ and adds the audio player ...

The process of incorporating or expanding an object within a component

When using vue.js, you have the ability to iterate over an array of items in your template as shown below: <div id="app"> <div v-for="(item, i) in items">i: item</div> </div> <script> var example2 = new Vue({ el: &ap ...

The passport is experiencing an authentication issue: The subclass must override the Strategy#authenticate method

After attempting to authenticate and log in a user, I encountered an error message stating: Strategy#authenticate must be overridden by subclass. How can I resolve this issue? What could be causing this error to occur? Concerning Passport.js const LocalS ...

Is there a way to programmatically prevent the back button from functioning if the previous route pathname in React was 'Login'?

When it comes to navigating back on previous pages, the traditional back button is typically used instead of relying solely on the navigation bar. However, I am currently looking to disable this feature specifically when the next previous route in line is ...

Searching for values within an array using the ".includes" method

I'm curious if there's a method to determine if a string contains any characters that are also present in an array? const array = ["cake", "hello", "ok"]; const string = "hello"; let result = string.include ...

Tips for troubleshooting Angular 4 unit testing using jasmine and karma with simulated HTTP post requests

I have a service that I need to unit test in Angular 4 using TypeScript and Jasmine. The problem is with the http where it needs to perform a post request and get an identity in return, but for some reason, no data is being sent through. My goal is to ac ...

How to display and retrieve data from a JSON object using JavaScript

Having trouble retrieving input values from a JSON object and getting 'undefined' when running the code. Any suggestions or ideas would be greatly appreciated as I have tried various approaches. Additionally, I need to utilize JSON for my school ...

Vue js for filtering and replacing prohibited words

For this scenario, our objective is to screen the words in our input: <input type="text" class="form-control" placeholder="Write something..." v-model="todoInput""> Below are the restricted words that we aim to substitute in the input "restrict ...

Troubleshooting Timeout Problems with Selebiun Crawler in C#

I am encountering an error while running the following code. public void GetCategoriesSelenium() { string javascript = System.IO.File.ReadAllText(@"GetCategory.js"); CrawlerWebSeleniumJS.ExecuteScript("var finished;"); ...

Guide to extracting the values associated with a specific key across all elements within an array of objects

My goal is to retrieve the values from the products collection by accessing cart.item for each index in order to obtain the current price of the product. const CartSchema = mongoose.Schema({ userId: { type: mongoose.Schema.Types.ObjectId, ...

Transfer the AWS configuration settings to the imported module

Currently, I am attempting to perform unit testing on a JS AWS Lambda by running it locally. To simulate the Lambda environment, I am taking on the same role that the Lambda would have with AWS.config.credentials and then executing the Lambda function that ...

A guide on using jCrop to resize images to maintain aspect ratio

Utilizing Jcrop to resize an image with a 1:1 aspect ratio has been mostly successful, but I've encountered issues when the image is wider. In these cases, I'm unable to select the entire image. How can I ensure that I am able to select the whole ...

Determine whether the elements within an array are present on the webpage. If they are, display an alert. If not, reload the page

Initially, I had a userscript designed to search for a specific string within a webpage. If the script failed to locate the string, it would refresh the page after 4 seconds: var item = 'apple'; if(document.body.innerHTML.toString().indexOf(item ...

Angular HttpClient does not support cross-domain POST requests, unlike jQuery which does

I am transitioning to Angular 13 and I want to switch from using jQuery.ajax to HttpClient. The jquery code below is currently functional: function asyncAjax(url: any){ return new Promise(function(resolve, reject) { $.ajax({ type: ...

How to Modify CSS in Angular 6 for Another Element in ngFor Loop Using Renderer2

I have utilized ngFor to add columns to a table. When a user clicks on a <td>, it triggers a Dialog box to open and return certain values. Using Renderer2, I change the background-color of the selected <td>. Now, based on these returned values, ...

Tips for testing an Angular 6 service with a dependency that utilizes private methods and properties to alter the output of public methods and properties

I've encountered a challenge while attempting to write a Jasmine/Karma test for an Angular 6 app. The test is for a service in my application that relies on another service with private properties and methods, causing my tests to consistently fail. W ...

Exploring innovative CSS/Javascript techniques for creating intricate drawings

When using browsers other than Internet Explorer, the <canvas> element allows for advanced drawing. However, in IE, drawing with <div> elements can be slow for anything more than basic tasks. Is there a way to do basic drawing in IE 5+ using o ...

Maintain selected dropdown option after page reload

I attempted to preserve the selected item after triggering a reload with an onchange event, however, I encountered this error in the console: "TypeError: o.nodeName is undefined[Learn More]" Here is my select element : <select onchange="showMov(this. ...

What is the process for removing a particular file from my bundle?

I am currently utilizing webpack to build my angular2/typescript application and have successfully generated two files, one for my code and another for vendors. However, I am in need of a third file to separate my config (specifically for API_ENDPOINT) whi ...