{"id":13727050,"url":"https://github.com/rubengrill/apollo-typed-documents","last_synced_at":"2025-05-07T22:30:48.833Z","repository":{"id":39335405,"uuid":"255319477","full_name":"rubengrill/apollo-typed-documents","owner":"rubengrill","description":"Get type safety for your apollo documents.","archived":false,"fork":false,"pushed_at":"2023-03-27T19:13:09.000Z","size":4852,"stargazers_count":23,"open_issues_count":47,"forks_count":6,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-04-26T13:42:09.338Z","etag":null,"topics":["apollo-hooks","apollo-react","codegen","typescript"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/rubengrill.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2020-04-13T12:26:46.000Z","updated_at":"2023-06-19T19:05:15.000Z","dependencies_parsed_at":"2024-01-07T21:16:20.011Z","dependency_job_id":null,"html_url":"https://github.com/rubengrill/apollo-typed-documents","commit_stats":{"total_commits":47,"total_committers":5,"mean_commits":9.4,"dds":"0.23404255319148937","last_synced_commit":"5fd3cbdbbb3ba0c8b5c5fabebc2e9af740cdfa32"},"previous_names":[],"tags_count":6,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rubengrill%2Fapollo-typed-documents","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rubengrill%2Fapollo-typed-documents/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rubengrill%2Fapollo-typed-documents/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rubengrill%2Fapollo-typed-documents/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/rubengrill","download_url":"https://codeload.github.com/rubengrill/apollo-typed-documents/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252965186,"owners_count":21832835,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["apollo-hooks","apollo-react","codegen","typescript"],"created_at":"2024-08-03T01:03:37.458Z","updated_at":"2025-05-07T22:30:47.420Z","avatar_url":"https://github.com/rubengrill.png","language":"TypeScript","funding_links":[],"categories":["TypeScript"],"sub_categories":[],"readme":"# apollo-typed-documents\n\nProvides graphql-codegen plugins (https://graphql-code-generator.com/) for type safe GraphQL documents (`DocumentNode`).\n\nIt allows functions to accept a generic `TypedDocumentNode\u003cTVariables, TData\u003e` so that types of other arguments or the return type can be inferred.\n\nIt is helpful for TypeScript projects but also if used only within an IDE, e.g. it works extremely well with VSCode (uses TypeScript behind the scenes).\n\n```sh\n$ yarn add apollo-typed-documents\n```\n\n## codegenTypedDocuments\n\nGenerates TypeScript typings for `.graphql` files.\n\nSimilar to `@graphql-codegen/typescript-graphql-files-modules` (https://graphql-code-generator.com/docs/plugins/typescript-graphql-files-modules).\n\nThe difference is that is uses generic types, so that you have type safety with Apollo (e.g. `useQuery` / `useMutation`).\n\nThe `apollo-typed-documents` plugin also accepts the same `modulePathPrefix`, `relativeToCwd` and `prefix` config settings as [typescript-graphql-files-modules](https://graphql-code-generator.com/docs/plugins/typescript-graphql-files-modules).\n\n### Install\n\n```sh\n$ yarn add @graphql-codegen/add @graphql-codegen/typescript @graphql-codegen/typescript-operations\n$ yarn add apollo-typed-documents\n```\n\n`codegen.yml`:\n\n\u003c!-- AUTO-GENERATED-CONTENT:START (CODE:src=./examples/docs/codegenTypedDocuments.yml) --\u003e\n\u003c!-- The below code snippet is automatically added from ./examples/docs/codegenTypedDocuments.yml --\u003e\n```yml\nschema: schema.graphql\ndocuments: src/**/*.graphql\nconfig:\n  scalars:\n    Date: string\ngenerates:\n  ./src/codegenTypedDocuments.d.ts:\n    plugins:\n      - apollo-typed-documents/lib/codegenTypedDocuments\n    config:\n      typesModule: \"@codegen-types\"\n  ./src/codegenTypes.d.ts:\n    plugins:\n      - add:\n          placement: prepend\n          content: 'declare module \"@codegen-types\" {'\n      - add:\n          placement: append\n          content: \"}\"\n      - typescript\n      - typescript-operations\n```\n\u003c!-- AUTO-GENERATED-CONTENT:END --\u003e\n\n`tsconfig.json`:\n\nAdd `node_modules/apollo-typed-documents/lib/reactHooks.d.ts` in `include` to override the typings for hooks of `@apollo/client`, so that types can be inferred from typed documents.\n\n\u003c!-- AUTO-GENERATED-CONTENT:START (CODE:src=./examples/docs/tsconfig.json) --\u003e\n\u003c!-- The below code snippet is automatically added from ./examples/docs/tsconfig.json --\u003e\n```json\n{\n  \"compilerOptions\": {\n    \"noEmit\": true,\n    \"allowJs\": true,\n    \"checkJs\": true,\n    \"strict\": true,\n    \"jsx\": \"react\",\n    \"esModuleInterop\": true\n  },\n  \"include\": [\"src\", \"node_modules/apollo-typed-documents/lib/reactHooks.d.ts\"]\n}\n```\n\u003c!-- AUTO-GENERATED-CONTENT:END --\u003e\n\n### Example\n\n`src/authors.graphql`:\n\n\u003c!-- AUTO-GENERATED-CONTENT:START (CODE:src=./examples/docs/src/authors.graphql) --\u003e\n\u003c!-- The below code snippet is automatically added from ./examples/docs/src/authors.graphql --\u003e\n```graphql\nquery authors {\n  authors {\n    id\n    createdAt\n    name\n    description\n    books {\n      id\n      title\n    }\n  }\n}\n```\n\u003c!-- AUTO-GENERATED-CONTENT:END --\u003e\n\n`src/createAuthor.graphql`:\n\n\u003c!-- AUTO-GENERATED-CONTENT:START (CODE:src=./examples/docs/src/createAuthor.graphql) --\u003e\n\u003c!-- The below code snippet is automatically added from ./examples/docs/src/createAuthor.graphql --\u003e\n```graphql\nmutation createAuthor($input: AuthorInput!) {\n  createAuthor(input: $input) {\n    id\n    createdAt\n    name\n    description\n    books {\n      id\n      title\n    }\n  }\n}\n```\n\u003c!-- AUTO-GENERATED-CONTENT:END --\u003e\n\n`src/codegenTypedDocuments.d.ts` (generated):\n\n\u003c!-- AUTO-GENERATED-CONTENT:START (CODE:src=./examples/docs/src/codegenTypedDocuments.d.ts) --\u003e\n\u003c!-- The below code snippet is automatically added from ./examples/docs/src/codegenTypedDocuments.d.ts --\u003e\n```ts\ndeclare module \"*/authors.graphql\" {\n  import { TypedDocumentNode } from \"apollo-typed-documents\";\n  import { AuthorsQuery, AuthorsQueryVariables } from \"@codegen-types\";\n  export const authors: TypedDocumentNode\u003cAuthorsQueryVariables, AuthorsQuery\u003e;\n  export default authors;\n}\n\ndeclare module \"*/createAuthor.graphql\" {\n  import { TypedDocumentNode } from \"apollo-typed-documents\";\n  import { CreateAuthorMutation, CreateAuthorMutationVariables } from \"@codegen-types\";\n  export const createAuthor: TypedDocumentNode\u003cCreateAuthorMutationVariables, CreateAuthorMutation\u003e;\n  export default createAuthor;\n}\n```\n\u003c!-- AUTO-GENERATED-CONTENT:END --\u003e\n\n`src/AuthorList.js`:\n\n\u003c!-- AUTO-GENERATED-CONTENT:START (CODE:src=./examples/docs/src/AuthorList.js) --\u003e\n\u003c!-- The below code snippet is automatically added from ./examples/docs/src/AuthorList.js --\u003e\n```js\nimport { useMutation, useQuery } from \"@apollo/client\";\nimport React from \"react\";\n\nimport authorsQuery from \"./authors.graphql\";\nimport createAuthorMutation from \"./createAuthor.graphql\";\n\nconst AuthorList = () =\u003e {\n  // Type of `data` is inferred (AuthorsQuery)\n  const { data } = useQuery(authorsQuery);\n  const [createAuthor] = useMutation(createAuthorMutation);\n\n  return (\n    \u003c\u003e\n      \u003cul\u003e\n        {data?.authors.map((author) =\u003e (\n          \u003cli key={author.id}\u003e{author.name}\u003c/li\u003e\n        ))}\n      \u003c/ul\u003e\n      \u003cbutton\n        onClick={() =\u003e {\n          createAuthor({\n            // Type of variables is inferred (CreateAuthorMutationVariables)\n            variables: { input: { name: \"Foo\", books: [{ title: \"Bar\" }] } },\n          });\n        }}\n      \u003e\n        Add\n      \u003c/button\u003e\n    \u003c/\u003e\n  );\n};\n\nexport default AuthorList;\n```\n\u003c!-- AUTO-GENERATED-CONTENT:END --\u003e\n\n### Notes for `create-react-app` users\n\n`create-react-app` supports `graphql.macro` for loading `.graphql` files (https://create-react-app.dev/docs/loading-graphql-files/).\n\nThe `codegenTypedDocuments` plugin generates ambient module declarations for `.graphql` files, which means that `.graphql` files must be imported as regular modules (`import` syntax) so that TypeScript knows about the types.\n\nYou can use the babel plugin `babel-plugin-import-graphql` (https://github.com/detrohutt/babel-plugin-import-graphql), but then you need to use `react-app-rewired` (https://github.com/timarney/react-app-rewired/) and `customize-cra` (https://github.com/arackaf/customize-cra) so that you can define custom babel plugins.\n\n```sh\n$ yarn add react-app-rewired customize-cra\n$ yarn add babel-plugin-import-graphql\n```\n\n`config-overrides.js`\n\n```js\nconst { override, useBabelRc } = require(\"customize-cra\");\n\nmodule.exports = override(useBabelRc());\n```\n\n`.babelrc`\n\n```json\n{\n  \"presets\": [\"react-app\"],\n  \"plugins\": [\"babel-plugin-import-graphql\"]\n}\n```\n\n`package.json`\n\n```js\n\"scripts\": {\n  \"start\": \"react-app-rewired start\",\n  \"build\": \"react-app-rewired build\",\n  \"test\": \"react-app-rewired test\",\n  ...\n}\n```\n\nIf you have a TypeScript app, you need to override the `@apollo/client` types for hooks in `tsconfig.json`:\n\n`tsconfig.json`\n\n```js\n{\n  \"compilerOptions\": {\n    ...\n  },\n  \"include\": [\"src\", \"node_modules/apollo-typed-documents/lib/reactHooks.d.ts\"]\n}\n```\n\nIf you don't have a TypeScript app (you just want TypeScript support within your IDE) you can't create a `tsconfig.json` in your app folder, because `create-react-app` uses that file to detect if this is a TypeScript project.\n\nInstead, you have to create the `tsconfig.json` in your `src` folder:\n\n`src/tsconfig.json`\n\n\u003c!-- AUTO-GENERATED-CONTENT:START (CODE:src=./examples/cra/src/tsconfig.json) --\u003e\n\u003c!-- The below code snippet is automatically added from ./examples/cra/src/tsconfig.json --\u003e\n```json\n{\n  \"compilerOptions\": {\n    \"noEmit\": true,\n    \"allowJs\": true,\n    \"checkJs\": true,\n    \"strict\": true,\n    \"jsx\": \"react\",\n    \"esModuleInterop\": true\n  },\n  \"include\": [\".\", \"../node_modules/apollo-typed-documents/lib/reactHooks.d.ts\"]\n}\n```\n\u003c!-- AUTO-GENERATED-CONTENT:END --\u003e\n\nPlease see the following example projects for more details:\n\n- [`create-react-app` with TypeScript](examples/cra-ts)\n- [`create-react-app` without TypeScript](examples/cra)\n\n## codegenApolloMock\n\nCreates a helper method to easily create mocks for Apollo `MockedProvider` (https://www.apollographql.com/docs/react/api/react-testing/#mockedprovider).\n\nThe returned object is guaranteed to conform to the GraphQL Schema of the query / mutation: [reference](src/createApolloMock.ts).\n\nFor required (non-null) fields which are not provided (in data / variables), it will use a default value (e.g. `\"Author-id\"`).\n\nFor optional fields which are not provided (in data / variables), it will use `undefined` for variables and `null` for data.\n\nWorks for any nested selections (data) and any nested inputs (variables).\n\nIt will include `__typename` in data by default. This can be deactivated as an option:\n\n```js\napolloMock(documentNode, variables, result, { addTypename: false });\n```\n\nWhen used together with `codegenTypedDocuments` the data and variables are type checked (type inference).\n\nTo mock errors, you can provide `errors` in `result` (`GraphQLError`) or pass an `Error` instead of `result`:\n\n```js\napolloMock(documentNode, variables, { errors: [new GraphQLError(\"Already exists\")] });\napolloMock(documentNode, variables, new Error(\"Network error\"));\n```\n\n### Install\n\n```sh\n$ yarn add apollo-typed-documents\n```\n\n`codegen.yml`\n\n\u003c!-- AUTO-GENERATED-CONTENT:START (CODE:src=./examples/docs/codegenApolloMock.yml) --\u003e\n\u003c!-- The below code snippet is automatically added from ./examples/docs/codegenApolloMock.yml --\u003e\n```yml\nschema: schema.graphql\ndocuments: src/**/*.graphql\nconfig:\n  scalars:\n    Date: string\ngenerates:\n  ./src/apolloMock.js:\n    plugins:\n      - apollo-typed-documents/lib/codegenApolloMock\n```\n\u003c!-- AUTO-GENERATED-CONTENT:END --\u003e\n\n### Example\n\n`schema.graphql`:\n\n\u003c!-- AUTO-GENERATED-CONTENT:START (CODE:src=./examples/docs/schema.graphql) --\u003e\n\u003c!-- The below code snippet is automatically added from ./examples/docs/schema.graphql --\u003e\n```graphql\nscalar Date\n\ntype Author {\n  id: ID!\n  createdAt: Date!\n  name: String!\n  description: String\n  books: [Book!]!\n}\n\ntype Book {\n  id: ID!\n  title: String!\n}\n\ninput AuthorInput {\n  name: String!\n  description: String\n  books: [BookInput!]!\n}\n\ninput BookInput {\n  title: String!\n}\n\ntype Query {\n  authors: [Author!]!\n}\n\ntype Mutation {\n  createAuthor(input: AuthorInput!): Author!\n}\n\nschema {\n  query: Query\n  mutation: Mutation\n}\n```\n\u003c!-- AUTO-GENERATED-CONTENT:END --\u003e\n\n`src/authors.graphql`:\n\n\u003c!-- AUTO-GENERATED-CONTENT:START (CODE:src=./examples/docs/src/authors.graphql) --\u003e\n\u003c!-- The below code snippet is automatically added from ./examples/docs/src/authors.graphql --\u003e\n```graphql\nquery authors {\n  authors {\n    id\n    createdAt\n    name\n    description\n    books {\n      id\n      title\n    }\n  }\n}\n```\n\u003c!-- AUTO-GENERATED-CONTENT:END --\u003e\n\n`src/createAuthor.graphql`:\n\n\u003c!-- AUTO-GENERATED-CONTENT:START (CODE:src=./examples/docs/src/createAuthor.graphql) --\u003e\n\u003c!-- The below code snippet is automatically added from ./examples/docs/src/createAuthor.graphql --\u003e\n```graphql\nmutation createAuthor($input: AuthorInput!) {\n  createAuthor(input: $input) {\n    id\n    createdAt\n    name\n    description\n    books {\n      id\n      title\n    }\n  }\n}\n```\n\u003c!-- AUTO-GENERATED-CONTENT:END --\u003e\n\n`src/apolloMock.js` (generated):\n\nSee: [reference](examples/docs/src/apolloMock.js)\n\n`src/apolloMock.test.js`:\n\n\u003c!-- AUTO-GENERATED-CONTENT:START (CODE:src=./examples/docs/src/apolloMock.test.js) --\u003e\n\u003c!-- The below code snippet is automatically added from ./examples/docs/src/apolloMock.test.js --\u003e\n```js\nimport { GraphQLError } from \"graphql\";\n\nimport apolloMock from \"./apolloMock\";\nimport authors from \"./authors.graphql\";\nimport createAuthor from \"./createAuthor.graphql\";\n\ndescribe(\"apolloMock\", () =\u003e {\n  it(\"produces the minimal output that is valid according to graphql schema\", () =\u003e {\n    expect(apolloMock(authors, {}, {})).toEqual({\n      request: {\n        query: authors,\n        variables: {},\n      },\n      result: {\n        data: {\n          authors: [],\n        },\n      },\n    });\n\n    expect(apolloMock(authors, {}, { data: { authors: [{}] } })).toEqual({\n      request: {\n        query: authors,\n        variables: {},\n      },\n      result: {\n        data: {\n          authors: [\n            {\n              __typename: \"Author\",\n              id: \"Author-id\",\n              createdAt: \"Author-createdAt\",\n              name: \"Author-name\",\n              description: null,\n              books: [],\n            },\n          ],\n        },\n      },\n    });\n\n    expect(\n      apolloMock(\n        createAuthor,\n        { input: { name: \"Foo\", books: [{ title: \"Bar\" }] } },\n        { data: { createAuthor: { name: \"Foo\", books: [{ title: \"Bar\" }] } } }\n      )\n    ).toEqual({\n      request: {\n        query: createAuthor,\n        variables: {\n          input: {\n            name: \"Foo\",\n            description: undefined,\n            books: [{ title: \"Bar\" }],\n          },\n        },\n      },\n      result: {\n        data: {\n          createAuthor: {\n            __typename: \"Author\",\n            id: \"Author-id\",\n            createdAt: \"Author-createdAt\",\n            name: \"Foo\",\n            description: null,\n            books: [\n              {\n                __typename: \"Book\",\n                id: \"Book-id\",\n                title: \"Bar\",\n              },\n            ],\n          },\n        },\n      },\n    });\n  });\n\n  it(\"allows overriding default values for scalar types\", () =\u003e {\n    const scalarValues = { Date: \"2020-01-01\" };\n\n    expect(\n      apolloMock(authors, {}, { data: { authors: [{}] } }, { scalarValues })\n    ).toEqual({\n      request: {\n        query: authors,\n        variables: {},\n      },\n      result: {\n        data: {\n          authors: [\n            {\n              __typename: \"Author\",\n              id: \"Author-id\",\n              createdAt: \"2020-01-01\",\n              name: \"Author-name\",\n              description: null,\n              books: [],\n            },\n          ],\n        },\n      },\n    });\n  });\n\n  it(\"supports errors\", () =\u003e {\n    expect(\n      apolloMock(authors, {}, { errors: [new GraphQLError(\"Already exists\")] })\n    ).toEqual({\n      request: {\n        query: authors,\n        variables: {},\n      },\n      result: {\n        errors: [new GraphQLError(\"Already exists\")],\n      },\n    });\n\n    expect(apolloMock(authors, {}, new Error(\"Network error\"))).toEqual({\n      request: {\n        query: authors,\n        variables: {},\n      },\n      error: new Error(\"Network error\"),\n    });\n  });\n});\n```\n\u003c!-- AUTO-GENERATED-CONTENT:END --\u003e\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frubengrill%2Fapollo-typed-documents","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frubengrill%2Fapollo-typed-documents","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frubengrill%2Fapollo-typed-documents/lists"}