生产管理系统前端 - openapi - fetch生成器开发

This commit is contained in:
2025-10-27 21:53:18 +08:00
parent 5055e40de6
commit 42a4a9f566
29 changed files with 4264 additions and 1463 deletions

View File

@@ -1,14 +1,654 @@
import ApiExample from '@/components/examples/ApiExample';
'use client';
import { useState } from 'react';
import {
loginApiV1AuthLoginPost,
registerApiV1AuthRegisterPost,
getCurrentUserApiV1AuthMeGet,
getAllUsersApiV1AuthUsersGet,
logoutApiV1AuthLogoutPost,
rootGet,
healthCheckHealthGet,
type UserLogin,
type UserRegister,
type ApiResponse
} from '@/lib/api';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Badge } from '@/components/ui/badge';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Separator } from '@/components/ui/separator';
export default function ApiExamplePage() {
const [loading, setLoading] = useState(false);
const [results, setResults] = useState<any[]>([]);
const [errors, setErrors] = useState<string[]>([]);
// 登录表单状态
const [loginData, setLoginData] = useState<UserLogin>({
username: '',
password: ''
});
// 注册表单状态
const [registerData, setRegisterData] = useState<UserRegister>({
username: '',
password: ''
});
// 添加结果到显示列表
const addResult = (type: string, input: any, output: any, error?: string) => {
const result = {
id: Date.now(),
type,
input,
output,
error,
timestamp: new Date().toLocaleTimeString()
};
setResults(prev => [result, ...prev]);
if (error) {
setErrors(prev => [error, ...prev]);
}
};
// 清空结果
const clearResults = () => {
setResults([]);
setErrors([]);
};
// 用户登录
const handleLogin = async () => {
setLoading(true);
try {
addResult('用户登录', '登录请求', '发送中...');
const response = await loginApiV1AuthLoginPost({
body: loginData
});
if (response.data) {
addResult('用户登录', loginData, response.data);
} else if (response.error) {
addResult('用户登录', loginData, null, JSON.stringify(response.error));
}
} catch (error: any) {
addResult('用户登录', loginData, null, error.message);
} finally {
setLoading(false);
}
};
// 用户注册
const handleRegister = async () => {
setLoading(true);
try {
addResult('用户注册', '注册请求', '发送中...');
const response = await registerApiV1AuthRegisterPost({
body: registerData
});
if (response.data) {
addResult('用户注册', registerData, response.data);
} else if (response.error) {
addResult('用户注册', registerData, null, JSON.stringify(response.error));
}
} catch (error: any) {
addResult('用户注册', registerData, null, error.message);
} finally {
setLoading(false);
}
};
// 获取当前用户信息
const handleGetCurrentUser = async () => {
setLoading(true);
try {
addResult('获取当前用户', 'GET /api/v1/auth/me', '发送中...');
const response = await getCurrentUserApiV1AuthMeGet({});
if (response.data) {
addResult('获取当前用户', '无参数', response.data);
} else if (response.error) {
addResult('获取当前用户', '无参数', null, JSON.stringify(response.error));
}
} catch (error: any) {
addResult('获取当前用户', '无参数', null, error.message);
} finally {
setLoading(false);
}
};
// 获取所有用户
const handleGetAllUsers = async () => {
setLoading(true);
try {
addResult('获取所有用户', 'GET /api/v1/auth/users', '发送中...');
const response = await getAllUsersApiV1AuthUsersGet({});
if (response.data) {
addResult('获取所有用户', '无参数', response.data);
} else if (response.error) {
addResult('获取所有用户', '无参数', null, JSON.stringify(response.error));
}
} catch (error: any) {
addResult('获取所有用户', '无参数', null, error.message);
} finally {
setLoading(false);
}
};
// 用户登出
const handleLogout = async () => {
setLoading(true);
try {
addResult('用户登出', 'POST /api/v1/auth/logout', '发送中...');
const response = await logoutApiV1AuthLogoutPost({});
if (response.data) {
addResult('用户登出', '无参数', response.data);
} else if (response.error) {
addResult('用户登出', '无参数', null, JSON.stringify(response.error));
}
} catch (error: any) {
addResult('用户登出', '无参数', null, error.message);
} finally {
setLoading(false);
}
};
return (
<div className="min-h-screen bg-background">
<ApiExample />
<div className="min-h-screen bg-background p-6">
<div className="max-w-7xl mx-auto">
<div className="flex justify-between items-center mb-6">
<h1 className="text-3xl font-bold">OpenAPI </h1>
<Button
variant="outline"
onClick={clearResults}
disabled={results.length === 0}
>
({results.length})
</Button>
</div>
<Tabs defaultValue="interactive" className="w-full">
<TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="interactive"></TabsTrigger>
<TabsTrigger value="examples"></TabsTrigger>
</TabsList>
<TabsContent value="interactive" className="space-y-6">
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
{/* 左侧API 操作面板 */}
<Card>
<CardHeader>
<CardTitle>API </CardTitle>
<CardDescription>
使 @hey-api/openapi-ts
</CardDescription>
</CardHeader>
<CardContent>
<Tabs defaultValue="auth" className="w-full">
<TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="auth"></TabsTrigger>
<TabsTrigger value="user"></TabsTrigger>
</TabsList>
<TabsContent value="auth" className="space-y-4">
{/* 登录表单 */}
<div className="space-y-2">
<h4 className="font-medium"></h4>
<Input
placeholder="用户名"
value={loginData.username}
onChange={(e) => setLoginData(prev => ({ ...prev, username: e.target.value }))}
/>
<Input
type="password"
placeholder="密码"
value={loginData.password}
onChange={(e) => setLoginData(prev => ({ ...prev, password: e.target.value }))}
/>
<Button
onClick={handleLogin}
disabled={loading || !loginData.username || !loginData.password}
className="w-full"
>
{loading ? '登录中...' : '登录'}
</Button>
</div>
{/* 注册表单 */}
<div className="space-y-2">
<h4 className="font-medium"></h4>
<Input
placeholder="用户名"
value={registerData.username}
onChange={(e) => setRegisterData(prev => ({ ...prev, username: e.target.value }))}
/>
<Input
type="password"
placeholder="密码"
value={registerData.password}
onChange={(e) => setRegisterData(prev => ({ ...prev, password: e.target.value }))}
/>
<Button
onClick={handleRegister}
disabled={loading || !registerData.username || !registerData.password}
variant="outline"
className="w-full"
>
{loading ? '注册中...' : '注册'}
</Button>
</div>
</TabsContent>
<TabsContent value="user" className="space-y-4">
<div className="grid grid-cols-1 gap-2">
<Button
onClick={handleGetCurrentUser}
disabled={loading}
variant="outline"
>
</Button>
<Button
onClick={handleGetAllUsers}
disabled={loading}
variant="outline"
>
</Button>
<Button
onClick={handleLogout}
disabled={loading}
variant="outline"
>
</Button>
</div>
</TabsContent>
</Tabs>
</CardContent>
</Card>
{/* 右侧:结果显示面板 */}
<Card>
<CardHeader>
<CardTitle> & </CardTitle>
<CardDescription>
API
</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-4 max-h-[600px] overflow-y-auto">
{results.length === 0 ? (
<div className="text-center text-muted-foreground py-8">
<p> API </p>
<p className="text-sm"> API </p>
</div>
) : (
results.map((result) => (
<div key={result.id} className="border rounded-lg p-4 space-y-2">
<div className="flex items-center justify-between">
<h4 className="font-medium">{result.type}</h4>
<div className="flex items-center gap-2">
<Badge variant="outline">{result.timestamp}</Badge>
{result.error ? (
<Badge variant="destructive"></Badge>
) : (
<Badge variant="default"></Badge>
)}
</div>
</div>
{/* 输入数据 */}
<div className="space-y-1">
<p className="text-sm font-medium text-muted-foreground">:</p>
<pre className="text-xs bg-muted p-2 rounded overflow-x-auto">
{JSON.stringify(result.input, null, 2)}
</pre>
</div>
{/* 输出数据 */}
<div className="space-y-1">
<p className="text-sm font-medium text-muted-foreground">
{result.error ? '错误信息:' : '响应数据:'}
</p>
<pre className={`text-xs p-2 rounded overflow-x-auto ${
result.error ? 'bg-destructive/10 text-destructive' : 'bg-muted'
}`}>
{result.error || JSON.stringify(result.output, null, 2)}
</pre>
</div>
</div>
))
)}
</div>
</CardContent>
</Card>
</div>
{/* 错误提示 */}
{errors.length > 0 && (
<div className="mt-6">
<Alert>
<AlertDescription>
{errors.length}
</AlertDescription>
</Alert>
</div>
)}
</TabsContent>
<TabsContent value="examples" className="space-y-6">
<ApiExamplesPage />
</TabsContent>
</Tabs>
</div>
</div>
);
}
export const metadata = {
title: 'API 调用示例 - 智慧农业生产管理系统',
description: '测试和展示 OpenAPI 客户端的类型安全 API 调用',
};
// API示例页面组件
function ApiExamplesPage() {
const [examplesLoading, setExamplesLoading] = useState<Record<string, boolean>>({});
const [examplesResults, setExamplesResults] = useState<Record<string, any>>({});
// API示例配置 - 基于openapi.json
const apiExamples = [
{
id: 'login',
method: 'POST',
path: '/api/v1/auth/login',
title: '用户登录',
description: '用户登录接口',
exampleParams: {
username: 'admin',
password: 'admin123'
},
expectedOutput: {
success: true,
message: '登录成功',
data: { token: 'jwt_token_here' }
}
},
{
id: 'register',
method: 'POST',
path: '/api/v1/auth/register',
title: '用户注册',
description: '用户注册接口',
exampleParams: {
username: 'newuser',
password: 'newpassword'
},
expectedOutput: {
success: true,
message: '注册成功',
data: { user_id: 1, username: 'newuser' }
}
},
{
id: 'me',
method: 'GET',
path: '/api/v1/auth/me',
title: '获取当前用户信息',
description: '获取当前登录用户的信息',
exampleParams: null,
expectedOutput: {
success: true,
message: '获取用户信息成功',
data: { user_id: 1, username: 'admin' }
}
},
{
id: 'logout',
method: 'POST',
path: '/api/v1/auth/logout',
title: '用户登出',
description: '用户登出接口',
exampleParams: null,
expectedOutput: {
success: true,
message: '登出成功',
data: null
}
},
{
id: 'users',
method: 'GET',
path: '/api/v1/auth/users',
title: '获取所有用户列表',
description: '获取系统中所有用户的列表 (仅用于演示)',
exampleParams: null,
expectedOutput: {
success: true,
message: '获取用户列表成功',
data: [{ user_id: 1, username: 'admin' }]
}
},
{
id: 'root',
method: 'GET',
path: '/',
title: '根路径',
description: 'API根路径用于测试连接',
exampleParams: null,
expectedOutput: {}
},
{
id: 'health',
method: 'GET',
path: '/health',
title: '健康检查',
description: 'API健康检查接口',
exampleParams: null,
expectedOutput: { status: 'healthy' }
}
];
// 调用示例API
const callExampleApi = async (example: typeof apiExamples[0]) => {
setExamplesLoading(prev => ({ ...prev, [example.id]: true }));
try {
let response;
switch (example.id) {
case 'login':
response = await loginApiV1AuthLoginPost({
body: example.exampleParams
});
break;
case 'register':
response = await registerApiV1AuthRegisterPost({
body: example.exampleParams
});
break;
case 'me':
response = await getCurrentUserApiV1AuthMeGet({});
break;
case 'logout':
response = await logoutApiV1AuthLogoutPost({});
break;
case 'users':
response = await getAllUsersApiV1AuthUsersGet({});
break;
case 'root':
response = await rootGet({});
break;
case 'health':
response = await healthCheckHealthGet({});
break;
default:
throw new Error('Unknown API example');
}
setExamplesResults(prev => ({
...prev,
[example.id]: {
success: !response.error,
data: response.data,
error: response.error,
input: example.exampleParams,
timestamp: new Date().toLocaleTimeString()
}
}));
} catch (error: any) {
setExamplesResults(prev => ({
...prev,
[example.id]: {
success: false,
error: error.message,
input: example.exampleParams,
timestamp: new Date().toLocaleTimeString()
}
}));
} finally {
setExamplesLoading(prev => ({ ...prev, [example.id]: false }));
}
};
// 批量调用所有示例
const callAllExamples = async () => {
// 先调用登录接口获取token
await callExampleApi(apiExamples[0]);
// 然后调用其他接口
for (const example of apiExamples.slice(1)) {
await new Promise(resolve => setTimeout(resolve, 100)); // 间隔100ms
await callExampleApi(example);
}
};
return (
<div className="space-y-6">
<div className="flex justify-between items-center">
<div>
<h2 className="text-2xl font-bold"></h2>
<p className="text-muted-foreground">
OpenAPI规范自动生成的所有接口示例
</p>
</div>
<Button onClick={callAllExamples} disabled={Object.values(examplesLoading).some(v => v)}>
{Object.values(examplesLoading).some(v => v) ? '测试中...' : '批量测试所有接口'}
</Button>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{apiExamples.map((example) => (
<Card key={example.id} className="h-fit">
<CardHeader>
<div className="flex items-center justify-between">
<div>
<CardTitle className="text-base">{example.title}</CardTitle>
<CardDescription className="text-xs">
{example.method} {example.path}
</CardDescription>
</div>
<Badge variant="outline">{example.method}</Badge>
</div>
</CardHeader>
<CardContent className="space-y-4">
<p className="text-sm text-muted-foreground">{example.description}</p>
{/* 示例参数 */}
<div className="space-y-2">
<h4 className="text-sm font-medium">:</h4>
{example.exampleParams ? (
<pre className="text-xs bg-muted p-2 rounded overflow-x-auto">
{JSON.stringify(example.exampleParams, null, 2)}
</pre>
) : (
<p className="text-xs text-muted-foreground italic"></p>
)}
</div>
{/* 预期输出 */}
<div className="space-y-2">
<h4 className="text-sm font-medium">:</h4>
<pre className="text-xs bg-muted p-2 rounded overflow-x-auto">
{JSON.stringify(example.expectedOutput, null, 2)}
</pre>
</div>
{/* 实际结果 */}
{examplesResults[example.id] && (
<div className="space-y-2">
<div className="flex items-center justify-between">
<h4 className="text-sm font-medium">
<span className="ml-2 text-xs text-muted-foreground">
({examplesResults[example.id].timestamp})
</span>
</h4>
<Badge
variant={examplesResults[example.id].success ? "default" : "destructive"}
>
{examplesResults[example.id].success ? '成功' : '失败'}
</Badge>
</div>
<pre className={`text-xs p-2 rounded overflow-x-auto ${
examplesResults[example.id].success ? 'bg-green-50 text-green-800 border-green-200' : 'bg-red-50 text-red-800 border-red-200'
}`}>
{examplesResults[example.id].error
? JSON.stringify(examplesResults[example.id].error, null, 2)
: JSON.stringify(examplesResults[example.id].data, null, 2)
}
</pre>
</div>
)}
<Button
onClick={() => callExampleApi(example)}
disabled={examplesLoading[example.id]}
className="w-full"
variant={examplesResults[example.id]?.success ? "outline" : "default"}
>
{examplesLoading[example.id] ? '测试中...' : '测试此接口'}
</Button>
</CardContent>
</Card>
))}
</div>
{/* 统计信息 */}
<Card>
<CardHeader>
<CardTitle></CardTitle>
</CardHeader>
<CardContent>
<div className="grid grid-cols-3 gap-4 text-center">
<div>
<p className="text-2xl font-bold text-green-600">
{Object.values(examplesResults).filter(r => r?.success).length}
</p>
<p className="text-sm text-muted-foreground"></p>
</div>
<div>
<p className="text-2xl font-bold text-red-600">
{Object.values(examplesResults).filter(r => r?.success === false).length}
</p>
<p className="text-sm text-muted-foreground"></p>
</div>
<div>
<p className="text-2xl font-bold text-blue-600">
{apiExamples.length}
</p>
<p className="text-sm text-muted-foreground"></p>
</div>
</div>
</CardContent>
</Card>
</div>
);
}

