diff --git a/docs/astro.config.mjs b/docs/astro.config.mjs index 8d29d4b..0992d10 100644 --- a/docs/astro.config.mjs +++ b/docs/astro.config.mjs @@ -1,8 +1,10 @@ import { satteri } from "@astrojs/markdown-satteri"; +import sitemap from "@astrojs/sitemap"; import starlight from "@astrojs/starlight"; // @ts-check import { defineConfig } from "astro/config"; import starlightLlmsTxt from "starlight-llms-txt"; +import { lastModified } from "./src/lastModified.mjs"; const site = "https://orqc.7nohe.dev"; const ogUrl = new URL("og.jpg", site).href; @@ -37,6 +39,14 @@ export default defineConfig({ processor: satteri({ features: { smartPunctuation: false } }), }, integrations: [ + // Starlight adds the sitemap itself unless one is already here. This one + // also says when each page last changed. + sitemap({ + serialize(item) { + const lastmod = lastModified(new URL(item.url).pathname); + return lastmod ? { ...item, lastmod } : item; + }, + }), starlight({ title: "OpenAPI React Query Codegen", routeMiddleware: "./src/routeData.ts", @@ -61,11 +71,12 @@ export default defineConfig({ { label: "Getting started and usage", description: - "install, first run, the generated layout, using the generated hooks and queryOptions factories, every CLI option, mock data and MSW handlers, CI checks, coding agents and the FAQ", + "install, first run, the generated layout, using the generated hooks and queryOptions factories, every CLI option, configuring the client (base URL, tokens, interceptors), mock data and MSW handlers, CI checks, coding agents and the FAQ", paths: [ "guides/introduction", "guides/usage", "guides/cli-options", + "guides/client", "guides/mocking", "guides/ci-and-agents", "guides/faq", @@ -95,6 +106,7 @@ export default defineConfig({ "guides/introduction", "guides/usage", "guides/cli-options", + "guides/client", "guides/mocking", "guides/ci-and-agents", "guides/faq", @@ -138,6 +150,7 @@ export default defineConfig({ { slug: "guides/introduction" }, { slug: "guides/usage" }, { slug: "guides/cli-options" }, + { slug: "guides/client" }, { slug: "guides/mocking" }, { slug: "guides/ci-and-agents" }, { slug: "guides/comparison" }, diff --git a/docs/package.json b/docs/package.json index 0d0dbb7..0a0150e 100644 --- a/docs/package.json +++ b/docs/package.json @@ -12,6 +12,7 @@ "dependencies": { "@astrojs/check": "^0.9.4", "@astrojs/markdown-satteri": "0.4.7", + "@astrojs/sitemap": "3.7.4", "@astrojs/starlight": "^0.42.8", "@fontsource-variable/ibm-plex-sans": "5.3.0", "@fontsource/ibm-plex-mono": "5.3.0", diff --git a/docs/src/content/docs/guides/client.md b/docs/src/content/docs/guides/client.md new file mode 100644 index 0000000..a9cab87 --- /dev/null +++ b/docs/src/content/docs/guides/client.md @@ -0,0 +1,135 @@ +--- +title: Configuring the Client +description: Set the base URL, send a bearer token or an API key, add headers and cookies, and use request, response and error interceptors with the generated fetch or axios client. +--- + +Every generated hook sends its request through one client, exported from `openapi/requests/client.gen.ts`. Configure it once, in a module your application loads before the first request, and every hook uses that configuration. + +```ts +// src/client.ts +import { client } from "../openapi/requests/client.gen"; + +client.setConfig({ + baseUrl: "https://api.example.com", +}); +``` + +`setConfig` merges what you pass into the current configuration, so it can be called more than once. This page describes the fetch client first. [What differs with axios](#with-the-axios-client) is at the end. + +## Base URL + +Without configuration the client uses the first `servers` URL of the specification. Set `baseUrl` to send requests somewhere else, for example from an environment variable: + +```ts +client.setConfig({ + baseUrl: import.meta.env.VITE_API_URL, +}); +``` + +## Authentication + +For operations that declare `security` in the specification, give the client a token. It is sent the way the security scheme says: as `Authorization: Bearer ` for an HTTP bearer scheme, as `Basic` for HTTP basic, and in the header, query parameter or cookie that an API key scheme names. + +```ts +client.setConfig({ + auth: () => localStorage.getItem("token") ?? undefined, +}); +``` + +`auth` can be a string or a function, and the function can be asynchronous. It is called for each request, so a token that changes is picked up without configuring the client again. Operations without `security` are sent without the token. + +If the specification declares no `security`, send the header yourself with [`headers`](#headers-and-cookies) or with a [request interceptor](#interceptors). + +## Headers and cookies + +```ts +client.setConfig({ + headers: { "X-Tenant": "acme" }, + // Send cookies to another origin. + credentials: "include", +}); +``` + +Besides `headers`, the configuration takes the options of `fetch` itself, such as `credentials`, `cache` and `mode`. + +## Interceptors + +An interceptor sees every request, response or error of the client. + +```ts +// Before the request is sent. Return the request to send. +client.interceptors.request.use((request) => { + request.headers.set("X-Request-Id", crypto.randomUUID()); + return request; +}); + +// After a response arrives, successful or not. Return the response to use. +client.interceptors.response.use((response) => { + if (response.status === 401) { + window.location.assign("/login"); + } + return response; +}); + +// When a request fails. What it returns becomes the error. +client.interceptors.error.use((error, response) => { + console.error(response?.status, error); + return error; +}); +``` + +`use` returns an id. Pass it to `eject` to remove the interceptor: `client.interceptors.request.eject(id)`. + +## Options for one request + +The first argument of a query hook, and the variables of a mutation, take the same options next to `path`, `query` and `body`. They apply to that request only: + +```tsx +const { data } = useFindPets({ + query: { limit: 10 }, + headers: { "Accept-Language": "ja" }, +}); + +addPet({ body: { name: "Fluffy" }, headers: { "Idempotency-Key": key } }); +``` + +The options of a query hook are part of its query key, so two calls with different headers are two cache entries. A query key of your own, passed as the hook's second argument, takes the place of the options in the key. Put into it whatever changes the response, such as the language, or two calls that differ only in a header share one entry. + +## Errors + +When the server answers with an error status, the generated hooks reject. `error` is the body of the response, parsed as JSON when it is JSON, and typed from the error responses the specification declares: + +```tsx +const { error } = useFindPets(); +// error: { code: number; message: string } | null +``` + +The functions in `sdk.gen.ts` behave differently when you call them yourself: they resolve to `{ data, error }` and do not throw, unless you pass `throwOnError: true` or set it with `client.setConfig`. + +## With the axios client + +With `-c axios` the configuration takes the options of axios instead of those of `fetch`. Three things differ: + +- The base URL option is `baseURL`. +- Interceptors are those of axios, on the instance the client uses: `client.instance.interceptors.request.use(...)`. +- An error is an `AxiosError`, so the body is `error.response?.data`. + +```ts +import { client } from "../openapi/requests/client.gen"; + +client.setConfig({ + baseURL: "https://api.example.com", + auth: () => localStorage.getItem("token") ?? undefined, +}); + +client.instance.interceptors.request.use((config) => { + config.headers.set("X-Tenant", "acme"); + return config; +}); +``` + +`auth`, `headers` and the options for one request work as described above. + +## Server rendering + +A framework that bundles server and browser code separately has two copies of the client, and each one needs the configuration. See the [Next.js example](/examples/nextjs/#configure-the-client-and-the-provider). diff --git a/docs/src/content/docs/guides/faq.md b/docs/src/content/docs/guides/faq.md index ec82f8f..bf898e3 100644 --- a/docs/src/content/docs/guides/faq.md +++ b/docs/src/content/docs/guides/faq.md @@ -80,7 +80,7 @@ client.interceptors.request.use((request) => { }); ``` -With the axios client the option is `baseURL`, and interceptors are registered on the axios instance: `client.instance.interceptors.request.use(...)`. +With the axios client the option is `baseURL`, and interceptors are registered on the axios instance: `client.instance.interceptors.request.use(...)`. See [Configuring the Client](/guides/client/) for cookies, response and error interceptors, and options for one request. ### How are error responses handled? diff --git a/docs/src/content/docs/guides/introduction.mdx b/docs/src/content/docs/guides/introduction.mdx index 2d40cba..831473f 100644 --- a/docs/src/content/docs/guides/introduction.mdx +++ b/docs/src/content/docs/guides/introduction.mdx @@ -9,9 +9,13 @@ OpenAPI React Query Codegen is a code generator for creating React Query (also k ## Features - Generates custom react hooks that use React Query's `useQuery`, `useSuspenseQuery`, `useMutation` and `useInfiniteQuery` hooks +- Generates `queryOptions` and `infiniteQueryOptions` factories to use with `useQuery`, `useQueries`, loaders and the query client - Generates custom functions that use React Query's `ensureQueryData` and `prefetchQuery` functions - Generates query keys and functions for query caching - Generates a pure TypeScript client (types, SDK functions and a small fetch or axios runtime) from the same specification +- Optionally generates mock data and [MSW](/guides/mocking/) request handlers + +How it differs from Orval, Kubb, Hey API and openapi-react-query is on the [Comparison](/guides/comparison/) page. ## Installation @@ -80,12 +84,13 @@ openapi/ │ ├── infiniteQueries.ts │ ├── prefetch.ts │ ├── queries.ts +│ ├── queryOptions.ts │ └── suspense.ts └── requests - ├── client/ - ├── core/ ├── client.gen.ts ├── index.ts + ├── runtime.gen.ts + ├── schemas.gen.ts ├── sdk.gen.ts ├── services.gen.ts └── types.gen.ts @@ -107,7 +112,7 @@ Before using the generated hooks, you need to install the required dependencies. Then, add the `QueryClientProvider` to your application's entry point. -Also, you can set the base URL and interceptors for the generated client. +Also, you can set the base URL and interceptors for the generated client. [Configuring the client](/guides/client/) has the details. ```tsx // src/main.tsx @@ -181,10 +186,11 @@ export default App; - openapi - queries - - index.ts Main file that exports common types, variables, and queries. Does not export suspense or prefetch hooks - - common.ts Common types + - index.ts Re-exports `common.ts`, `queries.ts` and `queryOptions.ts`. Import the suspense, infinite, prefetch and ensureQueryData functions from their own files + - common.ts Common types, query keys and key functions - ensureQueryData.ts Generated ensureQueryData functions - queries.ts Generated query/mutation hooks + - queryOptions.ts Generated `queryOptions` and `infiniteQueryOptions` factories - infiniteQueries.ts Generated infinite query hooks - suspense.ts Generated suspense hooks - prefetch.ts Generated prefetch functions @@ -194,6 +200,7 @@ export default App; - sdk.gen.ts SDK functions (primary service functions) - services.gen.ts Backward-compatibility shim (re-exports from client.gen and sdk.gen) - types.gen.ts Generated TypeScript types + - schemas.gen.ts JSON schemas of the specification (unless `--noSchemas`) - index.ts Barrel file diff --git a/docs/src/content/docs/guides/usage.mdx b/docs/src/content/docs/guides/usage.mdx index bcd83f5..b0dfddf 100644 --- a/docs/src/content/docs/guides/usage.mdx +++ b/docs/src/content/docs/guides/usage.mdx @@ -46,7 +46,7 @@ function App() { export default App; ``` -## Using the generated `useQuerySuspense` hooks +## Using the generated `useSuspenseQuery` hooks ```tsx import { useFindPetsSuspense } from "../openapi/queries/suspense"; diff --git a/docs/src/content/docs/index.mdx b/docs/src/content/docs/index.mdx index 86231bd..cd35079 100644 --- a/docs/src/content/docs/index.mdx +++ b/docs/src/content/docs/index.mdx @@ -76,7 +76,7 @@ import { unit="s" /> -Median of five runs with Node.js {environment.node.replace("v", "")} on an {environment.cpu}, measured on {environment.date} with version {ownVersion}. Installing the generator adds {addedPackages[0].value} packages to a project, and its output for the Stripe and GitHub APIs compiles without a type error. [How these were measured, and the rest of the numbers](/guides/benchmarks/). +Median of five runs with Node.js {environment.node.replace("v", "")} on an {environment.cpu}, measured on {environment.date} with version {ownVersion}. Installing the generator adds {addedPackages[0].value} packages to a project, and its output for the Stripe and GitHub APIs compiles without a type error. [How these were measured, and the rest of the numbers](/guides/benchmarks/). [How it compares with Orval, Kubb, Hey API and openapi-react-query](/guides/comparison/). ## What lands in your project diff --git a/docs/src/lastModified.mjs b/docs/src/lastModified.mjs new file mode 100644 index 0000000..b772263 --- /dev/null +++ b/docs/src/lastModified.mjs @@ -0,0 +1,38 @@ +import { execFileSync } from "node:child_process"; +import { existsSync } from "node:fs"; +import { fileURLToPath } from "node:url"; + +const docsDir = fileURLToPath(new URL("./content/docs/", import.meta.url)); + +function git(...args) { + try { + return execFileSync("git", args, { + cwd: docsDir, + encoding: "utf8", + stdio: ["ignore", "pipe", "ignore"], + }).trim(); + } catch { + return ""; + } +} + +// A shallow clone has no commit older than its depth, so most pages would get +// the date of the oldest commit that was fetched. No date is better than a +// wrong one: the build host has to fetch the full history for these to appear +// (on Vercel, the VERCEL_DEEP_CLONE environment variable). +const hasHistory = git("rev-parse", "--is-shallow-repository") === "false"; + +/** + * When the page at `pathname` was last committed, for the sitemap. + * @param {string} pathname + * @returns {string | undefined} + */ +export function lastModified(pathname) { + if (!hasHistory) return undefined; + const slug = pathname.replace(/^\/|\/$/g, "") || "index"; + const file = ["mdx", "md"] + .map((extension) => `${slug}.${extension}`) + .find((name) => existsSync(docsDir + name)); + const date = file && git("log", "-1", "--format=%cI", "--", file); + return date ? new Date(date).toISOString() : undefined; +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 142de63..4057b6d 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -86,6 +86,9 @@ importers: '@astrojs/markdown-satteri': specifier: 0.4.7 version: 0.4.7 + '@astrojs/sitemap': + specifier: 3.7.4 + version: 3.7.4 '@astrojs/starlight': specifier: ^0.42.8 version: 0.42.10(astro@7.4.7(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.34.1)(tsx@4.23.12)(yaml@2.9.1))(typescript@5.6.3)