# @geekmidas/client 中文文档

规范地址：https://npmcn.com/package/%40geekmidas/client/

版本：9\.6\.1
npm 元数据更新时间：2026-11-16T09:28:23.567Z
中文译文更新时间：2026-11-16T09:37:34.229Z
软件包许可：未声明

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40geekmidas/client
原文对照：https://npmcn.com/package/%40geekmidas/client/?lang=original
项目主页：https://github.com/geekmidas/toolbox#readme
源码仓库：https://github.com/geekmidas/toolbox

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：619 kB，93 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：2 个
- peer 依赖：zod ^4\.1\.13，react \>=18\.0\.0，react-dom \>=18\.0\.0，@geekmidas/schema ^9\.6\.1，@geekmidas/constructs ^9\.6\.1，@tanstack/react-query \>=5\.0\.0
- 首次发布：2025-10-19T18:21:30.655Z
- 最新版本发布：2026-11-16T09:28:23.187Z
- 近 30 天下载量：13155（2026-10-16 至 2026-11-14，npm 官方下载统计）
- 已发布版本数：216（近 12 个月 215 个）

## 中文简介

用于消耗HTTP API的Type-seafe客户端库,配备了完整的TypeScript支持,React Query集成,以及从OpenAPI规格中自动生成代码.

## 安装

```sh
npm install @geekmidas/client
```

也可以使用：`pnpm add @geekmidas/client`、`yarn add @geekmidas/client`、`bun add @geekmidas/client`

## README

# @geekmidas/ 客户端

用于消耗HTTP API的Type-seafe客户端库,配备了完整的TypeScript支持,React Query集成,以及从OpenAPI规格中自动生成代码.

## 特征

-   **类型安全获取器**: 使用自动类型推论的完全输入的 HTTP 客户端
-   **重复查询集成**: 预建有 TypeScript 支持的钩子
-   **OpenAPI 代码生成**: 从 OpenAPI 光谱生成回放查询钩
-   **无限查询**: 内置支持页码和无限卷轴
-   **自动验证**: 与标准Schema进行请求/答复验证
-   **处理错误**: 用 HTTP 状态代码处理类型安全错误
-   **查询无效**: 类型安全缓存无效
-   **方法限制**: 每一端点HTTP方法的类型级执行

## 安装

```bash
pnpm add @geekmidas/client
```

对反应查询集成 :

```bash
pnpm add @geekmidas/client @tanstack/react-query
```

## 软件包导出

```typescript
// Type-safe fetcher
import { createTypedFetcher } from '@geekmidas/client';

// Auth-aware fetcher with security schemes
import { createAuthAwareFetcher } from '@geekmidas/client/auth-fetcher';

// React Query hooks (endpoint-string based)
import { createEndpointHooks } from '@geekmidas/client/endpoint-hooks';

// React Query client (class-based)
import { createTypedQueryClient } from '@geekmidas/client/react-query';

// OpenAPI hooks generation
import { generateReactQueryHooks } from '@geekmidas/client/openapi';

// Type utilities
import type { TypedApiFunction, FilteredRequestConfig } from '@geekmidas/client/types';
```

## 快速启动

### 类型安全获取器

为您的 API 创建打入器 :

```typescript
import { createTypedFetcher } from '@geekmidas/client';

// Define your API types
interface API {
  'GET /users': {
    response: {
      id: string;
      name: string;
      email: string;
    }[];
  };
  'POST /users': {
    body: {
      name: string;
      email: string;
    };
    response: {
      id: string;
      name: string;
      email: string;
    };
  };
  'GET /users/:id': {
    params: {
      id: string;
    };
    response: {
      id: string;
      name: string;
      email: string;
    };
  };
}

// Create typed fetcher
const api = createTypedFetcher<API>({
  baseUrl: 'https://api.example.com'
});

// Use with full type safety
const users = await api('GET /users');
// users is typed as Array<{ id: string; name: string; email: string }>

const user = await api('POST /users', {
  body: { name: 'John Doe', email: 'john@example.com' }
});
// user is typed as { id: string; name: string; email: string }

const singleUser = await api('GET /users/:id', {
  params: { id: '123' }
});
// singleUser is typed as { id: string; name: string; email: string }
```

### 重复查询集成

使用 React 查询用于自动缓存和状态管理 :

