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

Responses not typed in VS Code #591

Open
BorisKamp opened this issue Jan 10, 2025 · 4 comments
Open

Responses not typed in VS Code #591

BorisKamp opened this issue Jan 10, 2025 · 4 comments
Labels
bug Something isn't working

Comments

@BorisKamp
Copy link

Environment

Describe the bug

I remember in the past, that responses from Gql... auto created functions were typed, but in my recent project, that is no more.
See my screenshot here:
Screenshot 2025-01-10 at 09 09 02
response is any here...

In .nuxt/gql/default.ts I see the OrdersQuery generated, but it is not used somehow?
Screenshot 2025-01-10 at 09 09 45

Does anybody have a clue? It is very annoying that I get those TS errors because responses are any

Expected behaviour

The responses to be typed

Reproduction

No response

Additional context

No response

Logs

No response

@BorisKamp BorisKamp added the bug Something isn't working label Jan 10, 2025
@dacaga
Copy link

dacaga commented Jan 15, 2025

Same here, for SSR code only. Vuejs files seem to be using types from .nuxt/types/imports.d.ts and are typed properly. I can manually change the typeof import in nitro-imports.d.ts from typeof import('#gql-nitro') to typeof import('#gql') and it then works for server side code.

@dacaga
Copy link

dacaga commented Jan 15, 2025

Probably related to #333 and its proposed fix!

@BorisKamp
Copy link
Author

BorisKamp commented Jan 15, 2025

Probably related to #333 and its proposed fix!

That sounds good, when can we expect the fix in a release? And does that also mean the broken fragments are fixed?

@Moonlight63
Copy link

Moonlight63 commented Mar 3, 2025

The issue of not having typing information doesn't look to have anything to do with server fragments. Rather it has everything to do with no types being generated for the #gql-nitro module!

I ended up making a patch for the current release that fixes the missing types, and I think it also fixes server fragments. If you know how to use patches with patch-package, here you go:

nuxt-graphql-client+0.2.43.patch

diff --git a/node_modules/nuxt-graphql-client/dist/module.mjs b/node_modules/nuxt-graphql-client/dist/module.mjs
index 940d58f..1d38edc 100644
--- a/node_modules/nuxt-graphql-client/dist/module.mjs
+++ b/node_modules/nuxt-graphql-client/dist/module.mjs
@@ -146,6 +146,9 @@ async function prepareContext(ctx, prefix) {
       ...ctx.fns.map((f) => fnExp(f, true)),
       `  type GqlSdkFuncs = ${ctx.clients?.map((c) => `ReturnType<typeof ${c}GqlSdk>`).join(" & ") || "any"}`
     ],
+    "}",
+    "declare module '#gql-nitro' {",
+    `  export * from '#gql'`,
     "}"
   ].join("\n");
   ctx.fnImports = ctx.fns.map((fn) => ({ from: "#gql", name: fnName(fn) }));
@@ -362,6 +365,8 @@ const module = defineNuxtModule({
     if (config.autoImport) {
       nuxt.options.alias["#gql"] = resolver.resolve(nuxt.options.buildDir, "gql");
       nuxt.options.alias["#gql/*"] = resolver.resolve(nuxt.options.buildDir, "gql", "*");
+      nuxt.options.alias["#gql-nitro"] = resolver.resolve(nuxt.options.buildDir, "gql");
+      nuxt.options.alias["#gql-nitro/*"] = resolver.resolve(nuxt.options.buildDir, "gql", "*");
       addTemplate({
         filename: "gql.mjs",
         getContents: () => ctx.generateImports?.() || ""
@@ -394,18 +399,41 @@ const module = defineNuxtModule({
         return [...acc, `${client}: ` + mockTemplate(entries).replace("export ", "")];
       }, []);
       nitro.virtual = nitro.virtual || {};
-      nitro.virtual["#gql-nitro"] = [
-        "const clientSdks = {" + clientSdks + "}",
-        "const config = " + JSON.stringify(config.clients),
-        "const ops = " + JSON.stringify(ctx.clientOps),
-        "const clients = {}",
-        "const useGql = (op, variables = undefined) => {",
-        " const client = Object.keys(ops).find(k => ops[k].includes(op))",
-        " return clientSdks[client](clients?.[client])[op](variables)",
-        "}",
-        ctx.fns?.map((fn) => `export const ${config.functionPrefix + upperFirst(fn)} = (...params) => useGql('${fn}', ...params)`).join("\n"),
-        "export default { clients, config }"
-      ].join("\n");
+      nitro.virtual['#gql-nitro'] = [
+        'import { GraphQLClient } from "graphql-request"',
+        ...ctx.clients.map(client => `import { getSdk as ${client}Sdk } from "#gql/${client}"`),
+        'const config = ' + JSON.stringify(config.clients),
+        'const ops = ' + JSON.stringify(ctx.clientOps),
+        'const clients = {}',
+        'const sdks = {}',
+        '',
+        'function getSdkForKey(key) {',
+        '  if (!sdks[key]) {',
+        '    const client = clients[key]',
+        '    switch(key) {',
+        ...ctx.clients.map(client => `      case "${client}": sdks[key] = ${client}Sdk(client); break;`),
+        '      default: throw new Error(`Unknown GraphQL client: ${key}`)',
+        '    }',
+        '  }',
+        '  return sdks[key]',
+        '}',
+        '',
+        'const useGql = (op, ...params) => {',
+        "  const key = Object.keys(ops).find(k => ops[k].includes(op)) || 'default'",
+        '  const sdk = getSdkForKey(key)',
+        '  return sdk[op](...params)',
+        '}',
+        '',
+        ctx.fns
+          ?.map(
+            (fn) =>
+              `export const ${
+                config.functionPrefix + upperFirst(fn)
+              } = (...params) => useGql('${fn}', ...params)`
+          )
+          .join('\n'),
+        'export default { clients, config }',
+      ].join('\n')
       nitro.imports = defu(nitro.imports, {
         presets: [{
           from: "#gql-nitro",

Basically for types, I am just adding a type export for gql-nitro, and that module re-exports everything from gql.
Its a hack, but it works.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

3 participants