I'm facing an issue with my GraphQL resolvers due to a circular dependency

After modifying my repositories to directly return the GQL resolvers, everything was going smoothly until I encountered a circular dependency issue. Now, I have two repositories that rely on each other, creating a dilemma that JavaScript cannot easily resolve. Is there a solution to this problem?

ARepository.getA = () => {
   const a = getAFromDatabase();
   return {
      ...a,
      B: BRepository.getB()
}

Describing the first repository:

BRepository.getB = () => {
   const b = getBFromDatabase();
   return {
      ...b,
      A: ARepository.getA()
}

Both repositories have interdependencies, making it impossible to define one without the other. This creates a deadlock situation where neither repository can be fully defined.

Answer №1

It's not recommended to create a universal resolver for a GraphQL type, as it can lead to issues down the line.

Instead of combining the repository with the resolver, it's better practice to keep them separate. The repository should focus on retrieving records from the database, while the resolver can then call upon the repositories as needed.

It's advisable to have a distinct resolver for each query, rather than for each type. If there are multiple queries resolving the same types, consider abstracting them into functions like "gqlWrappers." These wrappers can enhance your database records with resolvers for specific types or fields that are considered simple or leaf nodes.

Be cautious of creating cyclical dependencies between gqlWrappers. If gqlWrapper for type A relies on gqlWrapper for type B, and vice versa, it can lead to unresolved cyclical dependencies.

For example, if type A and type B reference each other, it's essential to abstract other components. A possible solution for implementing the resolver for the getB Query could look like this:

Queries: {
    getB: async () => {
       const b = BRepository.getB(); // Only retrieve database raw data from the repo
       return {
          ...BGqlWrapper(b),
          A: async () => {
              const a = ARepository.getA();
              return AGqlWrapper(a);  // Prevent redundant retrieval of B from A if already starting from B
          }
       }
    }
}

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

Php file not receiving data from ajax post method

forget.php PHP: if (! (empty($_POST['emailforget'])) ) { echo "here in the function"; } else { echo "here"; } AJAX: $("#passreset").on('click', function(e) { var emailforget = $("#tempemail").val(); alert(emailforget); ...

Tips for sending an extra parameter to the callback function when using the loader.parse method in Three.js

The Parse method of the Loader object in three.js allows you to specify a callback function that will be triggered upon completion of the parsing process. This callback will receive a unique argument which represents the parsed object. However, I am encou ...

Tips for preserving the state of the Material-UI AutoComplete during component re-renders?

Currently, I am utilizing the Material-UI v4 AutoComplete component along with the renderOption prop in order to display a checkbox item option. The issue arises when the onChange event occurs and updates a hook in the parent component causing a re-rende ...

The inline HTML script was unable to execute the function as intended by Jquery

Attempting to remove the element using a custom function called within inline html on my script tag, below is the code: HTML <div id="form"> <input type="text" name="name", id="name"><br> <input type="text" name="address", id="ad ...

Learn how to obtain a response for a specific query using the `useQueries` function

Can we identify the response obtained from using useQueries? For instance, const ids = ['dg1', 'pt3', 'bn5']; const data = useQueries( ids.map(id => ( { queryKey: ['friends', id], queryFn: () =&g ...

Why is it necessary to type in localhost in the address bar when using node.js and socket.io instead of simply opening the client.html file directly?

I am intrigued by this topic. My suspicion is that it may be related to the temporary file created by socket.io, but I'm struggling to fully understand it... ...

Utilizing ng For in a personalized directive to fill a selection menu

I encountered an issue while trying to populate a selected dropdown using ngRepeat inside a custom directive. I came across this example that seemed similar to what I wanted to achieve here. Although it worked for the example, it didn't work for me. ...

What are the steps for utilizing AJAX effectively?

I am currently experimenting with AJAX in order to achieve a seamless page update without the need for a reload. My goal is to have the value change dynamically when I switch the select button from 1 to 5, and have the number 5 displayed live. Additionall ...

Is it possible to include a while loop for iteration inside a AJAX success function?

I'm currently working on dynamically creating an accordion and populating the content of each tab using AJAX. In my main HTML page, there is an empty div reserved for the accordion: <div id="accordion"></div> The desired outcome is to ha ...

Is it possible to organize MongoDB records that possess identical update timestamps?

My goal is to validate a route within my Express server using Supertest. This particular route retrieves data from a MongoDB, and the data is then sorted based on the updatedAt field. While attempting to test the order of the output, I encountered an issu ...

Leveraging jQuery chosen for interactive form elements

This Table Row contains 5 input fields, with the first being a select box. I am utilizing the chosen jQuery plugin to enable search functionality for the select items. Since this is a dynamic form, I am duplicating these rows. However, I am facing an issu ...

Verify record removal without a PHP click

My website features a navigation menu that streamlines the browsing experience: <form action="../"> <select onchange="window.open(this.options[this.selectedIndex].value,'_top')"> <option value="" selected="selected">Navigate< ...

What is the best way to save a JSON stream to a file in Node.js?

I am facing an issue with writing a complete JSON object to a file as it is received. Currently, I am using const file = fs.createWriteStream('./example.file'); var inputStream = JSON.parse(generatedData); fs.write(inputStream+"\n"); The d ...

Vue.js: Issue with applying class binding while iterating over an object

I've been working with an object data that looks like this: object = { "2020092020-08-01":{ "value":"123", "id_number":"202009" }, "2020092020-09-01":{ "value& ...

Issue encountered with the DevExtreme npm module: Uncaught TypeError - $(...).dxButton is not recognized as a function

Instructions for installing DevExtreme npm can be found on their official page here: https://www.npmjs.com/package/devextreme var $ = require('jquery'); require('devextreme/ui/button'); var dialog = require('devextreme/ui/dialog&a ...

Compatibility issues arise when trying to use jQuery Mobile in conjunction with jQuery UI

I'm currently developing an HTML5 application that needs to function seamlessly on desktops, tablets, and mobile devices. However, I've encountered a hurdle when it comes to implementing progress bars and dialog boxes. Initially, I was using jQue ...

When an accordion is clicked, the content is dynamically loaded within the accordion on the page using PHP, jQuery, and AJAX

To optimize the loading speed of my information-filled page connected to two databases using php, javascript, jquery, I'm looking for a way to make the upload process faster. Currently, some data is displayed immediately while other details are hidden ...

Steps for bundling a Node server with an Electron application

I am looking to package my Electron app, built with React.js, along with a local Node server into a single executable file. Is there a way to ensure that the separate Node server runs simultaneously with the Electron app when the program is executed? ...

Modifying vertices in THREE.LineSegment: Adding and deleting

I am facing an issue with a THREE.LineSegments object, where I need to dynamically change the number of vertices. However, when I try to modify the geometry vertices array, the lines with removed vertices remain in place. Is there a way to remove vertices ...

Creating reactive behavior with a Promise initiated within a constructor - A guide

I am facing an issue with my Thing class. In the constructor, there is an asynchronous operation using fetch. Once the fetch completes, the result is assigned to a field in the Thing object: class Thing { constructor() { this.image = null ...