```typescript
import { createTypedQueryClient } from '@geekmidas/client/react-query';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';

// Create query client
const queryClient = new QueryClient();
const api = createTypedQueryClient<API>({
  baseUrl: 'https://api.example.com'
});

// In your component
function UsersList() {
  const { data, isLoading, error } = api.useQuery('GET /users');

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <ul>
      {data.map(user => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}

// Mutations
function CreateUser() {
  const createUser = api.useMutation('POST /users');

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    await createUser.mutateAsync({
      body: { name: 'Jane Doe', email: 'jane@example.com' }
    });
  };

  return (
    <form onSubmit={handleSubmit}>
      <button disabled={createUser.isPending}>
        Create User
      </button>
    </form>
  );
}
```

### 查询参数

以全类型安全处理查询参数 :

```typescript
interface API {
  'GET /users/search': {
    query: {
      q: string;
      limit?: number;
      offset?: number;
    };
    response: {
      users: Array<{ id: string; name: string }>;
      total: number;
    };
  };
}

// Usage
const result = await api('GET /users/search', {
  query: { q: 'john', limit: 10 }
});
```

### 无限查询

执行无限滚动平面图 :

```typescript
function InfiniteUsersList() {
  const {
    data,
    fetchNextPage,
    hasNextPage,
    isFetchingNextPage
  } = api.useInfiniteQuery(
    'GET /users',
    {
      query: { limit: 20 }
    },
    {
      getNextPageParam: (lastPage, pages) => {
        if (pages.length * 20 < lastPage.total) {
          return { offset: pages.length * 20 };
        }
        return undefined;
      }
    }
  );

  return (
    <div>
      {data?.pages.map((page, i) => (
        <div key={i}>
          {page.users.map(user => (
            <div key={user.id}>{user.name}</div>
          ))}
        </div>
      ))}
      {hasNextPage && (
        <button
          onClick={() => fetchNextPage()}
          disabled={isFetchingNextPage}
        >
          Load More
        </button>
      )}
    </div>
  );
}
```

## 生成 API 客户端( 建议)

使用时 `@geekmidas/cli` 要生成 OpenAPI 类型,请获得一个完整的配置 `createApi` 工厂:

```typescript
// Generated by: gkm openapi --output ./src/api.ts
import { createApi } from './api';

// Create API client with authentication
const api = createApi({
  baseURL: 'https://api.example.com',
  authStrategies: {
    // Only strategies for schemes actually used in your API are required
    jwt: {
      type: 'bearer',
      tokenProvider: async () => localStorage.getItem('token'),
    },
  },
});

// Imperative fetching - callable directly
const user = await api('GET /users/{id}', { params: { id: '123' } });

// React Query hooks - available as properties
function UserProfile({ id }: { id: string }) {
  // Config is required when endpoint has path params
  const { data, isLoading } = api.useQuery('GET /users/{id}', {
    params: { id }
  });

  if (isLoading) return <div>Loading...</div>;
  return <div>{data.name}</div>;
}

// Mutations
function CreateUser() {
  const mutation = api.useMutation('POST /users');

  return (
    <button onClick={() => mutation.mutate({
      body: { name: 'John', email: 'john@example.com' }
    })}>
      Create User
    </button>
  );
}
```

### 类型安全配置要求

生成的客户端在类型级别执行配置要求 :

```typescript
// ✅ GET /health - no params, no body → config optional
await api('GET /health');

// ❌ GET /users/{id} - has params → config required
await api('GET /users/{id}'); // Type error!

// ✅ GET /users/{id} - with required params
await api('GET /users/{id}', { params: { id: '123' } });

// ❌ POST /users - has body → config required
await api('POST /users'); // Type error!

// ✅ POST /users - with required body
await api('POST /users', { body: { name: 'John', email: 'john@example.com' } });
```

### 认证策略

这个 `authStrategies` 选项将安全方案ID映射给认证处理器 :

```typescript
const api = createApi({
  baseURL: 'https://api.example.com',
  authStrategies: {
    // Bearer token (JWT)
    jwt: {
      type: 'bearer',
      tokenProvider: async () => getAccessToken(),
    },

    // API Key in header
    apiKey: {
      type: 'apiKey',
      tokenProvider: async () => process.env.API_KEY,
    },

    // Custom authentication
    custom: {
      type: 'custom',
      applyAuth: async (headers) => {
        headers.set('X-Custom-Auth', await getCustomToken());
      },
    },
  },
});
```

## 自动获取器

用于不生成代码的手动设置, 使用 `createAuthAwareFetcher`数字 :

