feat(device): 实现设备创建功能并优化API调用

- 添加设备创建接口,支持认证检查和重定向
- 更新设备服务以使用新的请求体类型
- 修改表单组件以支持设备创建请求和响应处理
- 扩展HTTP客户端和类型定义以支持对象类型的请求体
- 添加调试日志记录API响应信息
- 更新按钮点击事件处理函数以触发设备创建流程
This commit is contained in:
Chaos
2025-12-01 07:36:14 +08:00
parent f973284140
commit 87892951f6
5 changed files with 53 additions and 15 deletions

View File

@@ -6,7 +6,7 @@ import { log } from '$lib/log.ts';
interface RequestOptions extends Omit<RequestInit, 'method' | 'body'> {
body?: JsonObject | FormData;
body?: JsonObject | FormData | object;
}
const API_BASE_URL = import.meta.env.VITE_PUBLIC_API_URL || 'http://localhost:18888/api';
@@ -92,6 +92,7 @@ const httpRequest = async <T>(
body: canHaveBody ? requestBody : undefined,
...rest
});
log.debug('API Response:', response)
if (!response.ok) {
let errorDetail;

View File

@@ -1,6 +1,7 @@
import { api } from '$lib/api/httpClient.ts';
import type { PageResult } from '$lib/types/dataTable.ts';
import type { CreateDeviceRequest, DeviceResponse } from '$lib/types/api.ts';
import type { JsonValue } from '$lib/types/http.ts';
export const deviceService = {
@@ -35,7 +36,7 @@ export const deviceService = {
createDevice: async (device: CreateDeviceRequest,token:string) => {
const result = await api.post<DeviceResponse>('/devices',{
body: JSON.stringify(device),
body: device,
headers:{Authorization: `${token}`}
});
if (result.code != 200 || !result.data){

View File

@@ -87,12 +87,39 @@
export function submitAndGetPayload(): CreateDeviceRequest | null {
if (validate()) {
// 返回深拷贝的数据,防止后续修改影响
return $state.snapshot(formData);
const snapshot = $state.snapshot(formData);
fetch('/api/devices', {
method: 'POST',
headers: {},
body: JSON.stringify(snapshot)
}).then(res => res.json())
.then(res => {
if (res.ok) {
log.info('设备创建成功', res);
open = false;
} else {
log.error('设备创建失败', res);
}
})
.catch(err => {
log.error('设备创建失败', err);
});
return snapshot;
}
return null; // 验证失败
}
const handleSubmit = () => {
const payload = submitAndGetPayload();
if (payload) {
log.info('设备创建成功', payload);
open = false;
}
};
</script>
<div class="space-y-8">
@@ -233,6 +260,6 @@
<div class="join flex justify-center" >
<button class="btn btn-error join-item" onclick={onreset}>重置</button>
<button class="btn join-item" onclick={draft}>保存草稿</button>
<button class="btn btn-primary btn-wide join-item" onclick={submit}>提交</button>
<button class="btn btn-primary btn-wide join-item" onclick={handleSubmit}>提交</button>
</div>
</div>

View File

@@ -4,4 +4,4 @@ export interface JsonObject {
[key:string] : JsonValue;
}
export type JsonArray = JsonValue[];
export type JsonValue = JsonPrimitive | JsonObject | JsonArray;
export type JsonValue = JsonPrimitive | JsonObject | JsonArray | object;