Code Monkey home page Code Monkey logo

ts-graphql-plugin's People

Contributors

andrew-w-ross avatar enzoferey avatar eseliger avatar felixfbecker avatar forivall avatar fregante avatar greenkeeper[bot] avatar hallettj avatar helfer avatar jesse-savary avatar kaicataldo avatar quramy avatar renovate-bot avatar renovate[bot] avatar thebartekbanach avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

ts-graphql-plugin's Issues

Update peer dependencies

The library has the following peer dependencies:

"peerDependencies": {
  "graphql": "^0.10.2",
  "typescript": "^2.3.0"
},

These should be updated to work with TypeScript 3 and latest graphql, something like:

"peerDependencies": {
  "graphql": "^0.13.0 | ^14.0.0",
  "typescript": "^2.3.0 | ^3.0.0"
},

Having trouble getting this to work

I can't tell if the plugin isn't loading or VSCode isn't picking up the completion or if my schema json is invalid. Could you possibly point me in the right direction for debugging this?

An in-range update of graphql-language-service-interface is breaking the build 🚨

The dependency graphql-language-service-interface was updated from 2.1.0 to 2.3.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

graphql-language-service-interface is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • ❌ wercker/build: Wercker pipeline failed (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

[typegen] Nullable params should be optional

Nullable GraphQL fields are also optional. I can make a method to update a certain entity in my API, and only pass some fields, instead of whole object if his params are not-required. But types generated by ts-graphql-plugin are required, even if they are nullable:

export type SomeMutationVariables = {
    entityData: {
        id: number;
        param1: string | null;
        param2: number | null;
        param3: boolean | null;
    };
};

instead of

export type SomeMutationVariables = {
    entityData: {
        id: number;
        param1?: string | null;
        param2?: number | null;
        param3?: boolean | null;
    };
};

TypeScript auto-import completions are not shown (e.g., in VS Code) when this plugin is enabled

When ts-graphql-plugin was in our tsconfig.json, it made TypeScript auto-import completions no longer work. (I.e., when you start to type part of an identifier, it can show things that, upon completion, result in a new import statement at the top of the file. Those no longer were shown in the menu, only global TS lib defs and file-local scope items were shown.) This could be a problem specific to auto-imports, or a more general problem where this plugin prevented TypeScript from analyzing the project scope.

This problem started occurring only a few days ago for me, and I can't figure out what changed, so I accept that this bug report is short on details and repro steps. I will let you know if anyone else on our team has more info to share.

Thank you for making this great plugin, btw! It is otherwise awesome. We will continue to look into this on our end at @sourcegraph and (hopefully) submit a PR with a fix. If you have any pointers, that would be super helpful.

Details

Version: [email protected] from npm
TypeScript: [email protected]
Running in VS Code 1.25.1 on Linux (although my teammates on Mac also reported the same issue)

tsconfig.json plugin entry:

{
  "name": "ts-graphql-plugin",
  "schema": "graphqlschema.json",
  "tag": "gql"
}

The graphqlschema.json file is confirmed to be valid JSON.

this._logger in the code did not print any errors (or any messages other than Build client schema.). getCompletionAtPosition did not throw any exceptions (when I added a try...catch around it).

The tsserver.log contained no error logs related to this plugin (or any others).

ts-graphql-plugin doesn't see "schema" in tsconfig


name: Bug report
about: Create a report to help us improve
title: 'ts-graphql-plugin doesn't see "schema" in tsconfig'
labels: ''
assignees: ''
---Describe the bug
When I try to use the schema property in tsconfig, validate says that there's no schema field.

To Reproduce

  • Clone:
git clone https://github.com/komfy/frontend.git
{
  "compilerOptions": {
    "target": "es2017",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": false,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "alwaysStrict": false,
    "isolatedModules": true,
    "jsx": "preserve",
    "allowSyntheticDefaultImports": true,
    "preserveSymlinks": true,
    "plugins": [
      {
        "name": "ts-graphql-plugin",
        "schema": {
          "http": {
            "method": "POST",
            "url": "https://komfy.herokuapp.com/graphql"
          }
        },
        "tag": "gql"
      }
    ]
  },
  "exclude": ["node_modules"],
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"]
}
  • Run pnpx ts-graphql-plugin validate -p tsconfig.json --verbose

Expected behavior
It should read the schema property and validate properly

If the bug occurs on CLI, paste log with --verbose option.

➜ pnpx ts-graphql-plugin validate -p tsconfig.json --verbose
Found 1 errors:
error: No GraphQL schema. Confirm your ts-graphql-plugin's "schema" configuration at tsconfig.json's compilerOptions.plugins section.

Additional context

GraphQL api itself works fine:

image

Extend schema

We need ways to extend server-side schema. For example, with apollo local state , developers write operations such as:

const query = gql`
  query LocalQuery {
     userForm @client {
       name
       age
     }
  }
`;

But for now this plugin reports errors that @client and userForm type are not defined in server-side schema.

To suppress this ( or to complete local type fields or directives ), this plugin needs to support to extend server-side schema with client-only schema files.

## local.graphql

directive @client on FIELD
type UserForm {
  name: String!
  age: Int!
}

extend type Query {
  userForm: UserForm!
}
/* tsconfig.json */

"plugins": [
  { 
     "name": "ts-graphql-plugin",
     "schema": "./schema.graphql", /* derived from server */
     "localSchema": ["./local.graphql"], /* client only schema */
  } 
]

Schema from URL / GQL endpoint

It would be very useful if i could set the gql-endpoint in the config for the schema instead of a json-file. especially in development scenarios where the graphql-api is developed in parallel with the frontend it would save a lot of time to keep the schema up to date.

Empty variables, consider using `never` type?

First, thank you so much for this wonderful project! It's extremely impressive and I've been very happy with it overall.

I did run into one small issue for a query with no variables, e.g.

const QUERY = gql`
  query Users {
    users {
      id
      name
    }
  }
`

For this query, the generated type of the UsersVariables would be:

export type UsersVariables = {};

Unfortunately, TypeScript is a bit overly permissive with the {} literal value and will allow any object to be assigned:

type UsersVariables = {}

// The following is incorrect as the query takes no variables,
// but the typing allows it
const variables: UsersVariables = { name: 'hello' }

// Using a more restrictive type, we can prevent this:
type UsersVariablesNever = { [index: string]: never };
// This line will now properly highlight the `name` value
// as an error since the query doesn't accept any variables
const neverVariables: UsersVariablesNever = { name: 'hello' }

TypeScript playground with this example


My suggestion would be to use the more restrictive { [index: string]: never } instead of {} for empty variable type definitions.

Remove duplication of fragments


name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---Describe the bug
A clear and concise description of what the bug is.

To Reproduce

fragmentA = gql`
fragment A on Hoge {
  id
}
`;

fragmentB = gql`
${fragmentA}
fragment B on Hoge {
  ...A
  name
}
`;

fragmentC = gql`
${fragmentA}
fragment C on Hoge {
  ...A
  url
}
`;

query = gql`
${fragmentB}
${fragmentC}
query MyQuery {
  ...B
  ...C
}
`;

In this case, the query has 2 definitions of fragmentA and naive GraphQL validator reports "there can be only one fragment named A". It means editor reports this message as diagnostic.
But smart clients (e.g. apollo) removes the duplication so the query works well on runtime.

Expected behavior

The error about duplication of fragments can be suppressed. This plugin needs new option such as suppressFragmentDuplication: boolean

An in-range update of husky is breaking the build 🚨

The devDependency husky was updated from 4.0.8 to 4.0.9.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

husky is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • βœ… codecov/project: 84.42% remains the same compared to 2d6c6f8 (Details).
  • βœ… codecov/patch: Coverage not affected when comparing 2d6c6f8...e649400 (Details).
  • ❌ publish (12.x): There are 2 failures, 0 warnings, and 0 notices.
  • βœ… build (12.x): null

Release Notes for v4.0.9
  • Fix: read stdin from hook script (#645)
Commits

The new version differs by 2 commits ahead by 2, behind by 2.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

TS IntelliSense doesn't show any completion for queries in VS Code


name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---Describe the bug
Generated types aren't used by VS Code, so there are no any auto-completion options showing

To Reproduce

My case

  1. Run API, then generate types using pnpx ts-graphql-plugin typegen
  2. Extend Next.js config:
const TsGraphQLPlugin = require('ts-graphql-plugin/webpack')

const tsgqlPlugin = new TsGraphQLPlugin()

module.exports = {
  target: 'serverless',
  env:
    { API: 'http://localhost:8080', GRAPHQL: 'http://localhost:8080/graphql' },
  webpack: config => {
    config.module.rules.push({
      test: /\.tsx?$/,
      exclude: /node_modules/,
      loader: 'ts-loader',
      options: {
        getCustomTransformers: () => ({
          before: [tsgqlPlugin.getTransformer()]
        })
      }
    })
    return config
  }
}
  1. Put plugin inside of tsconfig:
{
  "compilerOptions": {
  // ...
    "plugins": [
      {
        "name": "ts-graphql-plugin",
        "schema": {
          "http": {
            "method": "POST",
            "url": "http://localhost:8080/graphql"
          }
        },
        "tag": "gql"
      }
    ]
  },
// ...
}

Manual installation

Clone two repos, build api, launch it, then build frontend

  • API
git clone https://github.com/komfy/api.git
cd api
go mod download
go run dev-server/server.go
  • Frontend
git clone https://github.com/komfy/frontend.git
cd frontend
pnpm i # or npm i
pnpm run dev # or npm run dev
pnpx ts-graphql-plugin typegen # or npx ts-graphql-plugin typegen

Expected behavior
I expected my exported types to autocomplete my queries

Debug log

image

fetching schema with http without explicitly specifying method causes unexpected 'No GraphQL schema.' error

Describe the bug
Not explicitly defining "method": "POST" in tsconfig.json causes npx ts-graphql-plugin validate --verbose to fail. On top of that, it fails with a wrong error message so it took me a good half hour to figure out. It fails with the following error message:

error: No GraphQL schema. Confirm your ts-graphql-plugin's "schema" configuration at tsconfig.json's compilerOptions.plugins section.

To Reproduce
Use schema over http without explicitly specifying method, like:

"plugins": [
      {
        "name": "ts-graphql-plugin",
        "schema": {
          "http": {
            "url": "http://xy.com/graphql", // whatever your graphql endpoint is
            // "method": "POST"  // do not specify it explicitly and it will fail
          }
        },
        "tag": "gql"
      }
    ]

Expected behavior
I've read in the documentation that one can omit "method": "POST" from tsconfig.json since that is the default. If that is not explicitly written in config, plugin silently fails, even with verbose flag. Either the documentation could be updated (willing to do a PR if needed) and error message could be updated, or it should be fixed in the package to fallback to POST even if not explicitly defined.

PS: great plugin and keep it going, thanks for your work.

An in-range update of typescript is breaking the build 🚨

Version 2.3.4 of typescript just got published.

Branch Build failing 🚨
Dependency typescript
Current Version 2.3.3
Type peerDependency

This version is covered by your current version range and after updating it in your project the build failed.

As typescript is β€œonly” a peerDependency of this project it might not break production or downstream projects, but β€œonly” your build or test tools – preventing new deploys or publishes.

I recommend you give this issue a high priority. I’m sure you can resolve this πŸ’ͺ

Status Details
  • ❌ wercker/build Wercker pipeline failed Details

Release Notes TypeScript 2.3.4

This release includes a new flag for tsserver to specify location of npm for nvm users.

Download:

Commits

The new version differs by 12 commits.

  • 1a579d9 Update LKG
  • e023dc3 Merge pull request #16113 from Microsoft/fixNpmLocationWithSpaces
  • d7555ed Fix equals
  • 47a0a7c Wrap npmLocation if needed
  • 47bd5af Allow configurable npmLocation for typingsInstaller (#16084) (#16102)
  • d333378 Merge branch 'release-2.3' of https://github.com/Microsoft/TypeScript into release-2.3
  • f80ca90 Add project telemetry (#16085)
  • fc4d109 Fix build breaks with the instrumenter
  • 196aba6 Merge pull request #16051 from Microsoft/PortRulesProviderFixToRelease-2.3
  • 9919b58 Updating compiler release version to 2.3.4
  • 3b9ef4e Changes from CR feedback
  • dcab328 RulesProvider performance improvements

See the full diff

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

RangeError: Maximum call stack size exceeded

First and foremost, thank you to @Quramy for this incredible plugin, the types it creates are very easy to be consumed in a React project. Recently I ran into some problem when it failed to generate types for my mutation which takes a list of things as an argument. For example:

  mutation($tags: [tag_insert_input!]!) {
    insert_tag(objects: $tags) {
      affected_rows
      returning {
        id
      }
    }
  }

Stacktrace:

RangeError: Maximum call stack size exceeded
 at /Users/bday/Code/ts-graphql-plugin-reproduce/node_modules/ts-graphql-plugin/lib/typegen/type-gen-visitor.js:131:33
    at Array.forEach (<anonymous>)
    at visitVariableType (/Users/bday/Code/ts-graphql-plugin-reproduce/node_modules/ts-graphql-plugin/lib/typegen/type-gen-visitor.js:129:70)
    at /Users/bday/Code/ts-graphql-plugin-reproduce/node_modules/ts-graphql-plugin/lib/typegen/type-gen-visitor.js:131:33
    at Array.forEach (<anonymous>)
    at visitVariableType (/Users/bday/Code/ts-graphql-plugin-reproduce/node_modules/ts-graphql-plugin/lib/typegen/type-gen-visitor.js:129:70)
    at /Users/bday/Code/ts-graphql-plugin-reproduce/node_modules/ts-graphql-plugin/lib/typegen/type-gen-visitor.js:131:33
    at Array.forEach (<anonymous>)
    at visitVariableType (/Users/bday/Code/ts-graphql-plugin-reproduce/node_modules/ts-graphql-plugin/lib/typegen/type-gen-visitor.js:129:70)
    at /Users/bday/Code/ts-graphql-plugin-reproduce/node_modules/ts-graphql-plugin/lib/typegen/type-gen-visitor.js:131:33
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

I created a project to reproduce the issue here: https://github.com/bday2009/ts-graphql-plugin-reproduce

This is a fairly common pattern and I guess everybody else is doing it, however I couldn't find a similar issue. Maybe it's something I overlooked on my part?

Thank you in advanced.

graphql rename causes problems for webpack parser (Error: Cannot find module 'graphql/validation/rules/ExecutableDefinitions')


name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---Describe the bug
The graphql package renamed its validation rule(s). This causes errors with this project, as e.g. 'graphql/validation/rules/ExecutableDefinitions' is linked.
This is the case with the webpack plugin

Expected behavior
use webpack plugin with newest graphql

'''Solution**
Update imports

Allow to customize type generation

Motivation

  • User defined Scalar type
  • Export more complex type using generated query result or variables types (e.g #230 )

type-generator core should be responsible for only converting from query to ts type. Customization the types should be implemented by other layer.

Generic library for providing template string intellisense

Thanks for your work on this plugin! I recently forked it to create a similar plugin for styled components and am now looking into creating a more generic library to simplify providing a language service for template strings. The idea is that styled plugin and other plugins like yours could use this library. Here's the prototype: https://github.com/Microsoft/typescript-template-language-service-decorator

Let me know if you'd be interested in using this library or have any feedback on the API. Besides abstracting away many of the details of working with template strings, the library also has basic support for substitutions

[vim] No completion nor errors

ts-graphql-plugin version: 57d27a0 (latest commit built via npm run compile and then npm linked to global node_modules)
tsserver: 3.0.1 (/usr/local/bin/tsserver)

I'm using youcompleteme to manage tsserver and am successfully getting completion for regular typescript. I don't get anything from this plugin however. The plugin doesn't report any errors, and appears to successfully parse the ./gql-schema.json containing the result of a regular introspection query. After the initial parsing it doesn't log anything else however.

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "allowJs": true,
    "resolveJsonModule": true,
    "allowSyntheticDefaultImports": true,
    "downlevelIteration": false,
    "experimentalDecorators": true,
    "suppressImplicitAnyIndexErrors": true,
    "lib": [
      "es2015",
      "es2016",
      "es2017",
      "dom"
    ],
    "plugins": [
      {
        "name": "ts-graphql-plugin",
        "schema": "./gql-schema.json",
        "tag": "gql"
      }
    ]
  },
  "include": [
    "app"
  ],
  "exclude": [
    "node_modules"
  ]
}

tsserver logs

Info 16   [17:4:27.426] Enabling plugin ts-graphql-plugin from candidate paths: /usr/local/lib/node_modules/typescript/lib/tsserver.js/../../..
Info 17   [17:4:27.427] Loading ts-graphql-plugin from /usr/local/lib/node_modules/typescript/lib/tsserver.js/../../.. (resolved to /usr/local/lib/node_modules/node_modules)
Info 18   [17:4:28.437] [ts-graphql-plugin] config: {"name":"ts-graphql-plugin","schema":"./gql-schema.json","tag":"gql"}
Info 19   [17:4:28.438] [ts-graphql-plugin] Read schema from {REDACTED}/gql-schema.json
Info 20   [17:4:28.484] [ts-graphql-plugin] Build client schema.
Info 21   [17:4:28.485] Plugin validation succeded
...

Example code

const gql = x => x

// No completion whatsoever when writing the contents below:
console.log(gql`
  query {
    me {
      ...on User {
        name
      }
      ...on 
    }
  }
`)

Feature Request: Cleanup generated files

When a query name changes or is completely removed the generated types still remain.
Is it possible to get a prune option for typegen that will remove any files in generated that weren't created in that run?

I'd be happy to create a pr.

Tags ReturnType

There is any possibility to define the return type of tag, on the basis of the query?

I need it to create custom typed fetcher, like it:

example

support multiple schemas

We have multiple schemas in a single project, so we need to be able to register multiple schemas. Is this possible?

Support GraphQL source as schema

I can generate the schema.json file, but it seems like it would be far easier to just pass the .graphql schema source and have ts-graphql-plugin generate the schema JSON. Are there any limitations that make that impossible or impractical?

Examine the possibility to use type from queries without generation


name: Feature request
about: Examine the possibility to use type from queries without generation
title: 'Create a function/generic to return the expected result of a query'
labels: 'question, feature request'
assignees: ''

---Describe the feature
Since typescript knows, thanks to this plugin, what are the expected key name and type of any query, could it be possible to have some sort of function or generic that would return the data from a query, without having to generate them?

It would replace:

const mouseQuery = gql`
query Mouse($mouseId: String!) {
  mouse(mouseId: $mouseId) {
    name
    bio {
      full
    }
  }
}
`
// generated types
type Mouse = {
    mouse: ({
        name: string;
        bio: ({
            full: string;
        }) | null;
    }) | null;
};
type MouseVariables = {
    mouseId: string;
};

with

// names may vary
import {
    TypeFromQuery,
    VariableTypeFromQuery
} from 'ts-graphql-plugin';

const mouseQuery = gql`
query Mouse($mouseId: String!) {
  mouse(mouseId: $mouseId) {
    name
    bio {
      full
    }
  }
}
`
type Mouse = TypeFromQuery<mouseQuery>;
type MouseVariables = VariableTypeFromQuery<mouseQuery>;

Since we can have auto-completion for queries and query type generation, what would we need to make this happen?

--

Thanks a lot for this plugin, love it!

Extract CLI or API

We can reuse GraphQL operations extracted from template literals, such as validation CLI or other static query analysis.

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Error type: undefined. Note: this is a nested preset so please contact the preset author if you are unable to fix it yourself.

Ensure compatibility with Typescript integrated in vscode

Right now the plugin does not work when used without installing as a dev dependency and referencing the tsserver to use the local version.

I have already excluded version conflicts by testing:

Does work:

  • 2.5.3 (dev dependency)

Does not work:

  • 2.5.3 (vscode build in) no intellisene in gql tags

No changes were made to project or package.json in the meanwhile. You can easily repro it by downloading your project and remove the workspace setting.

Since this doesn't seem to be a version issue, any idea why this breaks?

An in-range update of @types/node is breaking the build 🚨

The devDependency @types/node was updated from 12.12.7 to 12.12.8.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@types/node is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ wercker/build: Wercker pipeline failed (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Ignored or Blocked

These are blocked by an existing closed PR and will not be recreated unless you click a checkbox below.

Detected dependencies

github-actions
.github/workflows/build.yml
  • actions/checkout v4@0ad4b8fadaa221de15dcec353f45205ec38ea70b
  • actions/setup-node v4
  • codecov/codecov-action v4
  • codecov/codecov-action v4
.github/workflows/publish.yml
  • actions/checkout v4@0ad4b8fadaa221de15dcec353f45205ec38ea70b
  • actions/setup-node v4
  • actions/github-script v7
npm
package.json
  • graphql-language-service ^5.2.0
  • @types/jest 29.5.12
  • @types/node 20.12.8
  • @types/node-fetch 3.0.2
  • @typescript-eslint/eslint-plugin 7.7.0
  • @typescript-eslint/parser 7.7.0
  • c8 9.1.0
  • eslint 8.57.0
  • eslint-config-prettier 9.1.0
  • fretted-strings 2.0.0
  • glob 10.3.12
  • graphql 16.8.1
  • graphql-config 5.0.3
  • husky 9.0.11
  • jest 29.7.0
  • markdown-toc 1.2.0
  • msw 2.2.14
  • npm-run-all2 6.1.2
  • prettier ^3.2.5
  • pretty-quick 4.0.0
  • rimraf 5.0.5
  • talt 2.4.4
  • ts-jest 29.1.2
  • ts-loader 9.5.1
  • ts-node 10.9.2
  • typescript 5.4.5
  • typescript-eslint-language-service 5.0.5
  • webpack 5.91.0
  • webpack-cli 5.1.4
  • graphql ^15.0.0 || ^16.0.0
  • typescript ^4.8.0 || ^5.0.0
  • node >=18
project-fixtures/gql-errors-prj/package.json
  • graphql 16.8.1
  • typescript 5.4.5
project-fixtures/graphql-codegen-prj/package.json
  • @apollo/client 3.10.2
  • @graphql-codegen/cli 5.0.2
  • @graphql-codegen/client-preset 4.2.5
  • @graphql-codegen/typescript 4.0.6
  • @graphql-codegen/typescript-document-nodes 4.0.6
  • @types/react 18.3.1
  • @types/react-dom 18.3.0
  • graphql 16.8.1
  • prettier 3.2.5
  • react 18.3.1
  • react-dom 18.3.1
  • typescript 5.4.5
project-fixtures/react-apollo-prj/package.json
  • @apollo/client 3.10.2
  • @types/react 18.3.1
  • @types/react-dom 18.3.0
  • graphql 16.8.1
  • react 18.3.1
  • react-dom 18.3.1
  • typescript 5.4.5

  • Check this box to trigger a request for Renovate to run again on this repository

schema not found error

I get no completion or diagnostics. I tried also running this command but I get the following error:

$> npx ts-graphql-plugin validate -p tsconfig.server.json
Error: No GraphQL schema. Confirm your ts-graphql-plugin's "schema" configuration at tsconfig.json's compilerOptions.plugins section.

These are my tsconfg.server.json plugin settings:

    "plugins": [
      {
        "name": "ts-graphql-plugin",
        "schema": "./graphql/admin-api-schema.json",
        "tag": "gql"
      }
    ]

The same schema works with eslint-plugin-graphql though.

Substituting Template String

Now, adapter can treat only NonSubstituting Template Strings.

const query = ` query { }`            // it works
const query = ` query { ${foo} }` // it does not work

My problem is :

  • How to treat substituting params (e.g. ${foo} ). For example, in getSemanticDiagonistics, is it right to ignore the parameters ?

Custom transformer

And static QraphQL transformation ( e.g. climber side only directives)

"No GraphQL schema" error (GitHub API)

Like #106, but for GitHub’s schema

Describe the bug

❯ npx ts-graphql-plugin typegen --verbose
Found 1 errors generating type files.

error: No GraphQL schema. Confirm your ts-graphql-plugin's "schema" configuration at tsconfig.json's compilerOptions.plugins section.
No type files to generate.

To Reproduce

{
	"extends": "@sindresorhus/tsconfig",
	"compilerOptions": {
		"target": "es2022",
		"module": "es2022",
		"moduleResolution": "Node",
		"noUncheckedIndexedAccess": false,
		"noPropertyAccessFromIndexSignature": false,
		"lib": [
			"DOM",
			"DOM.Iterable",
			"ES2022"
		],
		"plugins": [
			{
				"name": "ts-graphql-plugin",
				"schema": "https://docs.github.com/public/schema.docs.graphql",
				"typegen": {
					"addons": [
						"ts-graphql-plugin/addons/typed-query-document"
					]
				}
			}
		]
	},
	"include": [
		"source",
		"test",
		"build",
		"webpack.config.ts"
	]
}

Additional context

I'm able to download the schema from the browser, but the suggested curl command fails:

curl -X POST -H "Content-Type: application/json" -d '{"query":"\n query IntrospectionQuery {\n __schema {\n queryType { name }\n mutationType { name }\n subscriptionType { name }\n types {\n ...FullType\n }\n directives {\n name\n description\n locations\n args {\n ...InputValue\n }\n }\n }\n }\n\n fragment FullType on __Type {\n kind\n name\n description\n fields(includeDeprecated: true) {\n name\n description\n args {\n ...InputValue\n }\n type {\n ...TypeRef\n }\n isDeprecated\n deprecationReason\n }\n inputFields {\n ...InputValue\n }\n interfaces {\n ...TypeRef\n }\n enumValues(includeDeprecated: true) {\n name\n description\n isDeprecated\n deprecationReason\n }\n possibleTypes {\n ...TypeRef\n }\n }\n\n fragment InputValue on __InputValue {\n name\n description\n type { ...TypeRef }\n defaultValue\n }\n\n fragment TypeRef on __Type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n }\n }\n }\n }\n }\n }\n }\n }\n "}' https://docs.github.com/public/schema.docs.graphql

<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'><html xmlns='http://www.w3.org/1999/xhtml'><head><meta content='text/html; charset=utf-8' http-equiv='content-type'/><style type='text/css'>body { font-family:Arial; margin-left:40px; }img  { border:0 none; }#content { margin-left: auto; margin-right: auto }#message h2 { font-size: 20px; font-weight: normal; color: #000000; margin: 34px 0px 0px 0px }#message p  { font-size: 13px; color: #000000; margin: 7px 0px 0px 0px }#errorref { font-size: 11px; color: #737373; margin-top: 41px }</style><title>Microsoft</title></head><body><div id='content'><div id='message'><h2>The request is blocked.</h2></div><div id='errorref'><span>06+J2ZAAAAAAnNfhTqbSpR5M7KXwz7WHBUEhMMzBFREdFMDMxOQA1OTZkNzhhMi1jYTVmLTQ3OWQtYmNkYy0wODM1ODMzMTc0YjI=</span></div></div></body></html>⏎

Typescript 4.8.2 breaking changes

Describe the bug
It seems that there is a breaking change on typescript 4.8.2, here is the error message I get:
TypeError: Cannot create property 'pos' on string 'QueryResults'

I downgraded to version 4.7.4 and I didn't have any issue.

To Reproduce
Steps to reproduce the behavior:

  • update typescript version to 4.8.2
  • run yarn typegen

Expected behavior
typegen commande should be running as expected

debug logs:
here is the full log I get:

TypeError: Cannot create property 'pos' on string 'QueryResults'
at setTextRangePos (/Users/user1/workdev/talent-front/community-app/node_modules/typescript/lib/typescript.js:21409:19)
    at Object.setTextRangePosEnd (/Users/user1/workdev/talent-front/community-app/node_modules/typescript/lib/typescript.js:21427:32)
    at createNodeArray (/Users/user1/workdev/talent-front/community-app/node_modules/typescript/lib/typescript.js:23022:16)
    at asNodeArray (/Users/user1/workdev/talent-front/community-app/node_modules/typescript/lib/typescript.js:27553:28)
    at createBaseGenericNamedDeclaration (/Users/user1/workdev/talent-front/community-app/node_modules/typescript/lib/typescript.js:23074:35)
    at Object.createTypeAliasDeclaration (/Users/user1/workdev/talent-front/community-app/node_modules/typescript/lib/typescript.js:25496:24)
    at Object.createTypeAliasDeclaration (/Users/user1/workdev/talent-front/community-app/node_modules/typescript/lib/typescript.js:3324:29)
    at TypeGenVisitor._createTsTypeDeclaration (/Users/user1/workdev/talent-front/community-app/node_modules/ts-graphql-plugin/lib/typegen/type-gen-visitor.js:338:37)
    at Object.leave (/Users/user1/workdev/talent-front/community-app/node_modules/ts-graphql-plugin/lib/typegen/type-gen-visitor.js:105:47)
    at visit (/Users/user1/workdev/talent-front/community-app/node_modules/graphql/language/visitor.js:197:21)```

Add more customizable pattern for `tag`

Thanks to TS new feature Template Literal Types it becomes possible to parse the query on type level, at least not complex one. However, it is not possible to get type of tagged literal because it is always TemplateStringsArray, but it is possible to use plain functions instead gql('query { data }'). So the correct types will be inferred in TS itself, and the autocomplete will be provided by this plugin.

Also, it would be good to add possibility to provide autocomplete in types just as bonus for edge cases, i.e.
type Data = Query<'query { data }'>

It would be good to specify more complex pattern like start with gql(' and ends with ') for functions and to cover case with types you could set start with Query<' and ends with '>, or array of patterns. So we need just to specify the pattern which includes graphql content.

I think it could close this issues as well
#117
#53

External/Global fragment sources

When working with GraphQL Relay they have a system where all components in the app using createContainerFragmen generate graphql fragments for use in a so-called QueryRenderer.

But reference to these fragments is global. See example here:

https://relay.dev/docs/en/quick-start-guide

        query={graphql`
          query ViewerQuery {
            viewer {
              id
              ...TodoList_userTodoData   # <-- global frament here...
            }
          }
        `}
 

How can this be supported?

Also note @acao recently blogged about new support for this in the GraphQL VSCode extension. Could be inspiration.

Ignore/disable/turn off rules (for a certain line?)


name: Feature request
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''

---Describe the bug
Not a bug really, but it would be nice to be able to ignore certain lines/rules (such as how eslint does). In my project, the graphql was updated to deprecate some queries. This however meant that the front end pipeline was failing, as the warnings produced could not be ignored (they also throw an error code 1 despite only being warnings, not sure if this is on purpose)

To Reproduce
Steps to reproduce the behavior:

  • Try to use a deprecated query
  • Run validate command

Throws warning: The field *** is deprecated.

Expected behavior
Should be able to ignore the warning somehow while we transition to the new query

Thanks :)

ts-graphql-plugin not working with schema.json generated by apollo client CLI

Describe the bug
If I run apollo client:download-schema from the apollo CLI (https://github.com/apollographql/apollo-tooling, version 2.6.8) and pass along the path to the generated schema.json file in the configuration of ts-graphql-plugin, no autocompletion occurs.

Inspecting the log from my tsserver reveals that the initialization of ts-graphql-plugin fails with the error "Could not read __schema of undefined".

Wrapping the content of the generated schema.json file in "data": { }, as outlined in the README file fixes the issue.

To Reproduce

  1. Install apollo client version 2.6.8 and run apollo client:download-schema with against your graphql endpoint to obtain a schema.json file containing your graphql schema.
  2. Configure ts-graphql-plugin as outlined in the README file and make the schema point to the newly generated schema.json
  3. (Re)start your editor. Attempt to trigger auto-completion in a gql string and notice how nothing happens
  4. Open the log of your tsserver, search for [ts-graphql-plugin and notice how it reports the above-described error.
  5. Wrap the content of graphql schema in data: { }, restart your editor and notice how auto-completion now works

Expected behavior
I except the plugin to work with the schema file output by apollo client by default without any modifications necessary as apollo is one of the big players in the graphql area.

At the very least, I would like to be able to pass along a flag to ts-graphql-plugin when setting it up, informing it that it should interpret the schema.json file as the output of apollo client

Debug log
Screenshot 2020-02-13 at 13 18 30

Is it possible to use it in tsconfig.json with ttypescript?

Hi.

There is https://github.com/cevek/ttypescript project which allows to use transformers in tsconfig.json (i.e. without webpack).

I noticed that ts-graphql-plugin should work with webpack's ts-loader, and thus it should've been compatible with tsconfig.json approach. But looks like it's not working there (maybe it's just not working with the latest version of TypeScript?) - the error shown is TypeError: transformer.transformSourceFile is not a function at node_modules/typescript/lib/typescript.js:93958:109 when using e.g. this file:

const getTransformer = require('ts-graphql-plugin/lib/transformer/transformer').getTransformer;
module.exports = getTransformer({});

P.S.
Here is an example of transformers we use in our project:

image

List of list support

Hi, I just introduced for the first time a list of list type in my GraphQL schema, and I found out ts-graphql-plugin is not supporting it.

Visiting nodes seams to be hardcoded to a single nested level list looking at _getFieldMetadataFromFieldTypeInstance, _getFieldMetadataFromTypeNode, and _wrapTsTypeNodeWithModifiers.

I have made a patch via patch-package for my use case --> [[Type!]!]!

diff --git a/node_modules/ts-graphql-plugin/lib/typegen/type-gen-visitor.js b/node_modules/ts-graphql-plugin/lib/typegen/type-gen-visitor.js
index 8fab69f..ca925f0 100644
--- a/node_modules/ts-graphql-plugin/lib/typegen/type-gen-visitor.js
+++ b/node_modules/ts-graphql-plugin/lib/typegen/type-gen-visitor.js
@@ -245,8 +245,17 @@ class TypeGenVisitor {
                 if (fieldType instanceof graphql_1.GraphQLNonNull) {
                     fieldType = fieldType.ofType;
                     isStrict = true;
-                }
-                else {
+                    if (fieldType instanceof graphql_1.GraphQLList) {
+                        fieldType = fieldType.ofType;
+                        listTypeKind = 'strictListStrictList';
+                        if (fieldType instanceof graphql_1.GraphQLNonNull) {
+                            fieldType = fieldType.ofType;
+                            isStrict = true;
+                        } else {
+                            isStrict = false;
+                        }
+                    }
+                } else {
                     isStrict = false;
                 }
             }
@@ -328,11 +337,14 @@ class TypeGenVisitor {
         if (!strict) {
             typeNode = typescript_1.default.createUnionTypeNode([typeNode, typescript_1.default.createKeywordTypeNode(typescript_1.default.SyntaxKind.NullKeyword)]);
         }
-        if (list === 'strictList' || list === 'nullableList') {
+        if (list === 'strictList' || list === 'nullableList' || list === "strictListStrictList") {
             typeNode = typescript_1.default.createArrayTypeNode(typeNode);
             if (list === 'nullableList') {
                 typeNode = typescript_1.default.createUnionTypeNode([typeNode, typescript_1.default.createKeywordTypeNode(typescript_1.default.SyntaxKind.NullKeyword)]);
             }
+            if(list === "strictListStrictList") {
+                typeNode = typescript_1.default.createArrayTypeNode(typeNode);
+            }
         }
         return typeNode;
     }

I didn't think too much about the other cases, but a similar approach could be taken to cover other missing permutations (nullableListStrictList, nullableListNullableList, strictListNullableList).

I think this should eventually be recursive, but I highly doubt there are many business cases beyond a 2 dimension array, so it might be a cheaper feature to implement for now and whoever will have the need in the future will be able to scratch her/his head around πŸ˜„

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.