```typescript
import { createAuthAwareFetcher } from '@geekmidas/client/auth-fetcher';
import { createEndpointHooks } from '@geekmidas/client/endpoint-hooks';
import type { paths } from './openapi-types';

// Define which endpoints use which auth
const endpointAuth = {
  'GET /users': 'jwt',
  'POST /users': 'jwt',
  'GET /health': null, // Public endpoint
} as const;

// Define security schemes
const securitySchemes = {
  jwt: { type: 'http', scheme: 'bearer', bearerFormat: 'JWT' },
} as const;

// Create auth-aware fetcher
const fetcher = createAuthAwareFetcher<
  paths,
  typeof endpointAuth,
  typeof securitySchemes
>({
  baseURL: 'https://api.example.com',
  endpointAuth,
  securitySchemes,
  authStrategies: {
    jwt: {
      type: 'bearer',
      tokenProvider: async () => localStorage.getItem('token'),
    },
  },
});

// Add React Query hooks
const hooks = createEndpointHooks<paths>(fetcher);

// Combine into single API object
const api = Object.assign(fetcher, hooks);
```

## OpenAPI 代码生成

从 OpenAPI 规格生成反应查询钩 :

```bash
# Using CLI
pnpm gkm generate:react-query --input api-docs.json --output ./src/api

# Programmatic usage
import { generateReactQueryHooks } from '@geekmidas/client/openapi';
import fs from 'fs/promises';

const spec = JSON.parse(await fs.readFile('api-docs.json', 'utf-8'));
const code = await generateReactQueryHooks(spec);
await fs.writeFile('./src/api/generated.ts', code);
```

生成的钩子示例 :

```typescript
// Generated from OpenAPI spec
export const api = createTypedQueryClient<{
  'GET /users': {
    response: User[];
  };
  'POST /users': {
    body: CreateUserRequest;
    response: User;
  };
  // ... all your endpoints
}>({
  baseUrl: process.env.REACT_APP_API_URL
});

// Use generated hooks
function MyComponent() {
  const { data: users } = api.useQuery('GET /users');
  const createUser = api.useMutation('POST /users');

  return (
    // Your component
  );
}
```

## 高级特性

### 查询无效

类型安全缓存无效 :

```typescript
// Invalidate specific query
await api.invalidateQueries('GET /users');

// Invalidate with params
await api.invalidateQueries('GET /users/:id', {
  params: { id: '123' }
});

// Invalidate multiple queries
await Promise.all([
  api.invalidateQueries('GET /users'),
  api.invalidateQueries('GET /users/:id')
]);
```

### 优化更新

执行乐观的用户界面更新 :

```typescript
const updateUser = api.useMutation('PUT /users/:id', {
  onMutate: async (variables) => {
    // Cancel outgoing refetches
    await api.cancelQueries('GET /users/:id', {
      params: { id: variables.params.id }
    });

    // Snapshot previous value
    const previousUser = api.getQueryData('GET /users/:id', {
      params: { id: variables.params.id }
    });

    // Optimistically update
    api.setQueryData('GET /users/:id', {
      params: { id: variables.params.id }
    }, variables.body);

    return { previousUser };
  },
  onError: (err, variables, context) => {
    // Rollback on error
    if (context?.previousUser) {
      api.setQueryData('GET /users/:id', {
        params: { id: variables.params.id }
      }, context.previousUser);
    }
  },
  onSettled: (data, error, variables) => {
    // Refetch after mutation
    api.invalidateQueries('GET /users/:id', {
      params: { id: variables.params.id }
    });
  }
});
```

### 自定义信头

在请求中添加自定义信头 :

```typescript
const api = createTypedFetcher<API>({
  baseUrl: 'https://api.example.com',
  headers: {
    'Authorization': `Bearer ${token}`,
    'X-Api-Key': apiKey
  }
});

// Per-request headers
const user = await api('GET /users/:id', {
  params: { id: '123' },
  headers: {
    'X-Request-ID': requestId
  }
});
```

### 处理错误

全类型安全处理出错 :

```typescript
import { HttpError } from '@geekmidas/errors';

try {
  const user = await api('GET /users/:id', {
    params: { id: '123' }
  });
} catch (error) {
  if (error instanceof HttpError) {
    if (error.statusCode === 404) {
      console.log('User not found');
    } else if (error.statusCode === 403) {
      console.log('Access denied');
    } else {
      console.error('API error:', error.message);
    }
  } else {
    console.error('Unexpected error:', error);
  }
}
```

