Search code examples
graphqlgraphql-java

GraphQL-codegen fails to load GraphQLSchema


So i have a problem loading a GraphQl schema using gql-codegen. When I try to generate, it fails with 404 error, however schema is available at http://localhost:8000/graphql below is the error. enter image description here

 Cannot convert undefined or null to object
      TypeError: Cannot convert undefined or null to object
      at Function.entries (<anonymous>)

I've tried to replace locahost with 127.0.0.1 in my npm file but i got the same result. Any help is much appreciated. Thanks in advance!


Solution

  • After some debugging I found that the error comes from ../node_modules/@graphql-tools/url-loader/cjs/index.js from the following method:

      class UrlLoader {
           ...
       handleSDL(pointer, fetch, options) {
           for (const [key, value] of Object.entries(options.headers)) {
                        if (key.startsWith(':')) {
                          // omit http2 headers
                          isHttp2 = true;
                        } else {
                          headers[key] = value
                        }
                      }   
            return new value_or_promise_1.ValueOrPromise(() => fetch(pointer, {
                    method: defaultMethod,
                    headers: typeof (options === null || options === void 0 ? void 0 : options.headers) === 'function' ? options.headers() : options === null || options === void 0 ? void 0 : options.headers,
                }))
        ... }
    

    The problem was that the options.headers property might be undefined or null, which cannot be iterated using Object.entries(). What solved my problem was adding a check to ensure that options.headers is defined before iterating through its entries:

    if (options.headers) {
      for (const [key, value] of Object.entries(options.headers)) {
        // ...
      }
    }
    

    And similarly, for the fetch call, I added a check to ensure that options.headers is defined before passing it to the fetch method.:

    return new value_or_promise_1.ValueOrPromise(() => fetch(pointer, {
      method: defaultMethod,
      headers: typeof options?.headers === 'function' ? options.headers() : options?.headers || {},
    })); 
    

    Then after running gql-gen again the error was gone and everything worked as expected.