Coder Social home page Coder Social logo

correttojs / graphql-codegen-apollo-next-ssr Goto Github PK

View Code? Open in Web Editor NEW
201.0 1.0 33.0 6.29 MB

Autogenerate apollo code for nextjs ssr

JavaScript 0.38% TypeScript 99.62%
graphql codegen apollo-client nextjs graphql-code-generator graphql-codegen

graphql-codegen-apollo-next-ssr's Introduction

Caffรจ corretto โ˜•๐Ÿฅƒ

Caffรจ corretto, an Italian beverage, consists of a shot of espresso with a small amount of liquor, usually grappa, and sometimes sambuca or brandy. It is also known (outside Italy) as an "espresso corretto".

Most Italian bartenders prepare a caffรจ corretto simply adding a few drops of the desired liquor into an espresso shot; however in some cases the liquor is served in a shot alongside the coffee allowing the customer to pour the quantity they desire. A few bartenders also let their regular customers make their drink themselves providing the espresso shot and the bottle of liquor.

The Italian word corretto reminds the (supposed) soundness of my code

JavaScript Nodejs Next.js Vercel React TypeScript GraphQL Deno

Top Langs

Hellas Verona ๐Ÿ’™๐Ÿ’›

last matches:

Hellas Verona FC Hellas Verona FC - Udinese Calcio: 1 - 0 ๐Ÿ˜„๐Ÿ’™๐Ÿ’›
Atalanta BC Atalanta BC - Hellas Verona FC: 2 - 2 ๐Ÿ˜
Hellas Verona FC Hellas Verona FC - Genoa CFC: 1 - 2 ๐Ÿ˜ญ
Cagliari Calcio Cagliari Calcio - Hellas Verona FC: 1 - 1 ๐Ÿ˜
Hellas Verona FC Hellas Verona FC - AC Milan: 1 - 3 ๐Ÿ˜ญ

next match:

Hellas Verona FC Hellas Verona FC - FC Internazionale Milano

Thanks Deno for the auto updated page

graphql-codegen-apollo-next-ssr's People

Contributors

anglinb avatar correttojs avatar dependabot[bot] avatar dvakatsiienko avatar kandros avatar kvithana avatar martijndeh avatar merceyz avatar ob6160 avatar renovate-bot avatar renovate[bot] avatar rohit-gohri avatar tmm 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

graphql-codegen-apollo-next-ssr's Issues

Respecting `importDocumentNodeExternallyFrom: near-operation-file`

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!

Example Doesn't Run

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:

  • C:\Users\riley\graphql-codegen-apollo-next-ssr\example\node_modules@graphql-codegen\plugin-helpers\index.js
  • C:\Users\riley\graphql-codegen-apollo-next-ssr\example\node_modules@graphql-codegen\cli\bin.js
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:880:15)
    at Function.Module._load (internal/modules/cjs/loader.js:725:27)
    at Module.require (internal/modules/cjs/loader.js:952:19)
    at require (internal/modules/cjs/helpers.js:88:18)
    at Object. (C:\Users\riley\graphql-codegen-apollo-next-ssr\example\node_modules@graphql-codegen\plugin-helpers\index.js:10:17)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Module.require (internal/modules/cjs/loader.js:952:19) {
    code: 'MODULE_NOT_FOUND',
    requireStack: [
    'C:\Users\riley\graphql-codegen-apollo-next-ssr\example\node_modules\@graphql-codegen\plugin-helpers\index.js',
    'C:\Users\riley\graphql-codegen-apollo-next-ssr\example\node_modules\@graphql-codegen\cli\bin.js'
    ]
    }
    error Command failed with exit code 1.`

Unable to get data from UNION types

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

React 17 support

this.imports.add(`import React from 'react';`);

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

Provided example not working

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.

console output (gist)

image

Docs: default values for replacePage and replaceQuery

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.

React wrongly imported as type

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} />

Trouble understanding limitations

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?

Mutation Behaviour

I am wondering if the behaviour when it comes to mutations is correct, for example i am seeing the following be generated

Screenshot 2020-11-20 at 23 55 28

Since mutations are designed to be deferred should these be ignored somehow ?

Allow setting `near-operation-file` file extension

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?

Errors returned by getServerPage() can't be serialized to JSON

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 from getServerSideProps 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 duplicate fragment docs

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

How to return multiple fetch responses on getServerSideProps or getStaticProps

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

Generated types output produces unused type if withHOC: false config value specified

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.

Make Apollo state key configurable

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.

const apolloState = apolloClient.cache.extract();
return {
props: {
apolloState,

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.

change example config?

maybe it's better to change the example config plugin option from

    plugins:
      - ./build/src/index.js

to

    plugins:
      - graphql-codegen-apollo-next-ssr

TS option strict: true

is it possible to use with Typescript compiler option 'strict: true' ?
it seems to be a little problem about 'optionsFunc' parameter which might be undefined value.
thank you for your work!
image

Trying it out with apollo client 3.0, missing `NormalizedCacheObject`

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'

Also getting a few errors:
Schermafbeelding 2020-07-20 om 10 43 36

Schermafbeelding 2020-07-20 om 10 43 41

Schermafbeelding 2020-07-20 om 10 43 46

Use `NextPage` for PageComp type instead of `React.FC`

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}>;

Getting TypeError when Node is a selection set

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.

Example doesn't work?

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:

Full Error Text
โ•ฐโ”€>$ 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.

Getting error `TypeError: visitFn.call is not a function`

image

Dependencies:
"@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"
Codegen file
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.

Error: Cannot find name 'Operations'.

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..

Change `getServerPage<Query>` to return the query instead of the cache/add a new method

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!

generated code has incorrect type for error

The generated code collapses the different possible errors into a single error property in the response:

From the test spec:

error: data?.error ?? data?.errors ?? null,

In that line of code:

  • data?.error is of type: Apollo.ApolloError | undefined
  • data?.errors is of type: ReadonlyArray<GraphQLError> | undefined
  • and both are nullish coalesced into null

The resulting type should be a compound type of those possibilities. However, the generated code incorrectly types this as error?: Apollo.ApolloError:

`export type PageFeedComp = React.FC<{data?: FeedQuery, error?: Apollo.ApolloError}>;`

Expected Behavior

  • Generated code types error as Apollo.ApolloError | readonly GraphQLError[] | null.

codegen issue

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)

Feature request: Add an option to return both query result and apollo cache.

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?

contextType is added as import

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?: )

Dependency Dashboard

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

Rate-Limited

These updates are currently rate-limited. Click on a checkbox below to force their creation now.

  • chore(deps): update dependency @types/jest to v29.5.12
  • chore(deps): update dependency @types/node to v18.19.31
  • chore(deps): update react monorepo to v18.3.1 (@types/react, react, react-dom)
  • ๐Ÿ” Create all rate-limited PRs at once ๐Ÿ”

Open

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

Detected dependencies

github-actions
.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
npm
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

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

NormalizedCacheObject is never used

Expected behavior

Generated file should not trigger errors with typescript compilation

Actual behavior

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?

Context

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

Cache results not changing even with fetch policy set to network-only or no-cache?

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),
)

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.