quramy / ts-graphql-plugin Goto Github PK
View Code? Open in Web Editor NEWTypeScript Language Service Plugin for GraphQL developers
License: MIT License
TypeScript Language Service Plugin for GraphQL developers
License: MIT License
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"
},
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?
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.
There is a collection of frequently asked questions. If those donβt help, you can always ask the humans behind Greenkeeper.
Your Greenkeeper Bot π΄
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;
};
};
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.
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).
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
git clone https://github.com/komfy/frontend.git
pnpm i --shamefully-hoist
compilerOptions.plugins.schema
with this link: https://komfy.herokuapp.com/graphql, so the config will look like this:{
"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"]
}
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:
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 */
}
]
src\ts-ast-util\template-expression-resolver.ts/_getValueAsString
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.
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.
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
β¬οΈ
graphql-language-service-interface is now deprecated, the way to go is to use graphql-language-service
as all of the subpackages are merged into it.
see deprecation message
I think it would be nice if package used graphqlrc.js
or any equivalent for configuration if graphql-config package is added to the project. I am willing to do a PR if you think it is a good idea.
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.
There is a collection of frequently asked questions. If those donβt help, you can always ask the humans behind Greenkeeper.
Your Greenkeeper Bot π΄
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
pnpx ts-graphql-plugin typegen
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
}
}
{
"compilerOptions": {
// ...
"plugins": [
{
"name": "ts-graphql-plugin",
"schema": {
"http": {
"method": "POST",
"url": "http://localhost:8080/graphql"
}
},
"tag": "gql"
}
]
},
// ...
}
Clone two repos, build api, launch it, then build frontend
git clone https://github.com/komfy/api.git
cd api
go mod download
go run dev-server/server.go
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
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.
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 πͺ
This release includes a new flag for tsserver to specify location of npm for nvm users.
Download:
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
There is a collection of frequently asked questions and of course you may always ask my humans.
Your Greenkeeper Bot π΄
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.
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
type-generator core should be responsible for only converting from query to ts type. Customization the types should be implemented by other layer.
In the relay standard exists an extra directive @connection for paging.
It is at least used by the apollo and relay toolkits.
ts-graphql-plugin complains that it doesn't know this directive.
Can you whitelist it?
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
For example: ts-graphql-plugin ...some_options> src/**/*.ts
Must have for CI/CD
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.
{
"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"
]
}
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
...
const gql = x => x
// No completion whatsoever when writing the contents below:
console.log(gql`
query {
me {
...on User {
name
}
...on
}
}
`)
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.
We have multiple schemas in a single project, so we need to be able to register multiple schemas. Is this possible?
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?
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!
We can reuse GraphQL operations extracted from template literals, such as validation CLI or other static query analysis.
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.
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:
Does not work:
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?
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.
There is a collection of frequently asked questions. If those donβt help, you can always ask the humans behind Greenkeeper.
Your Greenkeeper Bot π΄
While intellisense is provided during editing it there there are cases where somebody might slip in a typo or simply a field name has changed.
In these cases it would be great to generate a "problem" entry just like its already done when systax is checked.
Happy to help if you give me some pointers. Not that deep into language services.
This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.
These updates have all been created already. Click a checkbox below to force a retry/rebase of any.
@typescript-eslint/eslint-plugin
, @typescript-eslint/parser
)These are blocked by an existing closed PR and will not be recreated unless you click a checkbox below.
.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
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
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.
Now, adapter can treat only NonSubstituting Template Strings.
const query = ` query { }` // it works
const query = ` query { ${foo} }` // it does not work
My problem is :
${foo}
). For example, in getSemanticDiagonistics
, is it right to ignore the parameters ?And static QraphQL transformation ( e.g. climber side only directives)
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>β
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:
4.8.2
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)```
https://github.com/Quramy/ts-graphql-plugin/blob/master/src/ts-util/resolve-template-expression.ts#L159 is heavy because it has recursive calling langService's getDefinitions method.
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.
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.
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:
Throws warning: The field *** is deprecated.
Expected behavior
Should be able to ignore the warning somehow while we transition to the new query
Thanks :)
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
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
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:
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 π
A declarative, efficient, and flexible JavaScript library for building user interfaces.
π Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. πππ
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google β€οΈ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.