correttojs / graphql-codegen-apollo-next-ssr Goto Github PK
View Code? Open in Web Editor NEWAutogenerate apollo code for nextjs ssr
Autogenerate apollo code for nextjs ssr
in getStaticProps one can return
return {
props: {
apolloState: apolloClient.cache.extract(),
},
revalidate: 1,
}
but the generated types through this bundle does not provide this option to revalidate the pages
maybe it's better to change the example config plugin option from
plugins:
- ./build/src/index.js
to
plugins:
- graphql-codegen-apollo-next-ssr
I tried running the example project included in the repo and ran into some errors, see below. As is provided out of the box from the repo, I could not get it to run. Not sure if anyone else has encountered the same issue as me.
When compiling with TS strict mode, the following error is shown:
error TS1361: 'React' cannot be used as a value because it was imported using 'import type'.
599 return <WrappedComponent {...props} data={data} error={error} />
If wanted, I can write a patch.
Hello guys, im using default example config with only replacePage: false
with STRAPI Graphql.
Im unable to get my fields from union types, am i missing something obvious?
There is always just __typename
field and thats it.
{"__typename":"ComponentFeaturesFeatures26"}
Shall it not be so simple, i'll post more info and examples.
Thanks
I set up my Apollo client using the Next.js Apollo example so my state is stored using the key __APOLLO_STATE__
instead of apolloState
.
graphql-codegen-apollo-next-ssr/src/visitor.ts
Lines 202 to 206 in 536ca60
It would be great if this could be configurable. Maybe something like the following for backwards compatibility:
apolloStateKey
(default: 'apolloState'): Key used for storing Apollo state
If this sounds good, I'm happy to create a PR.
Currently Page Component types get generated using React.FC
but it should be using NextPage
Current:
import type React from 'react';
export type PageAllOrdersComp = React.FC<{data?: AllOrdersQuery, error?: Apollo.ApolloError}>;
Expected
import type { NextPage } from 'next';
export type PageAllOrdersComp = NextPage<{data?: AllOrdersQuery, error?: Apollo.ApolloError}>;
This looks like the only way to use Apollo with TypeScript typed queries and Next.js SSR at the same time without a lot of boilerplate. However, I'm worried about the limitation listed in the README: "The limitation/advantage of this solution is that all the queries embedded into inner react components are ignored, unless covered by the top level cache.".
That sounds scary to me, I don't want queries to be ignored. What situations would I need to avoid to prevent that from happening? If I have all of my graphql queries as graphql
files in the src
folder like in the example will I be okay?
I also have a separate maybe unrelated question: if I wanted to make a client-side only graphql request, how would I do that with this library? Is that what usePage
does?
When using a documentMode other than external you will get this error Cannot find name 'Operations'. ts(2304)
It appears that this library is hardcoded to for the documents to be external.
I think if the documentMode
is anything except external
then documentVariableName
should not be prefixed with Operation.
.
Generated file should not trigger errors with typescript compilation
When generating the queries with typescript config strict
and noUnusedLocals
compilation fails because the import NormalizedCacheObject
is never used.
Failed to compile.
./generated/queries.tsx:10:1
Type error: 'NormalizedCacheObject' is declared but its value is never read.
8 | import type React from 'react'
9 | import { getApolloClient } from 'lib/with-apollo'
> 10 | import type { NormalizedCacheObject } from '@apollo/client'
| ^
11 | export async function getServerPageArticle(
12 | options: Omit<Apollo.QueryOptions<Types.ArticleQueryVariables>, 'query'>,
13 | ctx?: any
error Command failed with exit code 1.
Am I missing something in my configuration that would use NormalizedCacheObject
?
codegen.yml
overwrite: true
schema: '<redacted>'
documents: 'lib/api/**/*.graphql'
generates:
generated/types.ts:
plugins:
- typescript
- typescript-operations
- typescript-react-apollo
generated/apollo-helpers.ts:
plugins:
- typescript-apollo-client-helpers
generated/queries.tsx:
config:
documentMode: external
importDocumentNodeExternallyFrom: ./types
reactApolloVersion: 3
withHooks: true
withHOC: true
apolloClientInstanceImport: 'lib/with-apollo'
preset: import-types
presetConfig:
typesPath: ./types
plugins:
- graphql-codegen-apollo-next-ssr
hooks:
afterOneFileWrite:
- prettier --write
- tslint --fix
Docs:
*replaceQuery (default: false): Replace "query" keyword inside the generated operations
replacePage (default: false): Replace "page" keyword inside the generated operations
Code:
replacePage: getConfigValue(rawConfig.replacePage, true),
replaceQuery: getConfigValue(rawConfig.replaceQuery, true),
as long as I understand, the second parameter is a default value. One of them is definitely wrong.
I'm not sure if there's a particular use case for the getServerPage<Query>
methods returning the entire serialized cache, but I think it would be more valuable to return the result of the query instead so that the return value of the query can be used directly.
i.e. instead of
await apolloClient.query({ ...options, query:Operations.${documentVariableName} });
const apolloState = apolloClient.cache.extract();
return {
props: {
apolloState,
},
};
it could return
return await apolloClient.query<${operationResultType}>({ ...options, query:Operations.${documentVariableName} });
Or if there is a use case for the above, then can a new method for the latter be added? I'd like to use this plugin, but I'd like to use it in getInitialProps
and also utilize the return value of the query (e.g. checking if the query returned any value), but returning the serialized cache state isn't useful for this purpose.
Thanks!
It would be great if this line could be configured via an option defaultLibImport
(or maybe you can come up with a better name) where we can configure this line. Some projects may want to use Preact
or in my case, I don't want any React import at all. (or at least change it to import * as React from "react"
or since Im using typescript and the only reason react is imported is for types - import type * as React from "react"
See the reason for this here on the offical repo: facebook/react#18102
We have two queries, namely query User {}
and query UserPage {}
.
However this plugin removes page
and query
from any operation name, resulting in duplicating namings export async function getServerPageUser
Hey!
I'm struggling a bit on how to use this. See my PR on my play-project here: KATT/e2e-typesafety/pull/1
KATT/e2e-typesafety#1
In my generated file it refers to an Operations
object that I don't know where it comes from: KATT/e2e-typesafety/blob/feature/graphql-codegen-apollo-next-ssr/apollo/__generated__/graphql.tsx#L56
You can see my config here: ssr/codegen.js
What am I missing to get it live and kicking?
Thanks
Tried implementing this example but I wasn't sure where the config was pulling ./graphql from.
Turns out the compiler has no idea either.
`Error: Cannot find module 'graphql'
Require stack:
Latest update generated the following line in my output file:
import { getApolloClient , any} from '~hooks/useApollo';
because the contextType is added as an import (which is wrong).
setting contextType: ""
fixes that line but generates wrong syntax for other lines:
- (options: Omit<Apollo.QueryOptions<Types.CalculatorQueryVariables>, 'query'>, ctx?: any)
+ (options: Omit<Apollo.QueryOptions<Types.CalculatorQueryVariables>, 'query'>, ctx?: )
I'm having an issue using this library that whenever I change something in my backend, the next js app does not update with the new results(when refreshing the page) even if the fetch policy is network-only o no-cache, any ideas why this is happening, or is there some documentation on how to accomplish that.
import {ssrGetRanking, PageGetRankingComp} from 'generated/page'
import {GetServerSidePropsContext} from 'next'
import React from 'react'
import {withApollo} from 'withApollo'
const RankingPage: PageGetRankingComp = ({data, error}) => {
// Comp logic goes here
}
export async function getServerSideProps(ctx: GetServerSidePropsContext) {
return await ssrGetRanking.getServerPage({fetchPolicy: 'network-only'}, ctx)
}
export default withApollo(ssrGetRanking.withPage(() => ({}))(RankingPage))
I also try to add the fetch policy in the HOC wrap but then I notice that the component was having a delay with the data values because it displays undefined and after that the data is valid.
import {ssrGetRanking, PageGetRankingComp} from 'generated/page'
import {GetServerSidePropsContext} from 'next'
import React from 'react'
import {withApollo} from 'withApollo'
const RankingPage: PageGetRankingComp = ({data, error}) => {
// Comp logic goes here
}
export async function getServerSideProps(ctx: GetServerSidePropsContext) {
return await ssrGetRanking.getServerPage({fetchPolicy: 'network-only'}, ctx)
}
export default withApollo(
ssrGetRanking.withPage(() => ({fetchPolicy: 'network-only'}))(RankingPage),
)
Hello! With Next.js 10, it is possible to set a property in the return object of getStaticProps that shows a 404 page with correct headers etc. This is done by setting the notFound property to true.
Example:
export function getStaticProps() {
return {
// returns the default 404 page with a status code of 404
notFound: true
}
}
To be able to easily check if we get any data, it would be nice to see the query result, and if it exists return the extracted apollo cache.
Is this something that is in scope for this library?
Hi,
I cloned the project and ran the example as follows:
cd path/to/package/root
npm install
npm run build
cd example
npm install
npm run codegen
However I get the following error:
╰─>$ npm run codegen
> [email protected] codegen
> graphql-codegen --config codegen.yml
✔ Parse configuration
❯ Generate outputs
✔ Generate src/generated/graphql.tsx
❯ Generate to src/generated/page.tsx (using EXPERIMENTAL preset "import-types")
✔ Load GraphQL schemas
✔ Load GraphQL documents
✖ Generate
→ spurious results.
Found 1 error
✖ src/generated/page.tsx
Error: Cannot use GraphQLScalarType "ID" from another module or realm.
Ensure that there is only one instance of "graphql" in the node_modules
directory. If different versions of "graphql" are the dependencies of other
relied on modules, use "resolutions" to ensure only one version is installed.
https://yarnpkg.com/en/docs/selective-version-resolutions
Duplicate "graphql" modules cannot be used at the same time since different
versions may have different capabilities and behavior. The data from one
version used in the function from another could produce confusing and
spurious results.
at instanceOf (/home/david/Documents/learn/graphql-codegen-apollo-next-ssr/node_modules/graphql/jsutils/instanceOf.js:29:13)
at Object.isScalarType (/home/david/Documents/learn/graphql-codegen-apollo-next-ssr/node_modules/graphql/type/definition.js:109:34)
at /home/david/Documents/learn/graphql-codegen-apollo-next-ssr/node_modules/@graphql-codegen/visitor-plugin-common/index.cjs.js:374:37
at Array.filter (<anonymous>)
at buildScalars (/home/david/Documents/learn/graphql-codegen-apollo-next-ssr/node_modules/@graphql-codegen/visitor-plugin-common/index.cjs.js:
374:14)
at buildScalarsFromConfig (/home/david/Documents/learn/graphql-codegen-apollo-next-ssr/node_modules/@graphql-codegen/visitor-plugin-common/ind
ex.cjs.js:363:12)
at new ClientSideBaseVisitor (/home/david/Documents/learn/graphql-codegen-apollo-next-ssr/node_modules/@graphql-codegen/visitor-plugin-common/
index.cjs.js:2120:22)
at new ApolloNextSSRVisitor (/home/david/Documents/learn/graphql-codegen-apollo-next-ssr/build/src/visitor.js:11:9)
at Object.plugin (/home/david/Documents/learn/graphql-codegen-apollo-next-ssr/build/src/index.js:28:21)
at executePlugin (/home/david/Documents/learn/graphql-codegen-apollo-next-ssr/example/node_modules/@graphql-codegen/core/index.cjs.js:38:35)
Error: Cannot use GraphQLScalarType "ID" from another module or realm.
Ensure that there is only one instance of "graphql" in the node_modules
directory. If different versions of "graphql" are the dependencies of other
relied on modules, use "resolutions" to ensure only one version is installed.
https://yarnpkg.com/en/docs/selective-version-resolutions
Duplicate "graphql" modules cannot be used at the same time since different
versions may have different capabilities and behavior. The data from one
version used in the function from another could produce confusing and
spurious results.
at instanceOf (/home/david/Documents/learn/graphql-codegen-apollo-next-ssr/node_modules/graphql/jsutils/instanceOf.js:29:13)
at Object.isScalarType (/home/david/Documents/learn/graphql-codegen-apollo-next-ssr/node_modules/graphql/type/definition.js:109:34)
at /home/david/Documents/learn/graphql-codegen-apollo-next-ssr/node_modules/@graphql-codegen/visitor-plugin-common/index.cjs.js:374:37
at Array.filter (<anonymous>)
at buildScalars (/home/david/Documents/learn/graphql-codegen-apollo-next-ssr/node_modules/@graphql-codegen/visitor-plugin-common/index.cjs.js:
374:14)
at buildScalarsFromConfig (/home/david/Documents/learn/graphql-codegen-apollo-next-ssr/node_modules/@graphql-codegen/visitor-plugin-common/ind
ex.cjs.js:363:12)
at new ClientSideBaseVisitor (/home/david/Documents/learn/graphql-codegen-apollo-next-ssr/node_modules/@graphql-codegen/visitor-plugin-common/
index.cjs.js:2120:22)
at new ApolloNextSSRVisitor (/home/david/Documents/learn/graphql-codegen-apollo-next-ssr/build/src/visitor.js:11:9)
at Object.plugin (/home/david/Documents/learn/graphql-codegen-apollo-next-ssr/build/src/index.js:28:21)
at executePlugin (/home/david/Documents/learn/graphql-codegen-apollo-next-ssr/example/node_modules/@graphql-codegen/core/index.cjs.js:38:35)
Something went wrong
It puzzled me why I see yarn when I used npm to install. I'm not sure how to interpret this. Apologies if this is something obvious. I've been having trouble with this package in general.
Hiii,
I having some trouble to understand how to use this library when I want to make multiple fetch on getStaticProps
(example) and return that data. I think Im not getting the correct result, because when I enter the page, the request appears on the XHR twice (one canceled, and the other with success), but it should not appear as I know.
Thanks
overwrite: true
schema: "http://localhost:1337/graphql"
documents: "graphql/**/*.graphql"
generates:
generated/graphql.tsx:
plugins:
- "typescript"
- "typescript-operations"
- "typescript-react-apollo"
config:
reactApolloVersion: 3
withHooks: false
withHOC: false
withComponent: false
exportFragmentSpreadSubTypes: true
documentMode: graphQLTag
generated/page.tsx:
config:
documentMode: external
importDocumentNodeExternallyFrom: ./graphql
reactApolloVersion: 3
withHooks: true
# withHOC: false
# excludePatterns: 'getComments'
# excludePatternsOptions: 'i'
# customDataIdFromObjectName: 'test'
# customDataIdFromObjectImport: 'abc'
apolloClientInstanceImport: "@withApollo"
# apolloStateKey: '__APOLLO_STATE__'
preset: import-types
presetConfig:
typesPath: ./graphql
plugins:
- "graphql-codegen-apollo-next-ssr/build/src/index.js" # replace by - graphql-codegen-apollo-next-ssr
generated/page.tsx
Unable to find preset matching 'import-types'
Install one of the following packages:
- @graphql-codegen/import-types
- @graphql-codegen/import-types-preset
- import-types
Error: Unable to find preset matching import-types
at getPresetByName (/home/aman/Work/ew_work1/client/node_modules/@graphql-codegen/cli/bin.js:404:11)
at async /home/aman/Work/ew_work1/client/node_modules/@graphql-codegen/cli/bin.js:932:47
at async Task.task (/home/aman/Work/ew_work1/client/node_modules/@graphql-codegen/cli/bin.js:760:17)
Error: Unable to find preset matching import-types
at getPresetByName (/home/aman/Work/ew_work1/client/node_modules/@graphql-codegen/cli/bin.js:404:11)
at async /home/aman/Work/ew_work1/client/node_modules/@graphql-codegen/cli/bin.js:932:47
at async Task.task (/home/aman/Work/ew_work1/client/node_modules/@graphql-codegen/cli/bin.js:760:17)
Just an observation, since server side doesn't work when simply returning the await ssrQueryThing.....
.
I tried to convert the with-apollo example at Next.js to TypeScript implementing graphQl-code-generator. This is the sandbox in development: https://codesandbox.io/s/nextjs-with-apollo-3-and-graphql-generator-5463i
I'm using the near-operation-file
preset to generate the base types, and would like to keep them that way. My config .graphqlrc.yml
looks like this:
schema: '${GRAPHQL_SERVER:http://localhost:3000/graphql}'
extensions:
codegen:
watch: true
overwrite: true
generates:
packages/types/src/graphql.ts:
plugins:
- add
- 'typescript'
apps/web-app/gql:
documents:
- 'apps/web-app/src/**/*.graphql'
preset: near-operation-file
presetConfig:
extension: .generated.ts
baseTypesPath: '~@pkg/types/graphql'
plugins:
- 'typescript-operations'
- 'typescript-react-apollo'
config:
withHooks: false
reactApolloVersion: 3
apps/web-app/next:
documents:
- 'apps/web-app/src/**/*.graphql'
preset: near-operation-file
presetConfig:
extension: .page.tsx
baseTypesPath: '~@pkg/types/graphql'
plugins:
- 'apollo-next-ssr'
config:
documentMode: external
importDocumentNodeExternallyFrom: near-operation-file
withHooks: true
contextType: 'ApolloClientContext'
contextTypeRequired: true
apolloClientInstanceImport: '~/utils/apollo/client'
reactApolloVersion: 3
Types are generated in .generated.ts
files and not .graphql
files. Would it be possible to provide a suffix for importDocumentNodeExternallyFrom: near-operation-file
option?
Please fix example with lastest @apollo/client
The generated code collapses the different possible errors into a single error property in the response:
From the test spec:
In that line of code:
data?.error
is of type: Apollo.ApolloError | undefined
data?.errors
is of type: ReadonlyArray<GraphQLError> | undefined
null
The resulting type should be a compound type of those possibilities. However, the generated code incorrectly types this as error?: Apollo.ApolloError
:
Expected Behavior
error
as Apollo.ApolloError | readonly GraphQLError[] | null
.The problem seems to be based here https://github.com/correttojs/graphql-codegen-apollo-next-ssr/blob/master/src/visitor.ts#L80.
Would love to see a fix & thanks for your work!
In getServerSideProps()
, it's not safe to return the object returned by getServerPage
as-is. This is because errors in res.props.error
can't be serialized to JSON.
This might not be a bug, but it does mean that you have to do your own error handling in every getServerSideProps
function rather than handling that when you're rendering your component, or in pages/_app.tsx
to keep your code more DRY. And it's confusing, because I thought that a property named props
would be something you could safely return as the page props without modification.
The issue can be reproduced most easily by faking a GraphQL error:
import { GraphQLError } from 'graphql'
...
export async function getServerSideProps(ctx: GetServerSidePropsContext) {
...
res.props.error = [new GraphQLError('foo')]
This causes a next.js Server Error:
Error: Error serializing
.error[0]
returned fromgetServerSideProps
in "/artists/[creatorId]/[lotId]".
Reason:object
("[object Object]") cannot be serialized as JSON. Please only return JSON serializable data types.
It would be great if the generated code returned an error
prop that can be properly stringified to JSON instead of returning the ApolloError or GraphqlErrors objects directly. Or alternatively maybe generate a function you can optionally use to do the conversion, something like this:
if (res.props.error) {
return ssrMyQuery.pagePropsForErrorPage(res)
}
...which would grab the error message(s) and return a plain object, e.g.:
{
props: {
error: {
message: 'GraphqlError: foo'
}
}
}
Getting this error when trying to codegen with a operation which does not have a name.
After looking into the code it looks like it's to do with trying to access node.name.value
to define operationName but if the operation was not declared with a name, node.name
will return undefined.
By giving the operation a name this error goes away.
TypeError: Cannot read property 'value' of undefined
at ApolloNextSSRVisitor._buildOperationPageQuery (/Users/kalana/projects/musictaste-spaces/node_modules/graphql-codegen-apollo-next-ssr/bu
ild/src/visitor.js:74:58)
at ApolloNextSSRVisitor.buildOperation (/Users/kalana/projects/musictaste-spaces/node_modules/graphql-codegen-apollo-next-ssr/build/src/vi
sitor.js:140:36)
at ApolloNextSSRVisitor.OperationDefinition (/Users/kalana/projects/musictaste-spaces/node_modules/@graphql-codegen/visitor-plugin-common/
index.cjs.js:2413:33)
at Object.visit (/Users/kalana/projects/musictaste-spaces/node_modules/graphql/language/visitor.js:243:26)
at Object.plugin (/Users/kalana/projects/musictaste-spaces/node_modules/graphql-codegen-apollo-next-ssr/build/src/index.js:29:35)
at executePlugin (/Users/kalana/projects/musictaste-spaces/node_modules/@graphql-codegen/core/index.cjs.js:38:35)
at async /Users/kalana/projects/musictaste-spaces/node_modules/@graphql-codegen/core/index.cjs.js:116:24
at async Promise.all (index 1)
at async Object.codegen (/Users/kalana/projects/musictaste-spaces/node_modules/@graphql-codegen/core/index.cjs.js:106:20)
at async process (/Users/kalana/projects/musictaste-spaces/node_modules/@graphql-codegen/cli/bin.js:975:56)
TypeError: Cannot read property 'value' of undefined
at ApolloNextSSRVisitor._buildOperationPageQuery (/Users/kalana/projects/musictaste-spaces/node_modules/graphql-codegen-apollo-next-ssr/bu
ild/src/visitor.js:74:58)
at ApolloNextSSRVisitor.buildOperation (/Users/kalana/projects/musictaste-spaces/node_modules/graphql-codegen-apollo-next-ssr/build/src/vi
sitor.js:140:36)
at ApolloNextSSRVisitor.OperationDefinition (/Users/kalana/projects/musictaste-spaces/node_modules/@graphql-codegen/visitor-plugin-common/
index.cjs.js:2413:33)
at Object.visit (/Users/kalana/projects/musictaste-spaces/node_modules/graphql/language/visitor.js:243:26)
at Object.plugin (/Users/kalana/projects/musictaste-spaces/node_modules/graphql-codegen-apollo-next-ssr/build/src/index.js:29:35)
at executePlugin (/Users/kalana/projects/musictaste-spaces/node_modules/@graphql-codegen/core/index.cjs.js:38:35)
at async /Users/kalana/projects/musictaste-spaces/node_modules/@graphql-codegen/core/index.cjs.js:116:24
at async Promise.all (index 1)
at async Object.codegen (/Users/kalana/projects/musictaste-spaces/node_modules/@graphql-codegen/core/index.cjs.js:106:20)
at async process (/Users/kalana/projects/musictaste-spaces/node_modules/@graphql-codegen/cli/bin.js:975:56)
I managed to fix the error by passing in the node directly instead of trying to pass a string to the this.convertName
function. This results in the operationName
becoming Unnamed
which I think is the expected behaviour without crashing.
Hi, I would like to see an example of the fetchMore for use in pagination, tx
This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.
These updates are currently rate-limited. Click on a checkbox below to force their creation now.
@types/react
, react
, react-dom
)These updates have all been created already. Click a checkbox below to force a retry/rebase of any.
@graphql-codegen/cli
, @graphql-codegen/fragment-matcher
, @graphql-codegen/import-types-preset
, @graphql-codegen/introspection
, @graphql-codegen/testing
, @graphql-codegen/typescript
, @graphql-codegen/typescript-operations
)@graphql-codegen/cli
, @graphql-codegen/fragment-matcher
, @graphql-codegen/import-types-preset
, @graphql-codegen/introspection
, @graphql-codegen/plugin-helpers
, @graphql-codegen/testing
, @graphql-codegen/typescript
, @graphql-codegen/typescript-operations
, @graphql-codegen/typescript-react-apollo
, @graphql-codegen/visitor-plugin-common
).github/workflows/main.yml
actions/setup-node v3
.github/workflows/release.yml
actions/setup-node v3
actions/checkout v3
.github/workflows/test.yml
actions/checkout v3
example/package.json
@apollo/client 3.7.17
isomorphic-unfetch ^3.1.0
next 12.3.4
react 18.2.0
react-dom 18.2.0
@graphql-codegen/cli 2.11.7
@graphql-codegen/import-types-preset 2.2.3
@graphql-codegen/typescript 2.7.3
@graphql-codegen/typescript-operations 2.5.3
@graphql-codegen/typescript-react-apollo 3.3.7
@types/react 18.2.31
typescript 4.9.5
package.json
@graphql-codegen/plugin-helpers ^2.3.1
@graphql-codegen/visitor-plugin-common ^2.9.1
auto-bind ~4.0.0
@graphql-codegen/cli 2.11.7
@graphql-codegen/fragment-matcher 3.3.1
@graphql-codegen/import-types-preset 2.2.3
@graphql-codegen/introspection 2.2.1
@graphql-codegen/testing 1.17.7
@graphql-codegen/typescript 2.7.3
@graphql-codegen/typescript-operations 2.5.3
@graphql-codegen/typescript-react-apollo 3.3.7
@types/jest 29.5.6
@types/node 18.18.6
apollo-cache-inmemory 1.6.6
apollo-client 2.6.10
graphql 16.8.1
graphql-codegen 0.4.0
jest 29.7.0
standard-version 9.5.0
ts-jest 28.0.8
typescript 4.9.5
graphql <17.0.0
Hi there, this seems like an awesome module and was specifically what I was looking for. Great work!
Config:
generated/page.tsx:
plugins:
- apollo-next-ssr
# preset: import-types
# presetConfig:
# typesPath: ./graphql
config:
documentMode: external
importDocumentNodeExternallyFrom: ./apollo.ts
typesPrefix: GQL
# reactApolloVersion: 3
apolloCacheImportFrom: '@apollo/client'
The plugin path in the documentation is wrong it is referring to some build path, but it should be apollo-next-ssr
It seems I'm missing the type for the NormalizedCacheObject which I would expect to exist here:
import { QueryHookOptions, useQuery, NormalizedCacheObject } from '@apollo/client'
So if withHOC
GQL codegen config option is specified to false
, the output types contains unused line:
import { NextPage } from 'next';
This is because of this line of code in package sources.
Since withHOC
option is toggled to false
, the above piece of code produces an empty string.
There is no other mentions of NextPage
anymore.
The NextPage
import happens here. And it is unconditional. This is why with withHOC: false
, there is an unused import
happens in the produced type output.
This leads to a typescript error:
src/graphql/ssr-types.tsx:4:1 - error TS6133: 'NextPage' is declared but its value is never read.
4 import { NextPage } from 'next';
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
It is required to prune import { NextPage } from 'next';
is withHOC: false
GQL codegen config option applied.
According to the documentation in graphql-code-generator
(https://graphql-code-generator.com/docs/plugins/typescript-apollo-next#importdocumentnodeexternallyfrom`, setting
documentMode: external
importDocumentNodeExternallyFrom: near-operation-file
should properly import document nodes from the files created using the near-operation-file
preset, but according to the source code and the output I'm getting, that doesn't seem to be the case. Instead, it tries to directly import
import * as Operations from "near-operation-file";
Would it be possible to fix this behavior? Thanks!
"@graphql-codegen/cli": "^2.2.2",
"@graphql-codegen/import-types-preset": "^2.1.7",
"@graphql-codegen/typescript": "^2.3.1",
"@graphql-codegen/typescript-operations": "^2.2.0",
"@graphql-codegen/typescript-react-apollo": "^3.2.1",
"graphql-codegen-apollo-next-ssr": "^1.7.1"
overwrite: true
schema: "https://countries.trevorblades.com/"
# documents: "src/**/*.graphql"
generates:
src/generated/graphql.tsx:
plugins:
- typescript
- typescript-operations
- typescript-react-apollo
config:
reactApolloVersion: 3
withHooks: false
withHOC: false
withComponent: false
exportFragmentSpreadSubTypes: true
documentMode: graphQLTag
src/generated/page.tsx:
config:
documentMode: external
importDocumentNodeExternallyFrom: ./graphql
reactApolloVersion: 3
withHooks: true
contextType: "ApolloClientContext"
contextTypeRequired: true
# withHOC: false
# excludePatterns: 'getComments'
# excludePatternsOptions: 'i'
# customDataIdFromObjectName: 'test'
# customDataIdFromObjectImport: 'abc'
apolloClientInstanceImport: "../withApollo"
# apolloStateKey: '__APOLLO_STATE__'
preset: import-types
presetConfig:
typesPath: ./graphql
plugins:
# - "./build/src/index.js" # replace by - graphql-codegen-apollo-next-ssr
- graphql-codegen-apollo-next-ssr
I am thinking its a issue due to the dependencies, I tried running example and it worked completely fine.
I will try upgrading each package in example project and see where it breaks, will update here.
Given config:
src/graphql/:
preset: near-operation-file
presetConfig:
baseTypesPath: ./generated.tsx
extension: .generated.tsx
plugins:
- typescript-operations
- typescript-react-apollo
- apollo-next-ssr
config:
reactApolloVersion: 3
gqlImport: ''
withHooks: true
apolloClientInstanceImport: '../withApollo'
Output:
import * as Types from '../generated';
import { UserFragmentFragment } from './users.generated';
import gql from 'graphql-tag';
import { UserFragmentFragmentDoc } from './users.generated';
import * as Apollo from '@apollo/client';
import { NextPage } from 'next';
import { NextRouter, useRouter } from 'next/router'
import { QueryHookOptions, useQuery } from '@apollo/client';
import type React from 'react';
import { getApolloClient} from '../withApollo';
import type { NormalizedCacheObject } from '@apollo/client';
export type DocumentFragmentFragment = (
{ __typename?: 'Document' }
& Pick<Types.Document, 'id' | 'name' | 'fileName' | 'type' | 'fileType' | 'sourceUrl' | 'lastModifiedAt' | 'createdAt'>
& { user: (
{ __typename?: 'User' }
& UserFragmentFragment
) }
);
export type DocumentsQueryVariables = Types.Exact<{
clientId: Types.Scalars['ID'];
applicationId?: Types.Maybe<Types.Scalars['ID']>;
}>;
export type DocumentsQuery = (
{ __typename?: 'Query' }
& { documents: Array<(
{ __typename?: 'Document' }
& DocumentFragmentFragment
)> }
);
export type CreateDocumentMutationVariables = Types.Exact<{
input: Types.CreateDocumentInput;
}>;
export type CreateDocumentMutation = (
{ __typename?: 'Mutation' }
& { createDocument?: Types.Maybe<(
{ __typename?: 'CreateDocumentPayload' }
& { document: (
{ __typename?: 'Document' }
& DocumentFragmentFragment
) }
)> }
);
export const DocumentFragmentFragmentDoc = gql`
fragment DocumentFragment on Document {
id
name
fileName
type
fileType
sourceUrl
lastModifiedAt
createdAt
user {
...UserFragment
}
}
${UserFragmentFragmentDoc}`;
export const DocumentsDocument = gql`
query Documents($clientId: ID!, $applicationId: ID) {
documents(clientId: $clientId, applicationId: $applicationId) {
...DocumentFragment
}
}
${DocumentFragmentFragmentDoc}`;
/**
* __useDocumentsQuery__
*
* To run a query within a React component, call `useDocumentsQuery` and pass it any options that fit your needs.
* When your component renders, `useDocumentsQuery` returns an object from Apollo Client that contains loading, error, and data properties
* you can use to render your UI.
*
* @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;
*
* @example
* const { data, loading, error } = useDocumentsQuery({
* variables: {
* clientId: // value for 'clientId'
* applicationId: // value for 'applicationId'
* },
* });
*/
export function useDocumentsQuery(baseOptions: Apollo.QueryHookOptions<DocumentsQuery, DocumentsQueryVariables>) {
return Apollo.useQuery<DocumentsQuery, DocumentsQueryVariables>(DocumentsDocument, baseOptions);
}
export function useDocumentsLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<DocumentsQuery, DocumentsQueryVariables>) {
return Apollo.useLazyQuery<DocumentsQuery, DocumentsQueryVariables>(DocumentsDocument, baseOptions);
}
export type DocumentsQueryHookResult = ReturnType<typeof useDocumentsQuery>;
export type DocumentsLazyQueryHookResult = ReturnType<typeof useDocumentsLazyQuery>;
export type DocumentsQueryResult = Apollo.QueryResult<DocumentsQuery, DocumentsQueryVariables>;
export const CreateDocumentDocument = gql`
mutation CreateDocument($input: CreateDocumentInput!) {
createDocument(input: $input) {
document {
...DocumentFragment
}
}
}
${DocumentFragmentFragmentDoc}`;
export type CreateDocumentMutationFn = Apollo.MutationFunction<CreateDocumentMutation, CreateDocumentMutationVariables>;
/**
* __useCreateDocumentMutation__
*
* To run a mutation, you first call `useCreateDocumentMutation` within a React component and pass it any options that fit your needs.
* When your component renders, `useCreateDocumentMutation` returns a tuple that includes:
* - A mutate function that you can call at any time to execute the mutation
* - An object with fields that represent the current status of the mutation's execution
*
* @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2;
*
* @example
* const [createDocumentMutation, { data, loading, error }] = useCreateDocumentMutation({
* variables: {
* input: // value for 'input'
* },
* });
*/
export function useCreateDocumentMutation(baseOptions?: Apollo.MutationHookOptions<CreateDocumentMutation, CreateDocumentMutationVariables>) {
return Apollo.useMutation<CreateDocumentMutation, CreateDocumentMutationVariables>(CreateDocumentDocument, baseOptions);
}
export type CreateDocumentMutationHookResult = ReturnType<typeof useCreateDocumentMutation>;
export type CreateDocumentMutationResult = Apollo.MutationResult<CreateDocumentMutation>;
export type CreateDocumentMutationOptions = Apollo.BaseMutationOptions<CreateDocumentMutation, CreateDocumentMutationVariables>;
export const DocumentsDocument = gql`
query Documents($clientId: ID!, $applicationId: ID) {
documents(clientId: $clientId, applicationId: $applicationId) {
...DocumentFragment
}
}
${DocumentFragmentFragmentDoc}`;
export async function getServerPageDocuments
(options: Omit<Apollo.QueryOptions<DocumentsQueryVariables>, 'query'>, ctx? :any ){
const apolloClient = getApolloClient(ctx);
const data = await apolloClient.query<DocumentsQuery>({ ...options, query:Operations.DocumentsDocument });
const apolloState = apolloClient.cache.extract();
return {
props: {
apolloState,
data: data?.data,
error: data?.error ?? data?.errors ?? null,
},
};
}
export const useDocuments = (
optionsFunc?: (router: NextRouter)=> QueryHookOptions<DocumentsQuery, DocumentsQueryVariables>) => {
const router = useRouter();
const options = optionsFunc ? optionsFunc(router) : {};
return useQuery(Operations.DocumentsDocument, options);
};
export type PageDocumentsComp = React.FC<{data?: DocumentsQuery, error?: Apollo.ApolloError}>;
export const withPageDocuments = (optionsFunc?: (router: NextRouter)=> QueryHookOptions<DocumentsQuery, DocumentsQueryVariables>) => (WrappedComponent:PageDocumentsComp) : NextPage => (props) => {
const router = useRouter()
const options = optionsFunc ? optionsFunc(router) : {};
const {data, error } = useQuery(Operations.DocumentsDocument, options)
return <WrappedComponent {...props} data={data} error={error} /> ;
};
export const ssrDocuments = {
getServerPage: getServerPageDocuments,
withPage: withPageDocuments,
usePage: useDocuments,
}
export const CreateDocumentDocument = gql`
mutation CreateDocument($input: CreateDocumentInput!) {
createDocument(input: $input) {
document {
...DocumentFragment
}
}
}
${DocumentFragmentFragmentDoc}`;
Notice documents like CreateDocumentDocument
is created twice and I am also getting Operations.
which is incorrect
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.