### 请求/答复拦截者

为日志、 认证等添加截取器 :

```typescript
const api = createTypedFetcher<API>({
  baseUrl: 'https://api.example.com',
  beforeRequest: async (url, options) => {
    // Add auth token
    const token = await getAuthToken();
    options.headers = {
      ...options.headers,
      'Authorization': `Bearer ${token}`
    };
    return { url, options };
  },
  afterResponse: async (response) => {
    // Log response
    console.log(`${response.status} ${response.url}`);
    return response;
  },
  onError: async (error) => {
    // Handle auth errors
    if (error instanceof HttpError && error.statusCode === 401) {
      await refreshAuthToken();
      // Retry request
    }
    throw error;
  }
});
```

### 预选

更好的 UX 预选查询 :

```typescript
function UsersList() {
  const { data: users } = api.useQuery('GET /users');

  const handleUserHover = (userId: string) => {
    // Prefetch user details on hover
    api.prefetchQuery('GET /users/:id', {
      params: { id: userId }
    });
  };

  return (
    <ul>
      {users?.map(user => (
        <li
          key={user.id}
          onMouseEnter={() => handleUserHover(user.id)}
        >
          {user.name}
        </li>
      ))}
    </ul>
  );
}
```

## 类型公用事业

### 推断 API 类型

```typescript
import type { InferAPIResponse, InferAPIRequest } from '@geekmidas/client/types';

type UsersResponse = InferAPIResponse<API, 'GET /users'>;
// type UsersResponse = Array<{ id: string; name: string; email: string }>

type CreateUserRequest = InferAPIRequest<API, 'POST /users'>;
// type CreateUserRequest = { body: { name: string; email: string } }
```

### 方法限制

在类型级别执行正确的HTTP方法 :

```typescript
// ✅ Correct - POST endpoint with body
await api('POST /users', {
  body: { name: 'John' }
});

// ❌ Type error - GET endpoint can't have body
await api('GET /users', {
  body: { name: 'John' } // Type error!
});

// ❌ Type error - Wrong method
await api('DELETE /users', {}); // Type error if endpoint not defined!
```

## 测试

Moc API呼叫测试:

```typescript
import { createTypedFetcher } from '@geekmidas/client';
import { vi } from 'vitest';

const mockFetch = vi.fn();
global.fetch = mockFetch;

const api = createTypedFetcher<API>({
  baseUrl: 'https://api.example.com'
});

// Mock response
mockFetch.mockResolvedValueOnce({
  ok: true,
  json: async () => [{ id: '1', name: 'John', email: 'john@example.com' }]
});

const users = await api('GET /users');
expect(users).toHaveLength(1);
expect(mockFetch).toHaveBeenCalledWith(
  'https://api.example.com/users',
  expect.objectContaining({ method: 'GET' })
);
```

## 相关软件包

-   [@geekmidas/ 构造](https://npmcn.com/package/%40geekmidas/constructs) - 构建该客户端所消耗的型号安全端点
-   [@geekmidas/错误](https://npmcn.com/package/%40geekmidas/errors) - HTTP 错误类别,用于错误处理
-   [@geekmidas/ cli (英语)](https://npmcn.com/package/%40geekmidas/cli) - 生成 OpenAPI 规格并反演查询钩
-   [@tastack/ react-query (英语)](https://tanstack.com/query) - 反应查询库

## 许可证

麻省理工学院

## 常见问题

### @geekmidas/client 是什么？

用于消耗HTTP API的Type-seafe客户端库,配备了完整的TypeScript支持,React Query集成,以及从OpenAPI规格中自动生成代码\.

### 如何安装 @geekmidas/client？

在项目目录运行 npm install @geekmidas/client，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：zod（^4\.1\.13）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @geekmidas/client 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @geekmidas/client 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @geekmidas/client 可以商用吗？

@geekmidas/client 使用 未声明 许可。package\.json 没有声明许可证。没有许可证的代码默认保留全部权利，商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括，不构成法律意见，请以许可原文为准。

### @geekmidas/client 的下载量有多少？

根据 npm 官方下载统计，@geekmidas/client 在 2026/10/16 – 2026/11/14 这 30 天内被下载 13,155 次，日均约 439 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @geekmidas/client 还在维护吗？

最新版本 9\.6\.1 发布于 2026/11/16（今天）；至今共发布 216 个版本，其中过去 12 个月发布了 215 个；首次发布于 2025/10/20。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

