{"id":19571799,"url":"https://github.com/datocms/cda-client","last_synced_at":"2025-04-27T03:32:38.723Z","repository":{"id":250119342,"uuid":"833524534","full_name":"datocms/cda-client","owner":"datocms","description":"A lightweight NPM package that offers various helpers around the native Fetch API to perform GraphQL requests towards DatoCMS CDA.","archived":false,"fork":false,"pushed_at":"2025-04-02T12:31:33.000Z","size":1621,"stargazers_count":1,"open_issues_count":0,"forks_count":1,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-04-02T13:31:09.113Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/datocms.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-07-25T08:25:36.000Z","updated_at":"2025-04-02T12:31:36.000Z","dependencies_parsed_at":"2025-04-02T13:37:08.703Z","dependency_job_id":null,"html_url":"https://github.com/datocms/cda-client","commit_stats":null,"previous_names":["datocms/cda-client"],"tags_count":16,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/datocms%2Fcda-client","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/datocms%2Fcda-client/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/datocms%2Fcda-client/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/datocms%2Fcda-client/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/datocms","download_url":"https://codeload.github.com/datocms/cda-client/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":251085145,"owners_count":21533821,"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":[],"created_at":"2024-11-11T06:20:04.850Z","updated_at":"2025-04-27T03:32:38.716Z","avatar_url":"https://github.com/datocms.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003c!--datocms-autoinclude-header start--\u003e\n\n\u003ca href=\"https://www.datocms.com/\"\u003e\u003cimg src=\"https://www.datocms.com/images/full_logo.svg\" height=\"60\"\u003e\u003c/a\u003e\n\n👉 [Visit the DatoCMS homepage](https://www.datocms.com) or see [What is DatoCMS?](#what-is-datocms)\n\n---\n\n\u003c!--datocms-autoinclude-header end--\u003e\n\n# @datocms/cda-client\n\nA lightweight, TypeScript-ready package that offers various helpers around the native Fetch API to perform GraphQL requests towards DatoCMS [Content Delivery API](https://www.datocms.com/docs/content-delivery-api).\n\n## TypeScript Support\n\nThis package is built with TypeScript and provides type definitions out of the box. It supports `TypedDocumentNode` for improved type inference when using [gql.tada](https://gql-tada.0no.co/), [GraphQL Code Generator](https://the-guild.dev/graphql/codegen) or similar tools.\n\n## Examples\n\n### Basic Query Execution\n\n```typescript\nimport { executeQuery } from \"@datocms/cda-client\";\n\nconst query = `\n  query {\n    allArticles {\n      id\n      title\n    }\n  }\n`;\n\nconst result = await executeQuery(query, {\n  token: \"your-api-token-here\",\n});\n\nconsole.log(result);\n```\n\n### Using with TypeScript and GraphQL Code Generator\n\n```typescript\nimport { executeQuery } from \"@datocms/cda-client\";\nimport { AllArticlesQuery } from \"./generated/graphql\";\n\nconst result = await executeQuery(AllArticlesQuery, {\n  token: \"your-api-token-here\",\n  variables: {\n    limit: 10,\n  },\n});\n\nconsole.log(result.allArticles);\n```\n\n## Installation\n\n```bash\nnpm install @datocms/cda-client\n```\n\n## Usage\n\nThis package provides several utility functions to help you interact with the DatoCMS Content Delivery API using GraphQL.\n\n### `executeQuery`\n\nThe main function to execute a GraphQL query against the DatoCMS Content Delivery API.\n\n```typescript\nimport { executeQuery } from \"@datocms/cda-client\";\n\nconst result = await executeQuery(query, options);\n```\n\n#### Parameters\n\n- `query`: A GraphQL query string, `DocumentNode`, or `TypedDocumentNode`.\n- `options`: An object containing execution options.\n\n#### Options\n\n| Option               | Type                   | Description                                                                                                                                                   |\n| -------------------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `token`              | `string`               | DatoCMS API token (required) [Read more](https://www.datocms.com/docs/content-delivery-api/authentication)                                                    |\n| `includeDrafts`      | `boolean`              | If true, return draft versions of records [Read more](https://www.datocms.com/docs/content-delivery-api/api-endpoints#preview-mode-to-retrieve-draft-content) |\n| `excludeInvalid`     | `boolean`              | If true, filter out invalid records [Read more](https://www.datocms.com/docs/content-delivery-api/api-endpoints#strict-mode-for-non-nullable-graphql-types)   |\n| `environment`        | `string`               | Name of the DatoCMS environment for the query [Read more](https://www.datocms.com/docs/content-delivery-api/api-endpoints#specifying-an-environment)          |\n| `contentLink`        | `'vercel-v1'`          | If true, embed metadata for Content Link [Read more](https://www.datocms.com/docs/content-delivery-api/api-endpoints#content-link)                            |\n| `baseEditingUrl`     | `string`               | Base URL of your DatoCMS project [Read more](https://www.datocms.com/docs/content-delivery-api/api-endpoints#content-link)                                    |\n| `returnCacheTags`    | `boolean`              | If true, receive Cache Tags associated with the query [Read more](https://www.datocms.com/docs/content-delivery-api/api-endpoints#cache-tags)                 |\n| `variables`          | `object`               | Variables to be sent with the query                                                                                                                           |\n| `fetchFn`            | `function`             | Custom fetch function (optional)                                                                                                                              |\n| `requestInitOptions` | `Partial\u003cRequestInit\u003e` | Additional request initialization options (optional)                                                                                                          |\n| `autoRetry`          | `boolean`              | Automatically retry on rate limit (default: true)                                                                                                             |\n\n### `rawExecuteQuery`\n\nSimilar to `executeQuery`, but returns both the query result and the full response object. This can be handy when used together with returnCacheTags to actually retrieve the cache tags.\n\n```typescript\nimport { rawExecuteQuery } from \"@datocms/cda-client\";\n\nconst [result, response] = await rawExecuteQuery(query, {\n  token: \"your-api-token-here\",\n  returnCacheTags: true,\n});\nconst cacheTags = response.headers.get(\"x-cache-tags\");\n```\n\n### `executeQueryWithAutoPagination`\n\nThis function comes handy when the query contains a paginated collection: behind the scene,\n`executeQueryWithAutoPagination` reworks the passed query and collects the results, so that\nit's possible to get a collection of records that is longer than Content Delivery API's result limit.\nThat is done with a single API call, in a transparent way.\n\n```typescript\nimport { executeQueryWithAutoPagination } from \"@datocms/cda-client\";\n\nconst result = await executeQueryWithAutoPagination(query, options);\n```\n\n#### Parameters\n\nParameters are the same available for `executeQuery`:\n\n- `query`: A GraphQL query string, `DocumentNode`, or `TypedDocumentNode`.\n- `options`: An object containing execution options with the same shape of options for `executeQuery`.\n\n### How does it work?\n\nSuppose you want to execute the following query:\n\n```graphql\nquery BuildSitemapUrls {\n  allBlogPosts {\n    slug\n  }\n\n  entries: allSuccessStories(first: 500) {\n    ...SuccessStoryUrlFragment\n  }\n}\n\nfragment SuccessStoryUrlFragment on SuccessStoryRecord {\n  slug\n}\n```\n\nWell, that's a roadblock: DatoCMS CDA has limitations on the pagination page length (currently 500 items).\n\nThat means you should introduce a variable and execute the query multiple times, each time skipping the record\nthat have been returned by the previous query.\n\n`executeQueryWithAutoPagination` does that on your behalf: the above query is analyzed and rewritten on the fly like this:\n\n```graphql\nquery BuildSitemapUrls {\n  allBlogPosts {\n    slug\n  }\n  splitted_0_entries: allSuccessStories(first: 500, skip: 0) {\n    ...SuccessStoryUrlFragment\n  }\n  splitted_500_entries: allSuccessStories(first: 500, skip: 500) {\n    ...SuccessStoryUrlFragment\n  }\n  splitted_1000_entries: allSuccessStories(first: 500, skip: 1000) {\n    ...SuccessStoryUrlFragment\n  }\n  splitted_1500_entries: allSuccessStories(first: 500, skip: 1500) {\n    ...SuccessStoryUrlFragment\n  }\n  splitted_2000_entries: allSuccessStories(first: 500, skip: 2000) {\n    ...SuccessStoryUrlFragment\n  }\n}\n\nfragment SuccessStoryUrlFragment on SuccessStoryRecord {\n  slug\n}\n```\n\nOnce executed, the results get collected and recomposed as if nothing happened.\n\n#### Limitations\n\n`executeQueryWithAutoPagination` works only when the query contains only one selection that has \nan oversized `first:` argument (i.e. `first:` argument surpasses the Content Delivery API's result limit).\nIf two or more fields have oversiaed patination, the function triggers an error.\n\nThe rewritten query must still respect the [complexity cost](https://www.datocms.com/docs/content-delivery-api/complexity).\n\n### `rawExecuteQueryWithAutoPagination`\n\nAs for `executeQuery`, also `executeQueryWithAutoPagination` has a pair raw version that returns both the query result and the full response object.\nThis can be handy when used together with returnCacheTags to actually retrieve the cache tags.\n\n```typescript\nimport { rawExecuteQueryWithAutoPagination } from \"@datocms/cda-client\";\n\nconst [result, response] = await rawExecuteQueryWithAutoPagination(query, {\n  token: \"your-api-token-here\",\n  returnCacheTags: true,\n});\nconst cacheTags = response.headers.get(\"x-cache-tags\");\n```\n\n### `buildRequestHeaders`\n\nBuilds request headers for a GraphQL query towards the DatoCMS Content Delivery API.\n\n```typescript\nimport { buildRequestHeaders } from \"@datocms/cda-client\";\n\nconst headers = buildRequestHeaders(options);\n```\n\n#### Options\n\nThe `buildRequestHeaders` function accepts the same options as `executeQuery`, except for `variables`, `fetchFn`, and `autoRetry`.\n\n### `buildRequestInit`\n\nBuilds the request initialization object for a GraphQL query towards the DatoCMS Content Delivery API.\n\n```typescript\nimport { buildRequestInit } from \"@datocms/cda-client\";\n\nconst requestInit = buildRequestInit(query, options);\n```\n\n#### Parameters\n\n- `query`: A GraphQL query string or `DocumentNode`.\n- `options`: An object containing execution options (same as `executeQuery`).\n\n## Error Handling\n\nIn case a query fails (either with an HTTP status code outside of the 2xx range, or for an error in the query), an `ApiError` exception will be thrown by the client. This error contains all the details of the request and response, allowing you to debug and handle errors effectively.\n\n### Example\n\n```typescript\nimport { executeQuery, ApiError } from \"@datocms/cda-client\";\n\nconst query = `\n  query {\n    allArticles {\n      id\n      title\n    }\n  }\n`;\n\ntry {\n  const result = await executeQuery(query, {\n    token: \"your-api-token-here\",\n  });\n  console.log(result);\n} catch (e) {\n  if (e instanceof ApiError) {\n    // Information about the failed request\n    console.log(e.query);\n    console.log(e.options);\n\n    // Information about the response\n    console.log(e.response.status);\n    console.log(e.response.statusText);\n    console.log(e.response.headers);\n    console.log(e.response.body);\n  } else {\n    // Handle other types of errors\n    throw e;\n  }\n}\n```\n\n## Contributing\n\nContributions are welcome! Please feel free to submit a Pull Request.\n\n## License\n\nThis project is licensed under the MIT License.\n\n\u003c!--datocms-autoinclude-footer start--\u003e\n\n---\n\n# What is DatoCMS?\n\n\u003ca href=\"https://www.datocms.com/\"\u003e\u003cimg src=\"https://www.datocms.com/images/full_logo.svg\" height=\"60\" alt=\"DatoCMS - The Headless CMS for the Modern Web\"\u003e\u003c/a\u003e\n\n[DatoCMS](https://www.datocms.com/) is the REST \u0026 GraphQL Headless CMS for the modern web.\n\nTrusted by over 25,000 enterprise businesses, agencies, and individuals across the world, DatoCMS users create online content at scale from a central hub and distribute it via API. We ❤️ our [developers](https://www.datocms.com/team/best-cms-for-developers), [content editors](https://www.datocms.com/team/content-creators) and [marketers](https://www.datocms.com/team/cms-digital-marketing)!\n\n**Why DatoCMS?**\n\n- **API-First Architecture**: Built for both REST and GraphQL, enabling flexible content delivery\n- **Just Enough Features**: We believe in keeping things simple, and giving you [the right feature-set tools](https://www.datocms.com/features) to get the job done\n- **Developer Experience**: First-class TypeScript support with powerful developer tools\n\n**Getting Started:**\n\n- ⚡️ [Create Free Account](https://dashboard.datocms.com/signup) - Get started with DatoCMS in minutes\n- 🔖 [Documentation](https://www.datocms.com/docs) - Comprehensive guides and API references\n- ⚙️ [Community Support](https://community.datocms.com/) - Get help from our team and community\n- 🆕 [Changelog](https://www.datocms.com/product-updates) - Latest features and improvements\n\n**Official Libraries:**\n\n- [**Content Delivery Client**](https://github.com/datocms/cda-client) - TypeScript GraphQL client for content fetching\n- [**REST API Clients**](https://github.com/datocms/js-rest-api-clients) - Node.js/Browser clients for content management\n- [**CLI Tools**](https://github.com/datocms/cli) - Command-line utilities for schema migrations (includes [Contentful](https://github.com/datocms/cli/tree/main/packages/cli-plugin-contentful) and [WordPress](https://github.com/datocms/cli/tree/main/packages/cli-plugin-wordpress) importers)\n\n**Official Framework Integrations**\n\nHelpers to manage SEO, images, video and Structured Text coming from your DatoCMS projects:\n\n- [**React Components**](https://github.com/datocms/react-datocms)\n- [**Vue Components**](https://github.com/datocms/vue-datocms)\n- [**Svelte Components**](https://github.com/datocms/datocms-svelte)\n- [**Astro Components**](https://github.com/datocms/astro-datocms)\n\n**Additional Resources:**\n\n- [**Plugin Examples**](https://github.com/datocms/plugins) - Example plugins we've made that extend the editor/admin dashboard\n- [**Starter Projects**](https://www.datocms.com/marketplace/starters) - Example website implementations for popular frameworks\n- [**All Public Repositories**](https://github.com/orgs/datocms/repositories?q=\u0026type=public\u0026language=\u0026sort=stargazers)\n\n\u003c!--datocms-autoinclude-footer end--\u003e\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdatocms%2Fcda-client","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdatocms%2Fcda-client","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdatocms%2Fcda-client/lists"}