View File

@@ -1,231 +0,0 @@
'use client';
import React, { useState, useEffect } from 'react';
import { api, testConnection, type User, type Machinery } from '@/lib/api/client';
export default function ApiExample() {
const [users, setUsers] = useState<User[]>([]);
const [machinery, setMachinery] = useState<Machinery[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [connectionStatus, setConnectionStatus] = useState<'testing' | 'connected' | 'disconnected'>('testing');
// 获取用户列表
const fetchUsers = async () => {
setLoading(true);
setError(null);
try {
const result = await api.users.getList({ page: 1, limit: 10 });
if (result?.data?.users) {
setUsers(result.data.users);
}
} catch (err) {
setError(err instanceof Error ? err.message : '获取用户失败');
} finally {
setLoading(false);
}
};
// 获取农机列表
const fetchMachinery = async () => {
setLoading(true);
setError(null);
try {
const result = await api.machinery.getList({ page: 1, limit: 10 });
if (result?.data?.machinery) {
setMachinery(result.data.machinery);
}
} catch (err) {
setError(err instanceof Error ? err.message : '获取农机失败');
} finally {
setLoading(false);
}
};
// 创建新农机
const createMachinery = async () => {
try {
const newMachinery = await api.machinery.create({
name: '新拖拉机',
type: 'tractor',
model: 'John Deere 6M',
serial_number: 'JD6M123456',
purchase_date: new Date().toISOString().split('T')[0],
});
console.log('创建成功:', newMachinery);
// 刷新列表
fetchMachinery();
} catch (err) {
setError(err instanceof Error ? err.message : '创建农机失败');
}
};
// 测试 API 连接
const testApiConnection = async () => {
setConnectionStatus('testing');
const result = await testConnection();
if (result.success) {
setConnectionStatus('connected');
// 连接成功后获取数据
fetchUsers();
fetchMachinery();
} else {
setConnectionStatus('disconnected');
setError(`API 连接失败: ${result.error}`);
}
};
useEffect(() => {
testApiConnection();
}, []);
if (loading) {
return <div className="p-4">...</div>;
}
if (error) {
return (
<div className="p-4">
<div className="text-red-600">: {error}</div>
<button
onClick={() => {
setError(null);
fetchUsers();
fetchMachinery();
}}
className="mt-2 px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
>
</button>
</div>
);
}
// 连接状态显示
const renderConnectionStatus = () => {
switch (connectionStatus) {
case 'testing':
return (
<div className="mb-4 p-3 bg-blue-50 border border-blue-200 rounded-lg">
<div className="flex items-center">
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600 mr-2"></div>
<span className="text-blue-800"> API ...</span>
</div>
</div>
);
case 'connected':
return (
<div className="mb-4 p-3 bg-green-50 border border-green-200 rounded-lg">
<div className="flex items-center justify-between">
<div className="flex items-center">
<div className="w-3 h-3 bg-green-500 rounded-full mr-2"></div>
<span className="text-green-800">API </span>
</div>
<button
onClick={testApiConnection}
className="px-3 py-1 bg-green-600 text-white text-sm rounded hover:bg-green-700"
>
</button>
</div>
</div>
);
case 'disconnected':
return (
<div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-lg">
<div className="flex items-center justify-between">
<div>
<div className="flex items-center">
<div className="w-3 h-3 bg-red-500 rounded-full mr-2"></div>
<span className="text-red-800">API </span>
</div>
<div className="text-sm text-red-600 mt-1">{error}</div>
</div>
<button
onClick={testApiConnection}
className="px-3 py-1 bg-red-600 text-white text-sm rounded hover:bg-red-700"
>
</button>
</div>
</div>
);
}
};
return (
<div className="p-6">
<h1 className="text-2xl font-bold mb-6">API </h1>
{/* 连接状态 */}
{renderConnectionStatus()}
{/* 服务器信息 */}
<div className="mb-6 p-4 bg-muted rounded-lg">
<h3 className="font-semibold mb-2"></h3>
<div className="text-sm text-muted-foreground space-y-1">
<div><strong>Base URL:</strong> https://gitea-admin-test-app-app.dev.maimaiag.com/api/v1</div>
<div><strong>//:</strong> 使</div>
</div>
</div>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
{/* 用户列表 */}
<div className="bg-card border rounded-lg p-4">
<h2 className="text-xl font-semibold mb-4"></h2>
<div className="space-y-2">
{users.map((user) => (
<div key={user.id} className="p-3 bg-muted rounded">
<div className="font-medium">{user.full_name || user.username}</div>
<div className="text-sm text-muted-foreground">
{user.email} {user.role} {user.status}
</div>
</div>
))}
</div>
</div>
{/* 农机列表 */}
<div className="bg-card border rounded-lg p-4">
<div className="flex justify-between items-center mb-4">
<h2 className="text-xl font-semibold"></h2>
<button
onClick={createMachinery}
className="px-3 py-1 bg-primary text-primary-foreground rounded hover:bg-primary/90"
>
</button>
</div>
<div className="space-y-2">
{machinery.map((machine) => (
<div key={machine.id} className="p-3 bg-muted rounded">
<div className="font-medium">{machine.name}</div>
<div className="text-sm text-muted-foreground">
{machine.type} {machine.model} {machine.status}
</div>
{machine.operator && (
<div className="text-xs text-muted-foreground mt-1">
: {machine.operator.full_name || machine.operator.username}
</div>
)}
</div>
))}
</div>
</div>
</div>
{/* 类型安全示例 */}
<div className="mt-8 p-4 bg-muted rounded-lg">
<h3 className="text-lg font-semibold mb-2"></h3>
<ul className="list-disc list-inside space-y-1 text-sm text-muted-foreground">
<li> API </li>
<li> </li>
<li> </li>
<li> IDE </li>
</ul>
</div>
</div>
);
}

View File

@@ -0,0 +1,18 @@
// This file is auto-generated by @hey-api/openapi-ts
import { type ClientOptions, type Config, createClient, createConfig } from './client';
import type { ClientOptions as ClientOptions2 } from './types.gen';
/**
* The `createClientConfig()` function will be called on client initialization
* and the returned object will become the client's initial configuration.
*
* You may want to initialize your client this way instead of calling
* `setConfig()`. This is useful for example if you're using Next.js
* to ensure your client always has the correct values.
*/
export type CreateClientConfig<T extends ClientOptions = ClientOptions2> = (override?: Config<ClientOptions & T>) => Config<Required<ClientOptions> & T>;
export const client = createClient(createConfig<ClientOptions2>({
baseUrl: 'http://localhost:8080'
}));

View File

@@ -1,204 +0,0 @@
import createClient from 'openapi-fetch';
import type { paths } from './v1.d.ts';
// 创建 API 客户端
const client = createClient<paths>({
baseUrl: 'https://gitea-admin-test-app-app.dev.maimaiag.com/docs',
// 可以添加默认 headers
headers: {
'Content-Type': 'application/json',
},
});
// 添加认证的客户端
export const authClient = {
...client,
// 包装添加 token 的方法
withAuth: (token: string) => ({
...client,
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`,
},
}),
};
// 测试连接
export const testConnection = async () => {
try {
// 尝试获取一个简单的接口来测试连接
const { data, error, response } = await client.GET('/users', {
params: {
query: { page: 1, limit: 1 }
}
});
if (error) {
console.warn('API 连接测试失败:', error);
return { success: false, error };
}
console.log('API 连接测试成功:', { status: response?.status, data });
return { success: true, data };
} catch (err) {
console.error('API 连接测试出错:', err);
return { success: false, error: err instanceof Error ? err.message : '未知错误' };
}
};
// API 方法封装
export const api = {
// 用户管理 API
users: {
// 获取用户列表
getList: async (params?: {
page?: number;
limit?: number;
search?: string;
}) => {
const { data, error, response } = await client.GET('/users', {
params: {
query: params,
},
});
if (error) {
console.error('获取用户列表失败:', error);
throw new Error(`API Error: ${error}`);
}
return data;
},
// 获取用户详情
getDetail: async (id: number) => {
const { data, error } = await client.GET('/users/{id}', {
params: {
path: { id },
},
});
if (error) {
console.error('获取用户详情失败:', error);
throw new Error(`API Error: ${error}`);
}
return data;
},
},
// 农机管理 API
machinery: {
// 获取农机列表
getList: async (params?: {
page?: number;
limit?: number;
status?: 'running' | 'idle' | 'maintenance' | 'error' | 'offline';
}) => {
const { data, error } = await client.GET('/machinery', {
params: {
query: params,
},
});
if (error) {
console.error('获取农机列表失败:', error);
throw new Error(`API Error: ${error}`);
}
return data;
},
// 获取农机详情
getDetail: async (id: number) => {
const { data, error } = await client.GET('/machinery/{id}', {
params: {
path: { id },
},
});
if (error) {
console.error('获取农机详情失败:', error);
throw new Error(`API Error: ${error}`);
}
return data;
},
// 创建农机
create: async (machineryData: {
name: string;
type: 'tractor' | 'harvester' | 'planter' | 'sprayer' | 'irrigation';
model: string;
serial_number?: string;
operator_id?: number;
purchase_date?: string;
}) => {
const { data, error } = await client.POST('/machinery', {
body: machineryData,
});
if (error) {
console.error('创建农机失败:', error);
throw new Error(`API Error: ${error}`);
}
return data;
},
// 更新农机
update: async (
id: number,
updateData: {
name?: string;
status?: 'running' | 'idle' | 'maintenance' | 'error' | 'offline';
operator_id?: number;
last_maintenance?: string;
next_maintenance?: string;
}
) => {
const { data, error } = await client.PUT('/machinery/{id}', {
params: {
path: { id },
},
body: updateData,
});
if (error) {
console.error('更新农机失败:', error);
throw new Error(`API Error: ${error}`);
}
return data;
},
// 删除农机
delete: async (id: number) => {
const { error } = await client.DELETE('/machinery/{id}', {
params: {
path: { id },
},
});
if (error) {
console.error('删除农机失败:', error);
throw new Error(`API Error: ${error}`);
}
return true; // 删除成功
},
},
};
// 类型导出(供组件使用)
export type {
User,
Machinery,
Location,
Coordinates,
CreateMachineryRequest,
UpdateMachineryRequest,
Error as ApiError
} from './v1.d.ts';
export default client;

View File

@@ -0,0 +1,268 @@
// This file is auto-generated by @hey-api/openapi-ts
import { createSseClient } from '../core/serverSentEvents.gen';
import type { HttpMethod } from '../core/types.gen';
import { getValidRequestBody } from '../core/utils.gen';
import type {
Client,
Config,
RequestOptions,
ResolvedRequestOptions,
} from './types.gen';
import {
buildUrl,
createConfig,
createInterceptors,
getParseAs,
mergeConfigs,
mergeHeaders,
setAuthParams,
} from './utils.gen';
type ReqInit = Omit<RequestInit, 'body' | 'headers'> & {
body?: any;
headers: ReturnType<typeof mergeHeaders>;
};
export const createClient = (config: Config = {}): Client => {
let _config = mergeConfigs(createConfig(), config);
const getConfig = (): Config => ({ ..._config });
const setConfig = (config: Config): Config => {
_config = mergeConfigs(_config, config);
return getConfig();
};
const interceptors = createInterceptors<
Request,
Response,
unknown,
ResolvedRequestOptions
>();
const beforeRequest = async (options: RequestOptions) => {
const opts = {
..._config,
...options,
fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
headers: mergeHeaders(_config.headers, options.headers),
serializedBody: undefined,
};
if (opts.security) {
await setAuthParams({
...opts,
security: opts.security,
});
}
if (opts.requestValidator) {
await opts.requestValidator(opts);
}
if (opts.body !== undefined && opts.bodySerializer) {
opts.serializedBody = opts.bodySerializer(opts.body);
}
// remove Content-Type header if body is empty to avoid sending invalid requests
if (opts.body === undefined || opts.serializedBody === '') {
opts.headers.delete('Content-Type');
}
const url = buildUrl(opts);
return { opts, url };
};
const request: Client['request'] = async (options) => {
// @ts-expect-error
const { opts, url } = await beforeRequest(options);
const requestInit: ReqInit = {
redirect: 'follow',
...opts,
body: getValidRequestBody(opts),
};
let request = new Request(url, requestInit);
for (const fn of interceptors.request.fns) {
if (fn) {
request = await fn(request, opts);
}
}
// fetch must be assigned here, otherwise it would throw the error:
// TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation
const _fetch = opts.fetch!;
let response = await _fetch(request);
for (const fn of interceptors.response.fns) {
if (fn) {
response = await fn(response, request, opts);
}
}
const result = {
request,
response,
};
if (response.ok) {
const parseAs =
(opts.parseAs === 'auto'
? getParseAs(response.headers.get('Content-Type'))
: opts.parseAs) ?? 'json';
if (
response.status === 204 ||
response.headers.get('Content-Length') === '0'
) {
let emptyData: any;
switch (parseAs) {
case 'arrayBuffer':
case 'blob':
case 'text':
emptyData = await response[parseAs]();
break;
case 'formData':
emptyData = new FormData();
break;
case 'stream':
emptyData = response.body;
break;
case 'json':
default:
emptyData = {};
break;
}
return opts.responseStyle === 'data'
? emptyData
: {
data: emptyData,
...result,
};
}
let data: any;
switch (parseAs) {
case 'arrayBuffer':
case 'blob':
case 'formData':
case 'json':
case 'text':
data = await response[parseAs]();
break;
case 'stream':
return opts.responseStyle === 'data'
? response.body
: {
data: response.body,
...result,
};
}
if (parseAs === 'json') {
if (opts.responseValidator) {
await opts.responseValidator(data);
}
if (opts.responseTransformer) {
data = await opts.responseTransformer(data);
}
}
return opts.responseStyle === 'data'
? data
: {
data,
...result,
};
}
const textError = await response.text();
let jsonError: unknown;
try {
jsonError = JSON.parse(textError);
} catch {
// noop
}
const error = jsonError ?? textError;
let finalError = error;
for (const fn of interceptors.error.fns) {
if (fn) {
finalError = (await fn(error, response, request, opts)) as string;
}
}
finalError = finalError || ({} as string);
if (opts.throwOnError) {
throw finalError;
}
// TODO: we probably want to return error and improve types
return opts.responseStyle === 'data'
? undefined
: {
error: finalError,
...result,
};
};
const makeMethodFn =
(method: Uppercase<HttpMethod>) => (options: RequestOptions) =>
request({ ...options, method });
const makeSseFn =
(method: Uppercase<HttpMethod>) => async (options: RequestOptions) => {
const { opts, url } = await beforeRequest(options);
return createSseClient({
...opts,
body: opts.body as BodyInit | null | undefined,
headers: opts.headers as unknown as Record<string, string>,
method,
onRequest: async (url, init) => {
let request = new Request(url, init);
for (const fn of interceptors.request.fns) {
if (fn) {
request = await fn(request, opts);
}
}
return request;
},
url,
});
};
return {
buildUrl,
connect: makeMethodFn('CONNECT'),
delete: makeMethodFn('DELETE'),
get: makeMethodFn('GET'),
getConfig,
head: makeMethodFn('HEAD'),
interceptors,
options: makeMethodFn('OPTIONS'),
patch: makeMethodFn('PATCH'),
post: makeMethodFn('POST'),
put: makeMethodFn('PUT'),
request,
setConfig,
sse: {
connect: makeSseFn('CONNECT'),
delete: makeSseFn('DELETE'),
get: makeSseFn('GET'),
head: makeSseFn('HEAD'),
options: makeSseFn('OPTIONS'),
patch: makeSseFn('PATCH'),
post: makeSseFn('POST'),
put: makeSseFn('PUT'),
trace: makeSseFn('TRACE'),
},
trace: makeMethodFn('TRACE'),
} as Client;
};

View File

@@ -0,0 +1,26 @@
// This file is auto-generated by @hey-api/openapi-ts
export type { Auth } from '../core/auth.gen';
export type { QuerySerializerOptions } from '../core/bodySerializer.gen';
export {
formDataBodySerializer,
jsonBodySerializer,
urlSearchParamsBodySerializer,
} from '../core/bodySerializer.gen';
export { buildClientParams } from '../core/params.gen';
export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen';
export { createClient } from './client.gen';
export type {
Client,
ClientOptions,
Config,
CreateClientConfig,
Options,
OptionsLegacyParser,
RequestOptions,
RequestResult,
ResolvedRequestOptions,
ResponseStyle,
TDataShape,
} from './types.gen';
export { createConfig, mergeHeaders } from './utils.gen';

View File

@@ -0,0 +1,268 @@
// This file is auto-generated by @hey-api/openapi-ts
import type { Auth } from '../core/auth.gen';
import type {
ServerSentEventsOptions,
ServerSentEventsResult,
} from '../core/serverSentEvents.gen';
import type {
Client as CoreClient,
Config as CoreConfig,
} from '../core/types.gen';
import type { Middleware } from './utils.gen';
export type ResponseStyle = 'data' | 'fields';
export interface Config<T extends ClientOptions = ClientOptions>
extends Omit<RequestInit, 'body' | 'headers' | 'method'>,
CoreConfig {
/**
* Base URL for all requests made by this client.
*/
baseUrl?: T['baseUrl'];
/**
* Fetch API implementation. You can use this option to provide a custom
* fetch instance.
*
* @default globalThis.fetch
*/
fetch?: typeof fetch;
/**
* Please don't use the Fetch client for Next.js applications. The `next`
* options won't have any effect.
*
* Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead.
*/
next?: never;
/**
* Return the response data parsed in a specified format. By default, `auto`
* will infer the appropriate method from the `Content-Type` response header.
* You can override this behavior with any of the {@link Body} methods.
* Select `stream` if you don't want to parse response data at all.
*
* @default 'auto'
*/
parseAs?:
| 'arrayBuffer'
| 'auto'
| 'blob'
| 'formData'
| 'json'
| 'stream'
| 'text';
/**
* Should we return only data or multiple fields (data, error, response, etc.)?
*
* @default 'fields'
*/
responseStyle?: ResponseStyle;
/**
* Throw an error instead of returning it in the response?
*
* @default false
*/
throwOnError?: T['throwOnError'];
}
export interface RequestOptions<
TData = unknown,
TResponseStyle extends ResponseStyle = 'fields',
ThrowOnError extends boolean = boolean,
Url extends string = string,
> extends Config<{
responseStyle: TResponseStyle;
throwOnError: ThrowOnError;
}>,
Pick<
ServerSentEventsOptions<TData>,
| 'onSseError'
| 'onSseEvent'
| 'sseDefaultRetryDelay'
| 'sseMaxRetryAttempts'
| 'sseMaxRetryDelay'
> {
/**
* Any body that you want to add to your request.
*
* {@link https://developer.mozilla.org/docs/Web/API/fetch#body}
*/
body?: unknown;
path?: Record<string, unknown>;
query?: Record<string, unknown>;
/**
* Security mechanism(s) to use for the request.
*/
security?: ReadonlyArray<Auth>;
url: Url;
}
export interface ResolvedRequestOptions<
TResponseStyle extends ResponseStyle = 'fields',
ThrowOnError extends boolean = boolean,
Url extends string = string,
> extends RequestOptions<unknown, TResponseStyle, ThrowOnError, Url> {
serializedBody?: string;
}
export type RequestResult<
TData = unknown,
TError = unknown,
ThrowOnError extends boolean = boolean,
TResponseStyle extends ResponseStyle = 'fields',
> = ThrowOnError extends true
? Promise<
TResponseStyle extends 'data'
? TData extends Record<string, unknown>
? TData[keyof TData]
: TData
: {
data: TData extends Record<string, unknown>
? TData[keyof TData]
: TData;
request: Request;
response: Response;
}
>
: Promise<
TResponseStyle extends 'data'
?
| (TData extends Record<string, unknown>
? TData[keyof TData]
: TData)
| undefined
: (
| {
data: TData extends Record<string, unknown>
? TData[keyof TData]
: TData;
error: undefined;
}
| {
data: undefined;
error: TError extends Record<string, unknown>
? TError[keyof TError]
: TError;
}
) & {
request: Request;
response: Response;
}
>;
export interface ClientOptions {
baseUrl?: string;
responseStyle?: ResponseStyle;
throwOnError?: boolean;
}
type MethodFn = <
TData = unknown,
TError = unknown,
ThrowOnError extends boolean = false,
TResponseStyle extends ResponseStyle = 'fields',
>(
options: Omit<RequestOptions<TData, TResponseStyle, ThrowOnError>, 'method'>,
) => RequestResult<TData, TError, ThrowOnError, TResponseStyle>;
type SseFn = <
TData = unknown,
TError = unknown,
ThrowOnError extends boolean = false,
TResponseStyle extends ResponseStyle = 'fields',
>(
options: Omit<RequestOptions<TData, TResponseStyle, ThrowOnError>, 'method'>,
) => Promise<ServerSentEventsResult<TData, TError>>;
type RequestFn = <
TData = unknown,
TError = unknown,
ThrowOnError extends boolean = false,
TResponseStyle extends ResponseStyle = 'fields',
>(
options: Omit<RequestOptions<TData, TResponseStyle, ThrowOnError>, 'method'> &
Pick<
Required<RequestOptions<TData, TResponseStyle, ThrowOnError>>,
'method'
>,
) => RequestResult<TData, TError, ThrowOnError, TResponseStyle>;
type BuildUrlFn = <
TData extends {
body?: unknown;
path?: Record<string, unknown>;
query?: Record<string, unknown>;
url: string;
},
>(
options: Pick<TData, 'url'> & Options<TData>,
) => string;
export type Client = CoreClient<
RequestFn,
Config,
MethodFn,
BuildUrlFn,
SseFn
> & {
interceptors: Middleware<Request, Response, unknown, ResolvedRequestOptions>;
};
/**
* The `createClientConfig()` function will be called on client initialization
* and the returned object will become the client's initial configuration.
*
* You may want to initialize your client this way instead of calling
* `setConfig()`. This is useful for example if you're using Next.js
* to ensure your client always has the correct values.
*/
export type CreateClientConfig<T extends ClientOptions = ClientOptions> = (
override?: Config<ClientOptions & T>,
) => Config<Required<ClientOptions> & T>;
export interface TDataShape {
body?: unknown;
headers?: unknown;
path?: unknown;
query?: unknown;
url: string;
}
type OmitKeys<T, K> = Pick<T, Exclude<keyof T, K>>;
export type Options<
TData extends TDataShape = TDataShape,
ThrowOnError extends boolean = boolean,
TResponse = unknown,
TResponseStyle extends ResponseStyle = 'fields',
> = OmitKeys<
RequestOptions<TResponse, TResponseStyle, ThrowOnError>,
'body' | 'path' | 'query' | 'url'
> &
Omit<TData, 'url'>;
export type OptionsLegacyParser<
TData = unknown,
ThrowOnError extends boolean = boolean,
TResponseStyle extends ResponseStyle = 'fields',
> = TData extends { body?: any }
? TData extends { headers?: any }
? OmitKeys<
RequestOptions<unknown, TResponseStyle, ThrowOnError>,
'body' | 'headers' | 'url'
> &
TData
: OmitKeys<
RequestOptions<unknown, TResponseStyle, ThrowOnError>,
'body' | 'url'
> &
TData &
Pick<RequestOptions<unknown, TResponseStyle, ThrowOnError>, 'headers'>
: TData extends { headers?: any }
? OmitKeys<
RequestOptions<unknown, TResponseStyle, ThrowOnError>,
'headers' | 'url'
> &
TData &
Pick<RequestOptions<unknown, TResponseStyle, ThrowOnError>, 'body'>
: OmitKeys<RequestOptions<unknown, TResponseStyle, ThrowOnError>, 'url'> &
TData;

View File

@@ -0,0 +1,332 @@
// This file is auto-generated by @hey-api/openapi-ts
import { getAuthToken } from '../core/auth.gen';
import type { QuerySerializerOptions } from '../core/bodySerializer.gen';
import { jsonBodySerializer } from '../core/bodySerializer.gen';
import {
serializeArrayParam,
serializeObjectParam,
serializePrimitiveParam,
} from '../core/pathSerializer.gen';
import { getUrl } from '../core/utils.gen';
import type { Client, ClientOptions, Config, RequestOptions } from './types.gen';
export const createQuerySerializer = <T = unknown>({
parameters = {},
...args
}: QuerySerializerOptions = {}) => {
const querySerializer = (queryParams: T) => {
const search: string[] = [];
if (queryParams && typeof queryParams === 'object') {
for (const name in queryParams) {
const value = queryParams[name];
if (value === undefined || value === null) {
continue;
}
const options = parameters[name] || args;
if (Array.isArray(value)) {
const serializedArray = serializeArrayParam({
allowReserved: options.allowReserved,
explode: true,
name,
style: 'form',
value,
...options.array,
});
if (serializedArray) search.push(serializedArray);
} else if (typeof value === 'object') {
const serializedObject = serializeObjectParam({
allowReserved: options.allowReserved,
explode: true,
name,
style: 'deepObject',
value: value as Record<string, unknown>,
...options.object,
});
if (serializedObject) search.push(serializedObject);
} else {
const serializedPrimitive = serializePrimitiveParam({
allowReserved: options.allowReserved,
name,
value: value as string,
});
if (serializedPrimitive) search.push(serializedPrimitive);
}
}
}
return search.join('&');
};
return querySerializer;
};
/**
* Infers parseAs value from provided Content-Type header.
*/
export const getParseAs = (
contentType: string | null,
): Exclude<Config['parseAs'], 'auto'> => {
if (!contentType) {
// If no Content-Type header is provided, the best we can do is return the raw response body,
// which is effectively the same as the 'stream' option.
return 'stream';
}
const cleanContent = contentType.split(';')[0]?.trim();
if (!cleanContent) {
return;
}
if (
cleanContent.startsWith('application/json') ||
cleanContent.endsWith('+json')
) {
return 'json';
}
if (cleanContent === 'multipart/form-data') {
return 'formData';
}
if (
['application/', 'audio/', 'image/', 'video/'].some((type) =>
cleanContent.startsWith(type),
)
) {
return 'blob';
}
if (cleanContent.startsWith('text/')) {
return 'text';
}
return;
};
const checkForExistence = (
options: Pick<RequestOptions, 'auth' | 'query'> & {
headers: Headers;
},
name?: string,
): boolean => {
if (!name) {
return false;
}
if (
options.headers.has(name) ||
options.query?.[name] ||
options.headers.get('Cookie')?.includes(`${name}=`)
) {
return true;
}
return false;
};
export const setAuthParams = async ({
security,
...options
}: Pick<Required<RequestOptions>, 'security'> &
Pick<RequestOptions, 'auth' | 'query'> & {
headers: Headers;
}) => {
for (const auth of security) {
if (checkForExistence(options, auth.name)) {
continue;
}
const token = await getAuthToken(auth, options.auth);
if (!token) {
continue;
}
const name = auth.name ?? 'Authorization';
switch (auth.in) {
case 'query':
if (!options.query) {
options.query = {};
}
options.query[name] = token;
break;
case 'cookie':
options.headers.append('Cookie', `${name}=${token}`);
break;
case 'header':
default:
options.headers.set(name, token);
break;
}
}
};
export const buildUrl: Client['buildUrl'] = (options) =>
getUrl({
baseUrl: options.baseUrl as string,
path: options.path,
query: options.query,
querySerializer:
typeof options.querySerializer === 'function'
? options.querySerializer
: createQuerySerializer(options.querySerializer),
url: options.url,
});
export const mergeConfigs = (a: Config, b: Config): Config => {
const config = { ...a, ...b };
if (config.baseUrl?.endsWith('/')) {
config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
}
config.headers = mergeHeaders(a.headers, b.headers);
return config;
};
const headersEntries = (headers: Headers): Array<[string, string]> => {
const entries: Array<[string, string]> = [];
headers.forEach((value, key) => {
entries.push([key, value]);
});
return entries;
};
export const mergeHeaders = (
...headers: Array<Required<Config>['headers'] | undefined>
): Headers => {
const mergedHeaders = new Headers();
for (const header of headers) {
if (!header) {
continue;
}
const iterator =
header instanceof Headers
? headersEntries(header)
: Object.entries(header);
for (const [key, value] of iterator) {
if (value === null) {
mergedHeaders.delete(key);
} else if (Array.isArray(value)) {
for (const v of value) {
mergedHeaders.append(key, v as string);
}
} else if (value !== undefined) {
// assume object headers are meant to be JSON stringified, i.e. their
// content value in OpenAPI specification is 'application/json'
mergedHeaders.set(
key,
typeof value === 'object' ? JSON.stringify(value) : (value as string),
);
}
}
}
return mergedHeaders;
};
type ErrInterceptor<Err, Res, Req, Options> = (
error: Err,
response: Res,
request: Req,
options: Options,
) => Err | Promise<Err>;
type ReqInterceptor<Req, Options> = (
request: Req,
options: Options,
) => Req | Promise<Req>;
type ResInterceptor<Res, Req, Options> = (
response: Res,
request: Req,
options: Options,
) => Res | Promise<Res>;
class Interceptors<Interceptor> {
fns: Array<Interceptor | null> = [];
clear(): void {
this.fns = [];
}
eject(id: number | Interceptor): void {
const index = this.getInterceptorIndex(id);
if (this.fns[index]) {
this.fns[index] = null;
}
}
exists(id: number | Interceptor): boolean {
const index = this.getInterceptorIndex(id);
return Boolean(this.fns[index]);
}
getInterceptorIndex(id: number | Interceptor): number {
if (typeof id === 'number') {
return this.fns[id] ? id : -1;
}
return this.fns.indexOf(id);
}
update(
id: number | Interceptor,
fn: Interceptor,
): number | Interceptor | false {
const index = this.getInterceptorIndex(id);
if (this.fns[index]) {
this.fns[index] = fn;
return id;
}
return false;
}
use(fn: Interceptor): number {
this.fns.push(fn);
return this.fns.length - 1;
}
}
export interface Middleware<Req, Res, Err, Options> {
error: Interceptors<ErrInterceptor<Err, Res, Req, Options>>;
request: Interceptors<ReqInterceptor<Req, Options>>;
response: Interceptors<ResInterceptor<Res, Req, Options>>;
}
export const createInterceptors = <Req, Res, Err, Options>(): Middleware<
Req,
Res,
Err,
Options
> => ({
error: new Interceptors<ErrInterceptor<Err, Res, Req, Options>>(),
request: new Interceptors<ReqInterceptor<Req, Options>>(),
response: new Interceptors<ResInterceptor<Res, Req, Options>>(),
});
const defaultQuerySerializer = createQuerySerializer({
allowReserved: false,
array: {
explode: true,
style: 'form',
},
object: {
explode: true,
style: 'deepObject',
},
});
const defaultHeaders = {
'Content-Type': 'application/json',
};
export const createConfig = <T extends ClientOptions = ClientOptions>(
override: Config<Omit<ClientOptions, keyof T> & T> = {},
): Config<Omit<ClientOptions, keyof T> & T> => ({
...jsonBodySerializer,
headers: defaultHeaders,
parseAs: 'auto',
querySerializer: defaultQuerySerializer,
...override,
});

View File

@@ -0,0 +1,42 @@
// This file is auto-generated by @hey-api/openapi-ts
export type AuthToken = string | undefined;
export interface Auth {
/**
* Which part of the request do we use to send the auth?
*
* @default 'header'
*/
in?: 'header' | 'query' | 'cookie';
/**
* Header or query parameter name.
*
* @default 'Authorization'
*/
name?: string;
scheme?: 'basic' | 'bearer';
type: 'apiKey' | 'http';
}
export const getAuthToken = async (
auth: Auth,
callback: ((auth: Auth) => Promise<AuthToken> | AuthToken) | AuthToken,
): Promise<string | undefined> => {
const token =
typeof callback === 'function' ? await callback(auth) : callback;
if (!token) {
return;
}
if (auth.scheme === 'bearer') {
return `Bearer ${token}`;
}
if (auth.scheme === 'basic') {
return `Basic ${btoa(token)}`;
}
return token;
};

View File

@@ -0,0 +1,100 @@
// This file is auto-generated by @hey-api/openapi-ts
import type {
ArrayStyle,
ObjectStyle,
SerializerOptions,
} from './pathSerializer.gen';
export type QuerySerializer = (query: Record<string, unknown>) => string;
export type BodySerializer = (body: any) => any;
type QuerySerializerOptionsObject = {
allowReserved?: boolean;
array?: Partial<SerializerOptions<ArrayStyle>>;
object?: Partial<SerializerOptions<ObjectStyle>>;
};
export type QuerySerializerOptions = QuerySerializerOptionsObject & {
/**
* Per-parameter serialization overrides. When provided, these settings
* override the global array/object settings for specific parameter names.
*/
parameters?: Record<string, QuerySerializerOptionsObject>;
};
const serializeFormDataPair = (
data: FormData,
key: string,
value: unknown,
): void => {
if (typeof value === 'string' || value instanceof Blob) {
data.append(key, value);
} else if (value instanceof Date) {
data.append(key, value.toISOString());
} else {
data.append(key, JSON.stringify(value));
}
};
const serializeUrlSearchParamsPair = (
data: URLSearchParams,
key: string,
value: unknown,
): void => {
if (typeof value === 'string') {
data.append(key, value);
} else {
data.append(key, JSON.stringify(value));
}
};
export const formDataBodySerializer = {
bodySerializer: <T extends Record<string, any> | Array<Record<string, any>>>(
body: T,
): FormData => {
const data = new FormData();
Object.entries(body).forEach(([key, value]) => {
if (value === undefined || value === null) {
return;
}
if (Array.isArray(value)) {
value.forEach((v) => serializeFormDataPair(data, key, v));
} else {
serializeFormDataPair(data, key, value);
}
});
return data;
},
};
export const jsonBodySerializer = {
bodySerializer: <T>(body: T): string =>
JSON.stringify(body, (_key, value) =>
typeof value === 'bigint' ? value.toString() : value,
),
};
export const urlSearchParamsBodySerializer = {
bodySerializer: <T extends Record<string, any> | Array<Record<string, any>>>(
body: T,
): string => {
const data = new URLSearchParams();
Object.entries(body).forEach(([key, value]) => {
if (value === undefined || value === null) {
return;
}
if (Array.isArray(value)) {
value.forEach((v) => serializeUrlSearchParamsPair(data, key, v));
} else {
serializeUrlSearchParamsPair(data, key, value);
}
});
return data.toString();
},
};

View File

@@ -0,0 +1,153 @@
// This file is auto-generated by @hey-api/openapi-ts
type Slot = 'body' | 'headers' | 'path' | 'query';
export type Field =
| {
in: Exclude<Slot, 'body'>;
/**
* Field name. This is the name we want the user to see and use.
*/
key: string;
/**
* Field mapped name. This is the name we want to use in the request.
* If omitted, we use the same value as `key`.
*/
map?: string;
}
| {
in: Extract<Slot, 'body'>;
/**
* Key isn't required for bodies.
*/
key?: string;
map?: string;
};
export interface Fields {
allowExtra?: Partial<Record<Slot, boolean>>;
args?: ReadonlyArray<Field>;
}
export type FieldsConfig = ReadonlyArray<Field | Fields>;
const extraPrefixesMap: Record<string, Slot> = {
$body_: 'body',
$headers_: 'headers',
$path_: 'path',
$query_: 'query',
};
const extraPrefixes = Object.entries(extraPrefixesMap);
type KeyMap = Map<
string,
{
in: Slot;
map?: string;
}
>;
const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => {
if (!map) {
map = new Map();
}
for (const config of fields) {
if ('in' in config) {
if (config.key) {
map.set(config.key, {
in: config.in,
map: config.map,
});
}
} else if (config.args) {
buildKeyMap(config.args, map);
}
}
return map;
};
interface Params {
body: unknown;
headers: Record<string, unknown>;
path: Record<string, unknown>;
query: Record<string, unknown>;
}
const stripEmptySlots = (params: Params) => {
for (const [slot, value] of Object.entries(params)) {
if (value && typeof value === 'object' && !Object.keys(value).length) {
delete params[slot as Slot];
}
}
};
export const buildClientParams = (
args: ReadonlyArray<unknown>,
fields: FieldsConfig,
) => {
const params: Params = {
body: {},
headers: {},
path: {},
query: {},
};
const map = buildKeyMap(fields);
let config: FieldsConfig[number] | undefined;
for (const [index, arg] of args.entries()) {
if (fields[index]) {
config = fields[index];
}
if (!config) {
continue;
}
if ('in' in config) {
if (config.key) {
const field = map.get(config.key)!;
const name = field.map || config.key;
(params[field.in] as Record<string, unknown>)[name] = arg;
} else {
params.body = arg;
}
} else {
for (const [key, value] of Object.entries(arg ?? {})) {
const field = map.get(key);
if (field) {
const name = field.map || key;
(params[field.in] as Record<string, unknown>)[name] = value;
} else {
const extra = extraPrefixes.find(([prefix]) =>
key.startsWith(prefix),
);
if (extra) {
const [prefix, slot] = extra;
(params[slot] as Record<string, unknown>)[
key.slice(prefix.length)
] = value;
} else {
for (const [slot, allowed] of Object.entries(
config.allowExtra ?? {},
)) {
if (allowed) {
(params[slot as Slot] as Record<string, unknown>)[key] = value;
break;
}
}
}
}
}
}
}
stripEmptySlots(params);
return params;
};

View File

@@ -0,0 +1,181 @@
// This file is auto-generated by @hey-api/openapi-ts
interface SerializeOptions<T>
extends SerializePrimitiveOptions,
SerializerOptions<T> {}
interface SerializePrimitiveOptions {
allowReserved?: boolean;
name: string;
}
export interface SerializerOptions<T> {
/**
* @default true
*/
explode: boolean;
style: T;
}
export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited';
export type ArraySeparatorStyle = ArrayStyle | MatrixStyle;
type MatrixStyle = 'label' | 'matrix' | 'simple';
export type ObjectStyle = 'form' | 'deepObject';
type ObjectSeparatorStyle = ObjectStyle | MatrixStyle;
interface SerializePrimitiveParam extends SerializePrimitiveOptions {
value: string;
}
export const separatorArrayExplode = (style: ArraySeparatorStyle) => {
switch (style) {
case 'label':
return '.';
case 'matrix':
return ';';
case 'simple':
return ',';
default:
return '&';
}
};
export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => {
switch (style) {
case 'form':
return ',';
case 'pipeDelimited':
return '|';
case 'spaceDelimited':
return '%20';
default:
return ',';
}
};
export const separatorObjectExplode = (style: ObjectSeparatorStyle) => {
switch (style) {
case 'label':
return '.';
case 'matrix':
return ';';
case 'simple':
return ',';
default:
return '&';
}
};
export const serializeArrayParam = ({
allowReserved,
explode,
name,
style,
value,
}: SerializeOptions<ArraySeparatorStyle> & {
value: unknown[];
}) => {
if (!explode) {
const joinedValues = (
allowReserved ? value : value.map((v) => encodeURIComponent(v as string))
).join(separatorArrayNoExplode(style));
switch (style) {
case 'label':
return `.${joinedValues}`;
case 'matrix':
return `;${name}=${joinedValues}`;
case 'simple':
return joinedValues;
default:
return `${name}=${joinedValues}`;
}
}
const separator = separatorArrayExplode(style);
const joinedValues = value
.map((v) => {
if (style === 'label' || style === 'simple') {
return allowReserved ? v : encodeURIComponent(v as string);
}
return serializePrimitiveParam({
allowReserved,
name,
value: v as string,
});
})
.join(separator);
return style === 'label' || style === 'matrix'
? separator + joinedValues
: joinedValues;
};
export const serializePrimitiveParam = ({
allowReserved,
name,
value,
}: SerializePrimitiveParam) => {
if (value === undefined || value === null) {
return '';
}
if (typeof value === 'object') {
throw new Error(
'Deeply-nested arrays/objects arent supported. Provide your own `querySerializer()` to handle these.',
);
}
return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
};
export const serializeObjectParam = ({
allowReserved,
explode,
name,
style,
value,
valueOnly,
}: SerializeOptions<ObjectSeparatorStyle> & {
value: Record<string, unknown> | Date;
valueOnly?: boolean;
}) => {
if (value instanceof Date) {
return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
}
if (style !== 'deepObject' && !explode) {
let values: string[] = [];
Object.entries(value).forEach(([key, v]) => {
values = [
...values,
key,
allowReserved ? (v as string) : encodeURIComponent(v as string),
];
});
const joinedValues = values.join(',');
switch (style) {
case 'form':
return `${name}=${joinedValues}`;
case 'label':
return `.${joinedValues}`;
case 'matrix':
return `;${name}=${joinedValues}`;
default:
return joinedValues;
}
}
const separator = separatorObjectExplode(style);
const joinedValues = Object.entries(value)
.map(([key, v]) =>
serializePrimitiveParam({
allowReserved,
name: style === 'deepObject' ? `${name}[${key}]` : key,
value: v as string,
}),
)
.join(separator);
return style === 'label' || style === 'matrix'
? separator + joinedValues
: joinedValues;
};

View File

@@ -0,0 +1,136 @@
// This file is auto-generated by @hey-api/openapi-ts
/**
* JSON-friendly union that mirrors what Pinia Colada can hash.
*/
export type JsonValue =
| null
| string
| number
| boolean
| JsonValue[]
| { [key: string]: JsonValue };
/**
* Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes.
*/
export const queryKeyJsonReplacer = (_key: string, value: unknown) => {
if (
value === undefined ||
typeof value === 'function' ||
typeof value === 'symbol'
) {
return undefined;
}
if (typeof value === 'bigint') {
return value.toString();
}
if (value instanceof Date) {
return value.toISOString();
}
return value;
};
/**
* Safely stringifies a value and parses it back into a JsonValue.
*/
export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => {
try {
const json = JSON.stringify(input, queryKeyJsonReplacer);
if (json === undefined) {
return undefined;
}
return JSON.parse(json) as JsonValue;
} catch {
return undefined;
}
};
/**
* Detects plain objects (including objects with a null prototype).
*/
const isPlainObject = (value: unknown): value is Record<string, unknown> => {
if (value === null || typeof value !== 'object') {
return false;
}
const prototype = Object.getPrototypeOf(value as object);
return prototype === Object.prototype || prototype === null;
};
/**
* Turns URLSearchParams into a sorted JSON object for deterministic keys.
*/
const serializeSearchParams = (params: URLSearchParams): JsonValue => {
const entries = Array.from(params.entries()).sort(([a], [b]) =>
a.localeCompare(b),
);
const result: Record<string, JsonValue> = {};
for (const [key, value] of entries) {
const existing = result[key];
if (existing === undefined) {
result[key] = value;
continue;
}
if (Array.isArray(existing)) {
(existing as string[]).push(value);
} else {
result[key] = [existing, value];
}
}
return result;
};
/**
* Normalizes any accepted value into a JSON-friendly shape for query keys.
*/
export const serializeQueryKeyValue = (
value: unknown,
): JsonValue | undefined => {
if (value === null) {
return null;
}
if (
typeof value === 'string' ||
typeof value === 'number' ||
typeof value === 'boolean'
) {
return value;
}
if (
value === undefined ||
typeof value === 'function' ||
typeof value === 'symbol'
) {
return undefined;
}
if (typeof value === 'bigint') {
return value.toString();
}
if (value instanceof Date) {
return value.toISOString();
}
if (Array.isArray(value)) {
return stringifyToJsonValue(value);
}
if (
typeof URLSearchParams !== 'undefined' &&
value instanceof URLSearchParams
) {
return serializeSearchParams(value);
}
if (isPlainObject(value)) {
return stringifyToJsonValue(value);
}
return undefined;
};

View File

@@ -0,0 +1,264 @@
// This file is auto-generated by @hey-api/openapi-ts
import type { Config } from './types.gen';
export type ServerSentEventsOptions<TData = unknown> = Omit<
RequestInit,
'method'
> &
Pick<Config, 'method' | 'responseTransformer' | 'responseValidator'> & {
/**
* Fetch API implementation. You can use this option to provide a custom
* fetch instance.
*
* @default globalThis.fetch
*/
fetch?: typeof fetch;
/**
* Implementing clients can call request interceptors inside this hook.
*/
onRequest?: (url: string, init: RequestInit) => Promise<Request>;
/**
* Callback invoked when a network or parsing error occurs during streaming.
*
* This option applies only if the endpoint returns a stream of events.
*
* @param error The error that occurred.
*/
onSseError?: (error: unknown) => void;
/**
* Callback invoked when an event is streamed from the server.
*
* This option applies only if the endpoint returns a stream of events.
*
* @param event Event streamed from the server.
* @returns Nothing (void).
*/
onSseEvent?: (event: StreamEvent<TData>) => void;
serializedBody?: RequestInit['body'];
/**
* Default retry delay in milliseconds.
*
* This option applies only if the endpoint returns a stream of events.
*
* @default 3000
*/
sseDefaultRetryDelay?: number;
/**
* Maximum number of retry attempts before giving up.
*/
sseMaxRetryAttempts?: number;
/**
* Maximum retry delay in milliseconds.
*
* Applies only when exponential backoff is used.
*
* This option applies only if the endpoint returns a stream of events.
*
* @default 30000
*/
sseMaxRetryDelay?: number;
/**
* Optional sleep function for retry backoff.
*
* Defaults to using `setTimeout`.
*/
sseSleepFn?: (ms: number) => Promise<void>;
url: string;
};
export interface StreamEvent<TData = unknown> {
data: TData;
event?: string;
id?: string;
retry?: number;
}
export type ServerSentEventsResult<
TData = unknown,
TReturn = void,
TNext = unknown,
> = {
stream: AsyncGenerator<
TData extends Record<string, unknown> ? TData[keyof TData] : TData,
TReturn,
TNext
>;
};
export const createSseClient = <TData = unknown>({
onRequest,
onSseError,
onSseEvent,
responseTransformer,
responseValidator,
sseDefaultRetryDelay,
sseMaxRetryAttempts,
sseMaxRetryDelay,
sseSleepFn,
url,
...options
}: ServerSentEventsOptions): ServerSentEventsResult<TData> => {
let lastEventId: string | undefined;
const sleep =
sseSleepFn ??
((ms: number) => new Promise((resolve) => setTimeout(resolve, ms)));
const createStream = async function* () {
let retryDelay: number = sseDefaultRetryDelay ?? 3000;
let attempt = 0;
const signal = options.signal ?? new AbortController().signal;
while (true) {
if (signal.aborted) break;
attempt++;
const headers =
options.headers instanceof Headers
? options.headers
: new Headers(options.headers as Record<string, string> | undefined);
if (lastEventId !== undefined) {
headers.set('Last-Event-ID', lastEventId);
}
try {
const requestInit: RequestInit = {
redirect: 'follow',
...options,
body: options.serializedBody,
headers,
signal,
};
let request = new Request(url, requestInit);
if (onRequest) {
request = await onRequest(url, requestInit);
}
// fetch must be assigned here, otherwise it would throw the error:
// TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation
const _fetch = options.fetch ?? globalThis.fetch;
const response = await _fetch(request);
if (!response.ok)
throw new Error(
`SSE failed: ${response.status} ${response.statusText}`,
);
if (!response.body) throw new Error('No body in SSE response');
const reader = response.body
.pipeThrough(new TextDecoderStream())
.getReader();
let buffer = '';
const abortHandler = () => {
try {
reader.cancel();
} catch {
// noop
}
};
signal.addEventListener('abort', abortHandler);
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += value;
const chunks = buffer.split('\n\n');
buffer = chunks.pop() ?? '';
for (const chunk of chunks) {
const lines = chunk.split('\n');
const dataLines: Array<string> = [];
let eventName: string | undefined;
for (const line of lines) {
if (line.startsWith('data:')) {
dataLines.push(line.replace(/^data:\s*/, ''));
} else if (line.startsWith('event:')) {
eventName = line.replace(/^event:\s*/, '');
} else if (line.startsWith('id:')) {
lastEventId = line.replace(/^id:\s*/, '');
} else if (line.startsWith('retry:')) {
const parsed = Number.parseInt(
line.replace(/^retry:\s*/, ''),
10,
);
if (!Number.isNaN(parsed)) {
retryDelay = parsed;
}
}
}
let data: unknown;
let parsedJson = false;
if (dataLines.length) {
const rawData = dataLines.join('\n');
try {
data = JSON.parse(rawData);
parsedJson = true;
} catch {
data = rawData;
}
}
if (parsedJson) {
if (responseValidator) {
await responseValidator(data);
}
if (responseTransformer) {
data = await responseTransformer(data);
}
}
onSseEvent?.({
data,
event: eventName,
id: lastEventId,
retry: retryDelay,
});
if (dataLines.length) {
yield data as any;
}
}
}
} finally {
signal.removeEventListener('abort', abortHandler);
reader.releaseLock();
}
break; // exit loop on normal completion
} catch (error) {
// connection failed or aborted; retry after delay
onSseError?.(error);
if (
sseMaxRetryAttempts !== undefined &&
attempt >= sseMaxRetryAttempts
) {
break; // stop after firing error
}
// exponential backoff: double retry each attempt, cap at 30s
const backoff = Math.min(
retryDelay * 2 ** (attempt - 1),
sseMaxRetryDelay ?? 30000,
);
await sleep(backoff);
}
}
};
const stream = createStream();
return { stream };
};

View File

@@ -0,0 +1,118 @@
// This file is auto-generated by @hey-api/openapi-ts
import type { Auth, AuthToken } from './auth.gen';
import type {
BodySerializer,
QuerySerializer,
QuerySerializerOptions,
} from './bodySerializer.gen';
export type HttpMethod =
| 'connect'
| 'delete'
| 'get'
| 'head'
| 'options'
| 'patch'
| 'post'
| 'put'
| 'trace';
export type Client<
RequestFn = never,
Config = unknown,
MethodFn = never,
BuildUrlFn = never,
SseFn = never,
> = {
/**
* Returns the final request URL.
*/
buildUrl: BuildUrlFn;
getConfig: () => Config;
request: RequestFn;
setConfig: (config: Config) => Config;
} & {
[K in HttpMethod]: MethodFn;
} & ([SseFn] extends [never]
? { sse?: never }
: { sse: { [K in HttpMethod]: SseFn } });
export interface Config {
/**
* Auth token or a function returning auth token. The resolved value will be
* added to the request payload as defined by its `security` array.
*/
auth?: ((auth: Auth) => Promise<AuthToken> | AuthToken) | AuthToken;
/**
* A function for serializing request body parameter. By default,
* {@link JSON.stringify()} will be used.
*/
bodySerializer?: BodySerializer | null;
/**
* An object containing any HTTP headers that you want to pre-populate your
* `Headers` object with.
*
* {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more}
*/
headers?:
| RequestInit['headers']
| Record<
string,
| string
| number
| boolean
| (string | number | boolean)[]
| null
| undefined
| unknown
>;
/**
* The request method.
*
* {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more}
*/
method?: Uppercase<HttpMethod>;
/**
* A function for serializing request query parameters. By default, arrays
* will be exploded in form style, objects will be exploded in deepObject
* style, and reserved characters are percent-encoded.
*
* This method will have no effect if the native `paramsSerializer()` Axios
* API function is used.
*
* {@link https://swagger.io/docs/specification/serialization/#query View examples}
*/
querySerializer?: QuerySerializer | QuerySerializerOptions;
/**
* A function validating request data. This is useful if you want to ensure
* the request conforms to the desired shape, so it can be safely sent to
* the server.
*/
requestValidator?: (data: unknown) => Promise<unknown>;
/**
* A function transforming response data before it's returned. This is useful
* for post-processing data, e.g. converting ISO strings into Date objects.
*/
responseTransformer?: (data: unknown) => Promise<unknown>;
/**
* A function validating response data. This is useful if you want to ensure
* the response conforms to the desired shape, so it can be safely passed to
* the transformers and returned to the user.
*/
responseValidator?: (data: unknown) => Promise<unknown>;
}
type IsExactlyNeverOrNeverUndefined<T> = [T] extends [never]
? true
: [T] extends [never | undefined]
? [undefined] extends [T]
? false
: true
: false;
export type OmitNever<T extends Record<string, unknown>> = {
[K in keyof T as IsExactlyNeverOrNeverUndefined<T[K]> extends true
? never
: K]: T[K];
};

View File

@@ -0,0 +1,143 @@
// This file is auto-generated by @hey-api/openapi-ts
import type { BodySerializer, QuerySerializer } from './bodySerializer.gen';
import {
type ArraySeparatorStyle,
serializeArrayParam,
serializeObjectParam,
serializePrimitiveParam,
} from './pathSerializer.gen';
export interface PathSerializer {
path: Record<string, unknown>;
url: string;
}
export const PATH_PARAM_RE = /\{[^{}]+\}/g;
export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => {
let url = _url;
const matches = _url.match(PATH_PARAM_RE);
if (matches) {
for (const match of matches) {
let explode = false;
let name = match.substring(1, match.length - 1);
let style: ArraySeparatorStyle = 'simple';
if (name.endsWith('*')) {
explode = true;
name = name.substring(0, name.length - 1);
}
if (name.startsWith('.')) {
name = name.substring(1);
style = 'label';
} else if (name.startsWith(';')) {
name = name.substring(1);
style = 'matrix';
}
const value = path[name];
if (value === undefined || value === null) {
continue;
}
if (Array.isArray(value)) {
url = url.replace(
match,
serializeArrayParam({ explode, name, style, value }),
);
continue;
}
if (typeof value === 'object') {
url = url.replace(
match,
serializeObjectParam({
explode,
name,
style,
value: value as Record<string, unknown>,
valueOnly: true,
}),
);
continue;
}
if (style === 'matrix') {
url = url.replace(
match,
`;${serializePrimitiveParam({
name,
value: value as string,
})}`,
);
continue;
}
const replaceValue = encodeURIComponent(
style === 'label' ? `.${value as string}` : (value as string),
);
url = url.replace(match, replaceValue);
}
}
return url;
};
export const getUrl = ({
baseUrl,
path,
query,
querySerializer,
url: _url,
}: {
baseUrl?: string;
path?: Record<string, unknown>;
query?: Record<string, unknown>;
querySerializer: QuerySerializer;
url: string;
}) => {
const pathUrl = _url.startsWith('/') ? _url : `/${_url}`;
let url = (baseUrl ?? '') + pathUrl;
if (path) {
url = defaultPathSerializer({ path, url });
}
let search = query ? querySerializer(query) : '';
if (search.startsWith('?')) {
search = search.substring(1);
}
if (search) {
url += `?${search}`;
}
return url;
};
export function getValidRequestBody(options: {
body?: unknown;
bodySerializer?: BodySerializer | null;
serializedBody?: unknown;
}) {
const hasBody = options.body !== undefined;
const isSerializedBody = hasBody && options.bodySerializer;
if (isSerializedBody) {
if ('serializedBody' in options) {
const hasSerializedBody =
options.serializedBody !== undefined && options.serializedBody !== '';
return hasSerializedBody ? options.serializedBody : null;
}
// not all clients implement a serializedBody property (i.e. client-axios)
return options.body !== '' ? options.body : null;
}
// plain/text body
if (hasBody) {
return options.body;
}
// no body was provided
return undefined;
}

View File

@@ -0,0 +1,4 @@
// This file is auto-generated by @hey-api/openapi-ts
export type * from './types.gen';
export * from './sdk.gen';

View File

@@ -0,0 +1,132 @@
// This file is auto-generated by @hey-api/openapi-ts
import type { Client, Options as Options2, TDataShape } from './client';
import { client } from './client.gen';
import type { GetAllUsersApiV1AuthUsersGetData, GetAllUsersApiV1AuthUsersGetResponses, GetCurrentUserApiV1AuthMeGetData, GetCurrentUserApiV1AuthMeGetResponses, HealthCheckHealthGetData, HealthCheckHealthGetResponses, LoginApiV1AuthLoginPostData, LoginApiV1AuthLoginPostErrors, LoginApiV1AuthLoginPostResponses, LogoutApiV1AuthLogoutPostData, LogoutApiV1AuthLogoutPostResponses, RegisterApiV1AuthRegisterPostData, RegisterApiV1AuthRegisterPostErrors, RegisterApiV1AuthRegisterPostResponses, RootGetData, RootGetResponses } from './types.gen';
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean> = Options2<TData, ThrowOnError> & {
/**
* You can provide a client instance returned by `createClient()` instead of
* individual options. This might be also useful if you want to implement a
* custom client.
*/
client?: Client;
/**
* You can pass arbitrary values through the `meta` object. This can be
* used to access values that aren't defined as part of the SDK function.
*/
meta?: Record<string, unknown>;
};
/**
* 用户登录
*
* 用户登录接口
*
* - **username**: 用户名
* - **password**: 密码
*
* 返回JWT访问令牌
*/
export const loginApiV1AuthLoginPost = <ThrowOnError extends boolean = false>(options: Options<LoginApiV1AuthLoginPostData, ThrowOnError>) => {
return (options.client ?? client).post<LoginApiV1AuthLoginPostResponses, LoginApiV1AuthLoginPostErrors, ThrowOnError>({
url: '/api/v1/auth/login',
...options,
headers: {
'Content-Type': 'application/json',
...options.headers
}
});
};
/**
* 用户注册
*
* 用户注册接口
*
* - **username**: 用户名 (必须唯一)
* - **password**: 密码
*
* 注意:这是一个演示版本,实际生产环境需要更严格的验证
*/
export const registerApiV1AuthRegisterPost = <ThrowOnError extends boolean = false>(options: Options<RegisterApiV1AuthRegisterPostData, ThrowOnError>) => {
return (options.client ?? client).post<RegisterApiV1AuthRegisterPostResponses, RegisterApiV1AuthRegisterPostErrors, ThrowOnError>({
url: '/api/v1/auth/register',
...options,
headers: {
'Content-Type': 'application/json',
...options.headers
}
});
};
/**
* 获取当前用户信息
*
* 获取当前登录用户的信息
*/
export const getCurrentUserApiV1AuthMeGet = <ThrowOnError extends boolean = false>(options?: Options<GetCurrentUserApiV1AuthMeGetData, ThrowOnError>) => {
return (options?.client ?? client).get<GetCurrentUserApiV1AuthMeGetResponses, unknown, ThrowOnError>({
security: [
{
scheme: 'bearer',
type: 'http'
}
],
url: '/api/v1/auth/me',
...options
});
};
/**
* 用户登出
*
* 用户登出接口
*
* 注意由于JWT是无状态的实际登出需要客户端删除token
* 这里只是验证token并返回成功消息
*/
export const logoutApiV1AuthLogoutPost = <ThrowOnError extends boolean = false>(options?: Options<LogoutApiV1AuthLogoutPostData, ThrowOnError>) => {
return (options?.client ?? client).post<LogoutApiV1AuthLogoutPostResponses, unknown, ThrowOnError>({
security: [
{
scheme: 'bearer',
type: 'http'
}
],
url: '/api/v1/auth/logout',
...options
});
};
/**
* 获取所有用户列表
*
* 获取系统中所有用户的列表 (仅用于演示)
*/
export const getAllUsersApiV1AuthUsersGet = <ThrowOnError extends boolean = false>(options?: Options<GetAllUsersApiV1AuthUsersGetData, ThrowOnError>) => {
return (options?.client ?? client).get<GetAllUsersApiV1AuthUsersGetResponses, unknown, ThrowOnError>({
url: '/api/v1/auth/users',
...options
});
};
/**
* Root
*/
export const rootGet = <ThrowOnError extends boolean = false>(options?: Options<RootGetData, ThrowOnError>) => {
return (options?.client ?? client).get<RootGetResponses, unknown, ThrowOnError>({
url: '/',
...options
});
};
/**
* Health Check
*/
export const healthCheckHealthGet = <ThrowOnError extends boolean = false>(options?: Options<HealthCheckHealthGetData, ThrowOnError>) => {
return (options?.client ?? client).get<HealthCheckHealthGetResponses, unknown, ThrowOnError>({
url: '/health',
...options
});
};

View File

@@ -0,0 +1,207 @@
// This file is auto-generated by @hey-api/openapi-ts
export type ClientOptions = {
baseUrl: 'http://localhost:8080' | (string & {});
};
/**
* APIResponse
*/
export type ApiResponse = {
/**
* Success
*/
success: boolean;
/**
* Message
*/
message: string;
/**
* Data
*/
data?: {
[key: string]: unknown;
} | null;
};
/**
* HTTPValidationError
*/
export type HttpValidationError = {
/**
* Detail
*/
detail?: Array<ValidationError>;
};
/**
* UserLogin
*/
export type UserLogin = {
/**
* Username
*/
username: string;
/**
* Password
*/
password: string;
};
/**
* UserRegister
*/
export type UserRegister = {
/**
* Username
*/
username: string;
/**
* Password
*/
password: string;
};
/**
* ValidationError
*/
export type ValidationError = {
/**
* Location
*/
loc: Array<string | number>;
/**
* Message
*/
msg: string;
/**
* Error Type
*/
type: string;
};
export type LoginApiV1AuthLoginPostData = {
body: UserLogin;
path?: never;
query?: never;
url: '/api/v1/auth/login';
};
export type LoginApiV1AuthLoginPostErrors = {
/**
* Validation Error
*/
422: HttpValidationError;
};
export type LoginApiV1AuthLoginPostError = LoginApiV1AuthLoginPostErrors[keyof LoginApiV1AuthLoginPostErrors];
export type LoginApiV1AuthLoginPostResponses = {
/**
* Successful Response
*/
200: ApiResponse;
};
export type LoginApiV1AuthLoginPostResponse = LoginApiV1AuthLoginPostResponses[keyof LoginApiV1AuthLoginPostResponses];
export type RegisterApiV1AuthRegisterPostData = {
body: UserRegister;
path?: never;
query?: never;
url: '/api/v1/auth/register';
};
export type RegisterApiV1AuthRegisterPostErrors = {
/**
* Validation Error
*/
422: HttpValidationError;
};
export type RegisterApiV1AuthRegisterPostError = RegisterApiV1AuthRegisterPostErrors[keyof RegisterApiV1AuthRegisterPostErrors];
export type RegisterApiV1AuthRegisterPostResponses = {
/**
* Successful Response
*/
200: ApiResponse;
};
export type RegisterApiV1AuthRegisterPostResponse = RegisterApiV1AuthRegisterPostResponses[keyof RegisterApiV1AuthRegisterPostResponses];
export type GetCurrentUserApiV1AuthMeGetData = {
body?: never;
path?: never;
query?: never;
url: '/api/v1/auth/me';
};
export type GetCurrentUserApiV1AuthMeGetResponses = {
/**
* Successful Response
*/
200: ApiResponse;
};
export type GetCurrentUserApiV1AuthMeGetResponse = GetCurrentUserApiV1AuthMeGetResponses[keyof GetCurrentUserApiV1AuthMeGetResponses];
export type LogoutApiV1AuthLogoutPostData = {
body?: never;
path?: never;
query?: never;
url: '/api/v1/auth/logout';
};
export type LogoutApiV1AuthLogoutPostResponses = {
/**
* Successful Response
*/
200: ApiResponse;
};
export type LogoutApiV1AuthLogoutPostResponse = LogoutApiV1AuthLogoutPostResponses[keyof LogoutApiV1AuthLogoutPostResponses];
export type GetAllUsersApiV1AuthUsersGetData = {
body?: never;
path?: never;
query?: never;
url: '/api/v1/auth/users';
};
export type GetAllUsersApiV1AuthUsersGetResponses = {
/**
* Successful Response
*/
200: ApiResponse;
};
export type GetAllUsersApiV1AuthUsersGetResponse = GetAllUsersApiV1AuthUsersGetResponses[keyof GetAllUsersApiV1AuthUsersGetResponses];
export type RootGetData = {
body?: never;
path?: never;
query?: never;
url: '/';
};
export type RootGetResponses = {
/**
* Successful Response
*/
200: unknown;
};
export type HealthCheckHealthGetData = {
body?: never;
path?: never;
query?: never;
url: '/health';
};
export type HealthCheckHealthGetResponses = {
/**
* Successful Response
*/
200: unknown;
};

View File

@@ -1,526 +0,0 @@
/**
* This file was auto-generated by openapi-typescript.
* Do not make direct changes to the file.
*/
export interface paths {
"/users": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/**
* 获取用户列表
* @description 获取所有用户的分页列表
*/
get: {
parameters: {
query?: {
/** @description 页码 */
page?: number;
/** @description 每页数量 */
limit?: number;
/** @description 搜索关键词 */
search?: string;
};
header?: never;
path?: never;
cookie?: never;
};
requestBody?: never;
responses: {
/** @description 成功获取用户列表 */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
/** @example 200 */
code?: number;
/** @example success */
message?: string;
data?: {
users?: components["schemas"]["User"][];
/** @example 100 */
total?: number;
/** @example 1 */
page?: number;
/** @example 20 */
limit?: number;
};
};
};
};
};
};
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/users/{id}": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/**
* 获取用户详情
* @description 根据用户ID获取用户详细信息
*/
get: {
parameters: {
query?: never;
header?: never;
path: {
/** @description 用户ID */
id: number;
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description 成功获取用户详情 */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
/** @example 200 */
code?: number;
/** @example success */
message?: string;
data?: components["schemas"]["User"];
};
};
};
/** @description 用户不存在 */
404: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/machinery": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/**
* 获取农机列表
* @description 获取所有农机的分页列表
*/
get: {
parameters: {
query?: {
page?: number;
limit?: number;
/** @description 农机状态筛选 */
status?: "running" | "idle" | "maintenance" | "error" | "offline";
};
header?: never;
path?: never;
cookie?: never;
};
requestBody?: never;
responses: {
/** @description 成功获取农机列表 */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
/** @example 200 */
code?: number;
/** @example success */
message?: string;
data?: {
machinery?: components["schemas"]["Machinery"][];
/** @example 50 */
total?: number;
};
};
};
};
};
};
put?: never;
/**
* 创建农机
* @description 创建新的农机记录
*/
post: {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody: {
content: {
"application/json": components["schemas"]["CreateMachineryRequest"];
};
};
responses: {
/** @description 农机创建成功 */
201: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
/** @example 201 */
code?: number;
/** @example 农机创建成功 */
message?: string;
data?: components["schemas"]["Machinery"];
};
};
};
};
};
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/machinery/{id}": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/** 获取农机详情 */
get: {
parameters: {
query?: never;
header?: never;
path: {
id: number;
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description 成功获取农机详情 */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
/** @example 200 */
code?: number;
/** @example success */
message?: string;
data?: components["schemas"]["Machinery"];
};
};
};
};
};
/** 更新农机信息 */
put: {
parameters: {
query?: never;
header?: never;
path: {
id: number;
};
cookie?: never;
};
requestBody: {
content: {
"application/json": components["schemas"]["UpdateMachineryRequest"];
};
};
responses: {
/** @description 农机更新成功 */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
/** @example 200 */
code?: number;
/** @example 农机更新成功 */
message?: string;
data?: components["schemas"]["Machinery"];
};
};
};
};
};
post?: never;
/** 删除农机 */
delete: {
parameters: {
query?: never;
header?: never;
path: {
id: number;
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description 农机删除成功 */
204: {
headers: {
[name: string]: unknown;
};
content?: never;
};
};
};
options?: never;
head?: never;
patch?: never;
trace?: never;
};
}
export type webhooks = Record<string, never>;
export interface components {
schemas: {
User: {
/**
* @description 用户ID
* @example 1
*/
id?: number;
/**
* @description 用户名
* @example john_doe
*/
username?: string;
/**
* Format: email
* @description 邮箱地址
* @example john@example.com
*/
email?: string;
/**
* @description 全名
* @example John Doe
*/
full_name?: string;
/**
* @description 手机号码
* @example 13800138000
*/
phone?: string;
/**
* @description 用户角色
* @example operator
* @enum {string}
*/
role?: "admin" | "manager" | "operator" | "viewer";
/**
* @description 用户状态
* @example active
* @enum {string}
*/
status?: "active" | "inactive" | "suspended";
/**
* Format: date-time
* @description 创建时间
* @example 2024-01-15T10:30:00Z
*/
created_at?: string;
/**
* Format: date-time
* @description 更新时间
* @example 2024-01-15T10:30:00Z
*/
updated_at?: string;
};
Machinery: {
/**
* @description 农机ID
* @example 1
*/
id?: number;
/**
* @description 农机名称
* @example 拖拉机-001
*/
name?: string;
/**
* @description 农机类型
* @example tractor
* @enum {string}
*/
type?: "tractor" | "harvester" | "planter" | "sprayer" | "irrigation";
/**
* @description 型号
* @example John Deere 6M Series
*/
model?: string;
/**
* @description 序列号
* @example JD6M123456
*/
serial_number?: string;
/**
* @description 农机状态
* @example idle
* @enum {string}
*/
status?: "running" | "idle" | "maintenance" | "error" | "offline";
location?: components["schemas"]["Location"];
operator?: components["schemas"]["User"];
/**
* Format: date
* @description 购买日期
* @example 2024-01-01
*/
purchase_date?: string;
/**
* Format: date
* @description 上次维护日期
* @example 2024-06-15
*/
last_maintenance?: string;
/**
* Format: date
* @description 下次维护日期
* @example 2024-09-15
*/
next_maintenance?: string;
/**
* Format: date-time
* @description 创建时间
*/
created_at?: string;
/**
* Format: date-time
* @description 更新时间
*/
updated_at?: string;
};
Location: {
/**
* @description 地块ID
* @example 1
*/
field_id?: number;
/**
* @description 地块名称
* @example 北区A地块
*/
field_name?: string;
coordinates?: components["schemas"]["Coordinates"];
};
Coordinates: {
/**
* Format: double
* @description 纬度
* @example 39.9042
*/
latitude?: number;
/**
* Format: double
* @description 经度
* @example 116.4074
*/
longitude?: number;
};
CreateMachineryRequest: {
/** @description 农机名称 */
name: string;
/**
* @description 农机类型
* @enum {string}
*/
type: "tractor" | "harvester" | "planter" | "sprayer" | "irrigation";
/** @description 型号 */
model: string;
/** @description 序列号 */
serial_number?: string;
/**
* @description 操作员ID
* @example 1
*/
operator_id?: number;
/**
* Format: date
* @description 购买日期
*/
purchase_date?: string;
};
UpdateMachineryRequest: {
/** @description 农机名称 */
name?: string;
/**
* @description 农机状态
* @enum {string}
*/
status?: "running" | "idle" | "maintenance" | "error" | "offline";
/** @description 操作员ID */
operator_id?: number;
/**
* Format: date
* @description 上次维护日期
*/
last_maintenance?: string;
/**
* Format: date
* @description 下次维护日期
*/
next_maintenance?: string;
};
Error: {
/**
* @description 错误代码
* @example 404
*/
code?: number;
/**
* @description 错误信息
* @example 资源不存在
*/
message?: string;
/**
* @description 错误详情
* @example {
* "field": "id",
* "reason": "用户ID不存在"
* }
*/
details?: Record<string, never>;
};
};
responses: never;
parameters: never;
requestBodies: never;
headers: never;
pathItems: never;
}
export type $defs = Record<string, never>;
export type operations = Record<string, never>;