task-42(账号/权限页面): 实现用户列表查询适配

新增 users-model.ts 纯解析(Java AdminUserItemVo snake_case→camelCase、
缺 id 行过滤、分页字段归一、success=false 抛后端 message)与 users.ts
adapter(fetchUserList:normalize+GET /api/admin/users+parse);UsersPage
改用 adapter,去掉模板内联 http.get+unwrap。task-41 依赖断言改指数据层。
8 用例全过,299 单测 + build 绿。
This commit is contained in:
2026-09-05 14:31:32 +08:00
parent 60fa5a818b
commit d760838e71
5 changed files with 170 additions and 10 deletions
+54
View File
@@ -0,0 +1,54 @@
/** 用户列表查询适配(任务 42):纯解析模块,无 axios 依赖,与 Java AdminUserListVo 对齐。 */
import { unwrap } from './envelope.ts'
import { emptyUserPageResult, type UserPageResult } from './users-dto.ts'
import type { AdminUser } from '../types/admin'
function text(value: unknown): string {
return typeof value === 'string' ? value : ''
}
function numberOrNull(value: unknown): number | null {
return typeof value === 'number' && Number.isFinite(value) ? value : null
}
/** 把 Java AdminUserItemVo(snake_case) 映射为前端 AdminUser(camelCase);缺 id 视为无效。 */
export function toAdminUserItem(raw: unknown): AdminUser | null {
if (!raw || typeof raw !== 'object') return null
const r = raw as Record<string, unknown>
const id = numberOrNull(r.id)
if (id === null) return null
const item: AdminUser = { id, username: text(r.username), role: text(r.role) }
if (typeof r.is_admin === 'boolean') item.isAdmin = r.is_admin
const createdById = numberOrNull(r.created_by_id)
if (createdById !== null) item.createdById = createdById
const createdAt = text(r.created_at)
if (createdAt) item.createdAt = createdAt
const creator = text(r.creator_username)
if (creator) item.creatorUsername = creator
const abbr = text(r.pinyin_abbr)
if (abbr) item.pinyinAbbr = abbr
return item
}
/**
* 归一化 Java 用户列表负载(data:{items,total,page,page_size} 或已解包 VO)为前端
* UserPageResult;空/缺省字段回默认,success=false 抛后端 message。
*/
export function parseUserPage(payload: unknown): UserPageResult {
const out = emptyUserPageResult()
const core = unwrap<unknown>(payload)
if (!core || typeof core !== 'object') return out
const record = core as Record<string, unknown>
if (Array.isArray(record.items)) {
out.items = record.items
.map((raw) => toAdminUserItem(raw))
.filter((item): item is AdminUser => item !== null)
}
if (typeof record.total === 'number') out.total = record.total
if (typeof record.page === 'number' && record.page >= 1) out.page = Math.floor(record.page)
const rawSize = record.page_size ?? record.pageSize
if (typeof rawSize === 'number' && rawSize >= 1) out.pageSize = Math.floor(rawSize)
if (typeof record.current_user_id === 'number') out.currentUserId = record.current_user_id
if (typeof record.current_user_username === 'string') out.currentUserUsername = record.current_user_username
return out
}
+15
View File
@@ -0,0 +1,15 @@
import { http } from './http'
import { parseUserPage } from './users-model'
import {
normalizeUserPageParams,
toUserListQuery,
type UserListParams,
type UserPageResult,
} from './users-dto'
/** 分页查询用户列表:归一化参数 → GET /api/admin/users → 解析 Java 分页负载。 */
export async function fetchUserList(params: Partial<UserListParams> = {}): Promise<UserPageResult> {
const normalized = normalizeUserPageParams(params)
const { data } = await http.get('/api/admin/users', { params: toUserListQuery(normalized) })
return parseUserPage(data)
}
@@ -1,9 +1,9 @@
<script setup lang="ts"> <script setup lang="ts">
import { onMounted, reactive, ref } from 'vue' import { onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus' import { ElMessage, ElMessageBox } from 'element-plus'
import { http, unwrap } from '@/api/http' import { http } from '@/api/http'
import type { AdminUser } from '@/types/admin' import type { AdminUser } from '@/types/admin'
import type { UserPageResult } from '@/api/users-dto' import { fetchUserList } from '@/api/users'
const loading = ref(false) const loading = ref(false)
const rows = ref<AdminUser[]>([]) const rows = ref<AdminUser[]>([])
@@ -13,11 +13,9 @@ const form = reactive({ username: '', page: 1, pageSize: 15 })
async function loadUsers() { async function loadUsers() {
loading.value = true loading.value = true
try { try {
const { data } = await http.get('/api/admin/users', { params: { username: form.username || undefined, page: form.page, page_size: form.pageSize } }) const page = await fetchUserList({ page: form.page, pageSize: form.pageSize, keyword: form.username || undefined })
const result = unwrap<UserPageResult | { data?: UserPageResult }>(data) rows.value = page.items
const value: UserPageResult = 'data' in result && result.data ? result.data : result as UserPageResult total.value = page.total
rows.value = value.items || []
total.value = Number(value.total || 0)
} catch (error) { } catch (error) {
ElMessage.error(error instanceof Error ? error.message : '用户列表加载失败') ElMessage.error(error instanceof Error ? error.message : '用户列表加载失败')
} finally { } finally {
+5 -3
View File
@@ -63,10 +63,12 @@ test('test_task_041_users_dto_invalid_input_rejected', () => {
}) })
test('test_task_041_users_dto_dependency_failure_returns_actionable_message', () => { test('test_task_041_users_dto_dependency_failure_returns_actionable_message', () => {
// 依赖失败:DTO 纯模块不依赖 axios/http供页面与后续 adapter 引用。 // 依赖失败:DTO 纯模块不依赖 axios/http由查询适配层引用。
const dto = readSource('src/api/users-dto.ts') const dto = readSource('src/api/users-dto.ts')
assert.equal(/axios|from '\.\/http'/.test(dto), false, 'DTO 模块保持纯逻辑') assert.equal(/axios|from '\.\/http'/.test(dto), false, 'DTO 模块保持纯逻辑')
assert.match(dto, /export interface UserPageResult/) assert.match(dto, /export interface UserPageResult/)
const page = readSource('src/pages/account/UsersPage.vue') const adapter = readSource('src/api/users.ts')
assert.match(page, /users-dto|UserListParams|UserPageResult/) assert.match(adapter, /users-dto/, '查询适配复用 DTO/参数归一')
const model = readSource('src/api/users-model.ts')
assert.match(model, /users-dto/, '解析模型复用 DTO 默认值')
}) })
+91
View File
@@ -0,0 +1,91 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { readSource } from './helpers.ts'
import { parseUserPage, toAdminUserItem } from '../src/api/users-model.ts'
import { USER_PAGE_DEFAULT_SIZE } from '../src/api/users-dto.ts'
test('test_task_042_user_list_adapter_normal_primary_path', () => {
// 正常主路径:Java snake_case data.items 信封解出 camelCase 分页结果。
const page = parseUserPage({
success: true,
data: {
items: [{ id: 1, username: 'admin', role: 'super_admin', is_admin: true, created_by_id: 3, creator_username: 'root', created_at: '2026-01-01T00:00:00', pinyin_abbr: 'adm' }],
total: 1,
page: 1,
page_size: 15,
},
})
assert.equal(page.items.length, 1)
assert.equal(page.items[0].username, 'admin')
assert.equal(page.items[0].isAdmin, true)
assert.equal(page.items[0].createdById, 3)
assert.equal(page.items[0].creatorUsername, 'root')
assert.equal(page.items[0].pinyinAbbr, 'adm')
assert.equal(page.total, 1)
assert.equal(page.pageSize, 15)
})
test('test_task_042_user_list_adapter_normal_variant_input', () => {
// 正常变体:已解包的 AdminUserListVo 直传同样可归一。
const page = parseUserPage({
items: [{ id: 2, username: '张伟恒', role: 'admin', is_admin: true, created_by_id: null }],
total: 5,
page: 2,
page_size: 20,
})
assert.equal(page.items[0].username, '张伟恒')
assert.equal(page.items[0].createdById, undefined)
assert.equal(page.page, 2)
assert.equal(page.pageSize, 20)
})
test('test_task_042_user_list_adapter_normal_repeated_operation_is_idempotent', () => {
// 正常重复:解析不修改输入、结果稳定。
const payload = { data: { items: [{ id: 3, username: 'u', role: 'normal' }], total: 1, page: 1, page_size: 15 } }
assert.deepEqual(parseUserPage(payload), parseUserPage(payload))
})
test('test_task_042_user_list_adapter_boundary_empty_input', () => {
// 边界空值:无 items/空负载回默认空结果,不崩溃。
const page = parseUserPage({})
assert.deepEqual(page.items, [])
assert.equal(page.total, 0)
assert.equal(page.pageSize, USER_PAGE_DEFAULT_SIZE)
})
test('test_task_042_user_list_adapter_boundary_single_item', () => {
// 边界单元素:单条最小字段(缺 id 的行被过滤)。
const page = parseUserPage({ data: { items: [{ id: 7, username: 'root', role: 'super_admin' }, { username: 'no-id' }], total: 2, page: 1, page_size: 15 } })
assert.equal(page.items.length, 1)
assert.equal(page.items[0].id, 7)
})
test('test_task_042_user_list_adapter_boundary_limit_or_missing_field', () => {
// 边界上限/缺字段:缺 page_size 用默认;缺省字段为空串而非 undefined。
const single = toAdminUserItem({ id: 9, username: '', role: '', is_admin: false })
assert.equal(single?.username, '')
assert.equal(single?.role, '')
assert.equal(single?.isAdmin, false)
const page = parseUserPage({ items: [], total: 0, page: 1 })
assert.equal(page.pageSize, USER_PAGE_DEFAULT_SIZE)
})
test('test_task_042_user_list_adapter_invalid_input_rejected', () => {
// 异常输入:success=false 被拒绝并带后端 message;缺 id 的行不入列表。
assert.throws(() => parseUserPage({ success: false, message: '无权限查看用户' }), /无权限查看用户/)
assert.equal(toAdminUserItem({ username: 'x' }), null)
assert.equal(toAdminUserItem('garbage'), null)
})
test('test_task_042_user_list_adapter_dependency_failure_returns_actionable_message', () => {
// 依赖失败:页面查询走 adapter(fetchUserList→parseUserPage),不在模板内联解包。
const page = readSource('src/pages/account/UsersPage.vue')
assert.match(page, /fetchUserList/)
assert.equal(/unwrap<|\/api\/admin\/users/.test(page), false, '页面不再内联 http.get + unwrap')
const adapter = readSource('src/api/users.ts')
assert.match(adapter, /\/api\/admin\/users/)
assert.match(adapter, /parseUserPage/)
assert.match(adapter, /normalizeUserPageParams/)
const model = readSource('src/api/users-model.ts')
assert.match(model, /export function parseUserPage/)
})