Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot access 'resolvers' before initialization #1255

Closed
zhaodong-wang opened this issue Apr 1, 2022 · 9 comments
Closed

Cannot access 'resolvers' before initialization #1255

zhaodong-wang opened this issue Apr 1, 2022 · 9 comments
Labels
Question ❔ Not future request, proposal or bug issue Solved ✔️ The issue has been solved

Comments

@zhaodong-wang
Copy link

I was trying to follow the typegraphql-prisma tutorial but got some unexpected error. To repro this:

  1. In .prisma file add:
generator typegraphql {
  provider           = "typegraphql-prisma"
  output             = "../prisma/generated/type-graphql"
}
  1. In Bootstrapping, with next.js
import { resolvers } from "../prisma/generated/type-graphql";


const apolloServerInitialized = (async () => {
  // build schema before initializing apollo server
  const apolloServer = new ApolloServer({
    schema: await tq.buildSchema({
      resolvers,
      validate: false,
    }),
    context: context,
    introspection: true,
  });

  await apolloServer.start();

  return apolloServer;
})();

export const apolloServer = async (
  req: NextApiRequest,
  res: NextApiResponse
) => {
  const apolloServer = await apolloServerInitialized;

  const apolloHandler = apolloServer.createHandler({
    path: req.url,
  });

  await apolloHandler(req, res);
};

Then I got error: Cannot access 'resolvers' before initialization.

By tsconfig is as follows:

{
  "compilerOptions": {
    "sourceMap": true,
    "outDir": "dist",
    "strict": true,
    "esModuleInterop": true,
    "target": "es2018",
    "module": "commonjs",
    "lib": [
      "es2018",
      "esnext.asynciterable"
    ],
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "jsx": "preserve",
    "allowJs": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "incremental": true,
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true
  },
  "exclude": [
    "node_modules"
  ],
  "include": [
    "**/*.ts",
    "**/*.tsx"
  ]
}

NOTE:
This error only happens when I generate typegraphql files with customized output folder, and when the generated code is emitted as a raw TS source code. If I don't set output in .prisma file, and use import { resolvers } from "@generated/type-graphql"; with the transpiled code, there will not be such error.

However, I have to use the raw TS source code since I have some customized resolver with need the Types generated for @Args.

@zhaodong-wang
Copy link
Author

zhaodong-wang commented Apr 1, 2022

This seems like an issue with next.js, I only have this error when trying to use API route as the endpoint of the graphql API. But if I just simply write a script like this


const main = async () => {
  const server = new ApolloServer({
    schema: await tq.buildSchema({
      resolvers,
      validate: false,
    }),
    context: context,
    introspection: true,
  });

  const { port } = await server.listen(4000);
  console.log(`GraphQL is listening on http://localhost:${port}`);
};

main();

It works as expected.

But I am curious why using API route will yield this initialization error.

@MichalLytek
Copy link
Owner

I think it's because of the way NextJS bundle the code. See #55 and other related issues.

@MichalLytek MichalLytek added the Question ❔ Not future request, proposal or bug issue label Apr 1, 2022
@zhaodong-wang
Copy link
Author

Thanks @MichalLytek, regarding #55, which solution do you think might be a potential fix for this?

@zhaodong-wang
Copy link
Author

I tried using the babelrc as follows:

{
  "presets": ["next/babel"],
  "plugins": [
    ["@babel/plugin-proposal-decorators", { "legacy": true }],
    "@vjpr/babel-plugin-parameter-decorator",
    ["@babel/plugin-proposal-class-properties", { "loose": true }],
    "babel-plugin-transform-typescript-metadata"
  ]
}

But still get the same error.

@MichalLytek
Copy link
Owner

I think the error is caused by NextJS trying to bundle the whole API into a single file. This causes issues when you have references between your types (classes). The one below is not created yet, etc.

@zhaodong-wang
Copy link
Author

zhaodong-wang commented Apr 1, 2022

@MichalLytek I see, does that mean if we are using NextJS we have to set emitTranspiledCode = true?

But setting this I will not be able to reuse the types generated, and got errors like:

Error: Unable to infer GraphQL type from TypeScript reflection system. You need to provide explicit type for parameter #1 of '<someFunction>' of '<someResolver>' class.

@MichalLytek
Copy link
Owner

The transpiled code behaves just like a normal source code - you can import the classes, use them as values or as types.
The problem in your code might be somewhere else.

@MichalLytek
Copy link
Owner

Closing for a housekeeping purposes 🔒

@MichalLytek MichalLytek added the Solved ✔️ The issue has been solved label May 1, 2022
@devnaumov

This comment was marked as spam.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Question ❔ Not future request, proposal or bug issue Solved ✔️ The issue has been solved
Projects
None yet
Development

No branches or pull requests

3 participants