Openapi Qraft Github Documentation

website·Indexed 30 days ago

https://openapi-qraft.github.io/openapi-qraft

Searchable website documentation for Openapi Qraft Github from https://openapi-qraft.github.io/openapi-qraft.

Tokens
77.2K
Snippets
319
Records
459
Agent score
69%

What's inside Openapi Qraft Github Documentation

  1. Overview of OpenAPI Qraft

    OpenAPI Qraft is a library for creating type-safe API Hooks in React applications based on OpenAPI Documents. It is built on TanStack Query v5 and uses a Proxy-based API client design to automatically generate hooks with strict typing, eliminating manual boilerplate. It supports Server-Side Rendering (SSR), including compatibility with the Next.js /app directory.
  2. Overview of OpenAPI Qraft

    OpenAPI Qraft is a library for creating type-safe API Hooks in React applications based on OpenAPI Documents. It is built on TanStack Query v5 and uses a Proxy-based API client design to automatically generate hooks with strict TypeScript typing, reducing boilerplate and runtime errors. It supports Server-Side Rendering (SSR), including compatibility with the Next.js /app directory.
  3. Overview of openapi-qraft API Client

    openapi-qraft is an API client for React designed to provide strong typing and TSDoc generation for requests. It focuses on being lightweight by minimizing the amount of generated runtime code to optimize bundle size and enhance security checks. The client is built on top of TanStack Query, inheriting all of its caching and state management features.
  4. Overview of OpenAPI Qraft

    OpenAPI Qraft is a library used to create type-safe API hooks for React applications based on OpenAPI Documents. It leverages TanStack Query v5 and uses a Proxy-based API client design to generate custom hooks with strictly-typed parameters, eliminating manual boilerplate. It supports Server-Side Rendering (SSR), including the Next.js /app directory.
  5. Generate the predefined parameters request function utility

    To enable the generation of the create-predefined-parameters-request-fn.ts file, use the --operation-predefined-parameters option when running the @openapi-qraft/cli. This utility allows you to create a custom requestFn that automatically injects predefined parameters into specified API operations.
    npx openapi-qraft ... --operation-predefined-parameters '\/**:header.x-monite-version' 'get /**,!/auth/**:header.x-monite-entity-id'
  6. Generate code using qraft openapi plugins

    The qraft openapi command uses a plugin system to determine what code is generated. Plugins are specified using the --plugin <name> option. Multiple plugins can be used simultaneously. By default, the tanstack-query-react plugin is used if none are specified.
    # Generate Qraft Services and openapi-typescript types
    qraft openapi --plugin tanstack-query-react --plugin openapi-typescript
    
    # Generate Qraft Services only
    qraft openapi --plugin tanstack-query-react
    
    # Generate openapi-typescript types only
    qraft openapi --plugin openapi-typescript
  7. Configure automatic JWT token refreshing using QraftSecureRequestFn

    Use QraftSecureRequestFn to handle the lifecycle of a Bearer token. By providing a security scheme handler, you can define how to obtain a new token and how to refresh an existing one. The resulting secureRequestFn automatically injects the Authorization: Bearer <token> header into requests that require the specified security scheme.
    import { ReactNode } from 'react';
    import { requestFn, QraftContext } from '@openapi-qraft/react';
    import { QraftSecureRequestFn } from '@openapi-qraft/react/Unstable_QraftSecureRequestFn';
    import { createAPIClient } from './api'; // generated by OpenAPI Qraft CLI
    
    const qraft = createAPIClient();
    
    const App = ({ children }: { children: ReactNode }) => {
      return (
        <QraftSecureRequestFn
          requestFn={requestFn}
          securitySchemes={{
            // 'clientToken' matches the security scheme name in your OpenAPI spec
            clientToken: async ({ isRefreshing }) => {
              if (!isRefreshing) {
                const { access_token } = await qraft.auth.obtainToken({
                  body: { grant_type: 'client_credentials' },
                }, requestFn);
                return access_token;
              }
    
              const { access_token } = await qraft.auth.refreshToken({
                body: { grant_type: 'client_credentials' },
              }, requestFn);
    
              return access_token;
            }
          }}
        >
          {(secureRequestFn) => (
            <QraftContext.Provider value={{ requestFn: secureRequestFn }}>
              {children}
            </QraftContext.Provider>
          )}
        </QraftSecureRequestFn>
      );
    };
    
    export default App;
  8. Migrate qraftAPIClient calls to v2.6.0

    In OpenAPI Qraft v2.6.0, generic type parameters <Services, Callbacks> have been removed from qraftAPIClient function calls. Types are now automatically inferred from the arguments, simplifying the API and improving type inference.
    // Before v2.6.0
    const api = qraftAPIClient<Services, Callbacks>(services, callbacks, options);
    
    // After v2.6.0
    const api = qraftAPIClient(services, callbacks, options);
  9. Example: Implement a document upload status indicator

    This example demonstrates how to use useIsMutating to track both a specific document upload (filtered by entity_id) and the total number of document uploads occurring across the application.
    import { createAPIClient } from './api';
    import { requestFn } from '@openapi-qraft/react';
    import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
    
    const queryClient = new QueryClient();
    const api = createAPIClient({
      requestFn,
      queryClient,
      baseUrl: 'https://api.sandbox.monite.com/v1',
    });
    
    function DocumentsUploadStatus() {
      // Track mutation for a specific entity
      const creatingDocument = api.entities.postEntitiesIdDocuments.useIsMutating({
        parameters: {
          path: {
            entity_id: '1',
          },
        }
      });
    
      // Track all mutations for this operation
      const creatingDocumentTotal = api.entities.postEntitiesIdDocuments.useIsMutating();
    
      return (
        <>
          {!!creatingDocumentTotal && <div>Number of creating documents: {creatingDocumentTotal}...</div>}
          {!!creatingDocument && <div>Creating document...</div>}
        </>
      );
    }
    
    export default function App() {
      return (
        <QueryClientProvider client={queryClient}>
          <DocumentsUploadStatus />
        </QueryClientProvider>
      );
    }
  10. Set up `qraft openapi` in a project

    To integrate the OpenAPI code generation into your project, install the necessary CLI and plugins as dev dependencies and add a generation script to your package.json.
    {
      "devDependencies": {
        "@qraft/cli": "latest",
        "@openapi-qraft/openapi-typescript-plugin": "latest",
        "@openapi-qraft/tanstack-query-react-plugin": "latest"
      },
      "scripts": {
        "generate-client": "qraft openapi --plugin tanstack-query-react --plugin openapi-typescript https://raw.githubusercontent.com/swagger-api/swagger-petstore/master/src/main/resources/openapi.yaml --output-dir src/api"
      }
    }
  11. Example: Implementing loading indicators with useIsFetching

    This example demonstrates how to track the total number of fetching queries for a general operation and how to track a specific query based on path parameters and headers.
    import { createAPIClient } from './api'; // generated by OpenAPI Qraft CLI
    
    const qraft = createAPIClient();
    
    function FetchStatus() {
      // Checks all queries for `GET /entities`
      const fetchingTotal = qraft.entities.getEntities.useIsFetching();
    
      // Checks all queries for `GET /entities/3e3e-3e3e-3e3e` with a specific header
      const specificQueryKeyTotal = qraft.entities.getEntities.useIsFetching({
        infinite: false,
        parameters: {
          header: {
            'x-monite-version': '2023-09-01',
          },
          path: {
            entity_id: '3e3e-3e3e-3e3e',
          },
        },
      });
    
      return (
        <>
          {!!fetchingTotal && <div>Number of queries: {fetchingTotal}...</div>}
          {!!specificQueryKeyTotal && <div>Loading specific query...</div>}
        </>
      );
    }
  12. Execute concurrent requests with useSuspenseQueries

    The useSuspenseQueries hook allows you to execute multiple asynchronous data fetching operations concurrently with built-in support for React Suspense. It is functionally similar to useQueries but integrates with Suspense for loading states. The hook is accessed via the generated API client using the pattern: qraft.<service>.<operation>.useSuspenseQueries(options, queryClient).
    const result = qraft.<service>.<operation>.useSuspenseQueries(
      options,
      queryClient
    )