feat(app): FE 骨架协调提交——core 网络层/路由注册/页面桩

- DevEco 6.1 模板工程(API 6.1.1(24),bundle com.xiangsilian.app)+ INTERNET 权限
- core/:ApiClient(统一信封解包+401 自动刷新重试)/AuthStore(双令牌持久化+
  dev-token 通道+baseUrl 可配)/ContextHolder/ApiTypes —— 全部通过 ArkTS 严格编译
- 七页面注册 main_pages(桩态);Index 按登录态分流;页面间约定 router 路径跳转
  零 import(并行冲突隔离)
- app/README:CLI 构建门禁命令与代码约定
This commit is contained in:
xsl
2026-08-15 00:33:55 +08:00
parent 26357756e2
commit 9503c6e259
48 changed files with 994 additions and 0 deletions
+6
View File
@@ -0,0 +1,6 @@
/node_modules
/oh_modules
/.preview
/build
/.cxx
/.test
+33
View File
@@ -0,0 +1,33 @@
{
"apiType": "stageMode",
"buildOption": {
"resOptions": {
"copyCodeResource": {
"enable": false
}
}
},
"buildOptionSet": [
{
"name": "release",
"arkOptions": {
"obfuscation": {
"ruleOptions": {
"enable": false,
"files": [
"./obfuscation-rules.txt"
]
}
}
}
},
],
"targets": [
{
"name": "default"
},
{
"name": "ohosTest",
}
]
}
+6
View File
@@ -0,0 +1,6 @@
import { hapTasks } from '@ohos/hvigor-ohos-plugin';
export default {
system: hapTasks, /* Built-in plugin of Hvigor. It cannot be modified. */
plugins: [] /* Custom plugin to extend the functionality of Hvigor. */
}
+23
View File
@@ -0,0 +1,23 @@
# Define project specific obfuscation rules here.
# You can include the obfuscation configuration files in the current module's build-profile.json5.
#
# For more details, see
# https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/source-obfuscation
# Obfuscation options:
# -disable-obfuscation: disable all obfuscations
# -enable-property-obfuscation: obfuscate the property names
# -enable-toplevel-obfuscation: obfuscate the names in the global scope
# -compact: remove unnecessary blank spaces and all line feeds
# -remove-log: remove all console.* statements
# -print-namecache: print the name cache that contains the mapping from the old names to new names
# -apply-namecache: reuse the given cache file
# Keep options:
# -keep-property-name: specifies property names that you want to keep
# -keep-global-name: specifies names that you want to keep in the global scope
-enable-property-obfuscation
-enable-toplevel-obfuscation
-enable-filename-obfuscation
-enable-export-obfuscation
+10
View File
@@ -0,0 +1,10 @@
{
"name": "entry",
"version": "1.0.0",
"description": "Please describe the basic information.",
"main": "",
"author": "",
"license": "",
"dependencies": {}
}
+100
View File
@@ -0,0 +1,100 @@
/**
* 极简 HTTP 客户端:统一信封解包 + 401 自动刷新重试一次。
*
* ArkTS 严格模式约束(本文件全部遵守,FE 任务照此风格):
* - 请求体一律 Record<string, Object>(具名字面量),不用内联对象类型
* - throw 只抛 ApiError(Error 子类),未知异常先包装
* - code!=0 一律抛 ApiError;UI 层只 catch ApiError
*/
import http from '@ohos.net.http'
import { ApiEnvelope, ApiError } from './ApiTypes'
import { AuthStore } from './AuthStore'
const AUTH_EXPIRED_CODES: number[] = [40100, 40101, 40102]
export class ApiClient {
static async get<T>(path: string): Promise<T> {
return ApiClient.request<T>(http.RequestMethod.GET, path, undefined)
}
static async post<T>(path: string, body?: Record<string, Object>): Promise<T> {
return ApiClient.request<T>(http.RequestMethod.POST, path, body)
}
/** 不带 token、不触发自动刷新(AuthStore.refreshOnce 内部使用,防递归)。 */
static async postWithoutAuth<T>(path: string, body: Record<string, Object>): Promise<T> {
return ApiClient.doRequest<T>(path, http.RequestMethod.POST, body, undefined, false)
}
private static async request<T>(
method: http.RequestMethod,
path: string,
body: Record<string, Object> | undefined
): Promise<T> {
const token = AuthStore.getAccessToken()
if (token === undefined) {
// 未登录直接短路,省一次必然 401 的往返
throw new ApiError(40100, '请先登录', '登录后即可继续')
}
try {
return await ApiClient.doRequest<T>(path, method, body, token, true)
} catch (e) {
const wrapped = ApiClient.wrapUnknown(e)
if (wrapped instanceof ApiError && AUTH_EXPIRED_CODES.includes(wrapped.code)) {
const refreshed = await AuthStore.refreshOnce()
if (refreshed) {
return await ApiClient.doRequest<T>(path, method, body, AuthStore.getAccessToken(), true)
}
}
throw wrapped
}
}
private static async doRequest<T>(
path: string,
method: http.RequestMethod,
body: Record<string, Object> | undefined,
token: string | undefined,
withAuth: boolean
): Promise<T> {
const base = await AuthStore.getBaseUrl()
const url = `${base}${path}`
const client = http.createHttp()
try {
const header: Record<string, string> = {
'Content-Type': 'application/json'
}
if (withAuth && token !== undefined) {
header['Authorization'] = `Bearer ${token}`
}
const resp = await client.request(url, {
method: method,
header: header,
extraData: body !== undefined ? JSON.stringify(body) : undefined,
expectDataType: http.HttpDataType.OBJECT,
connectTimeout: 10000,
readTimeout: 30000
})
if (resp.responseCode !== 200 || resp.result === null || resp.result === undefined) {
// 网关/代理层错误:没有信封可用,给统一话术(NFR-UX-02)
throw new ApiError(50000, '服务开小差了', '请稍后重试', resp.responseCode)
}
const env = resp.result as ApiEnvelope<T>
if (env.code !== 0) {
throw new ApiError(env.code, env.message, env.hint, resp.responseCode)
}
return env.data
} finally {
client.destroy()
}
}
/** ArkTS 禁止 throw 任意类型:未知异常统一包装成 ApiError。 */
private static wrapUnknown(e: Object): ApiError {
if (e instanceof ApiError) {
return e
}
return new ApiError(50000, '请求失败,请检查网络', '请稍后重试')
}
}
+29
View File
@@ -0,0 +1,29 @@
/**
* 后端统一响应信封与错误类型(对齐 packages/shared/response.py)。
*
* 信封形状:{code, message, data, hint?, request_id?}
* - code=0 成功;4xxxx 客户端错;5xxxx 服务端错;6xxxx 外部依赖错
* - 所有非 0 code 都必须走 ApiError 抛出,UI 层只 catch ApiError
*/
export interface ApiEnvelope<T> {
code: number
message: string
data: T
hint?: string
request_id?: string
}
export class ApiError extends Error {
readonly code: number
readonly hint: string | undefined
readonly httpStatus: number
constructor(code: number, message: string, hint?: string, httpStatus = 200) {
super(message)
this.name = 'ApiError'
this.code = code
this.hint = hint
this.httpStatus = httpStatus
}
}
+155
View File
@@ -0,0 +1,155 @@
/**
* 会话状态与令牌持久化(对齐后端 FR-ACC-05 双令牌)。
*
* - access 短令牌放内存 + preferences(local 明文可接受:V1 骨架,无支付;
* 正式版应迁 @ohos.security.asset,注释留迁移点)
* - refresh 一次性轮换:每次 refresh 换新对
* - dev-token 登录:POST /auth/dev-token(后端 DEV_AUTH_ENABLED 本地可用;
* 华为账号/短信登录是后续通道,接口按多通道预留)
* - ArkTS 约束:所有请求/响应都是具名 interface;字面量先声明类型再传
*/
import preferences from '@ohos.data.preferences'
import { ApiClient } from './ApiClient'
import { ContextHolder } from './ContextHolder'
export interface TokenPair {
accessToken: string
refreshToken: string
expiresIn: number
refreshExpiresIn: number
userId: string
}
interface AuthWireResp {
access_token: string
refresh_token: string
expires_in: number
refresh_expires_in: number
user_id: string
}
const PREF_NAME = 'meida_auth'
const KEY_TOKENS = 'tokens'
const KEY_BASE_URL = 'base_url'
export const DEFAULT_BASE_URL = 'http://127.0.0.1:8000'
export class AuthStore {
private static tokens: TokenPair | undefined
private static prefs: preferences.Preferences | undefined
private static refreshing: Promise<boolean> | undefined
static async init(): Promise<void> {
AuthStore.prefs = await preferences.getPreferences(ContextHolder.get(), { name: PREF_NAME })
const raw = await AuthStore.prefs.get(KEY_TOKENS, '') as string
if (raw !== '') {
try {
AuthStore.tokens = JSON.parse(raw) as TokenPair
} catch (_e) {
AuthStore.tokens = undefined
}
}
}
static isLoggedIn(): boolean {
return AuthStore.tokens !== undefined && AuthStore.tokens.accessToken !== ''
}
static getAccessToken(): string | undefined {
return AuthStore.tokens?.accessToken
}
static getUserId(): string | undefined {
return AuthStore.tokens?.userId
}
static async setBaseUrl(url: string): Promise<void> {
await AuthStore.ensurePrefs()
await AuthStore.prefs!.put(KEY_BASE_URL, url)
await AuthStore.prefs!.flush()
}
static async getBaseUrl(): Promise<string> {
await AuthStore.ensurePrefs()
return await AuthStore.prefs!.get(KEY_BASE_URL, DEFAULT_BASE_URL) as string
}
/** dev-token 登录(本地后端开发通道)。失败由 ApiClient 抛 ApiError。 */
static async loginByDevToken(deviceKey: string): Promise<void> {
const req: Record<string, Object> = { 'device_key': deviceKey }
const data = await ApiClient.post<AuthWireResp>('/api/v1/auth/dev-token', req)
await AuthStore.saveTokens(AuthStore.fromWire(data))
}
/** 用 refresh 换新对。返回 false 表示会话已失效(应回登录页)。 */
static async refreshOnce(): Promise<boolean> {
if (AuthStore.refreshing !== undefined) {
return AuthStore.refreshing
}
const t = AuthStore.tokens
if (!t || t.refreshToken === '') {
return false
}
AuthStore.refreshing = AuthStore.doRefresh(t)
return AuthStore.refreshing
}
static async logout(): Promise<void> {
const t = AuthStore.tokens
if (t && t.refreshToken !== '') {
// 尽力通知服务端撤销;失败不阻塞本地登出
try {
const req: Record<string, Object> = { 'refresh_token': t.refreshToken }
await ApiClient.post<void>('/api/v1/auth/logout', req)
} catch (_e) {
// 忽略:服务端不可达也必须能本地登出
}
}
await AuthStore.clear()
}
static async clear(): Promise<void> {
AuthStore.tokens = undefined
await AuthStore.ensurePrefs()
await AuthStore.prefs!.delete(KEY_TOKENS)
await AuthStore.prefs!.flush()
}
private static async doRefresh(t: TokenPair): Promise<boolean> {
try {
// 刻意走 postWithoutAuth:绕过 ApiClient 的自动刷新(否则递归)
const req: Record<string, Object> = { 'refresh_token': t.refreshToken }
const data = await ApiClient.postWithoutAuth<AuthWireResp>('/api/v1/auth/refresh', req)
await AuthStore.saveTokens(AuthStore.fromWire(data))
return true
} catch (_e) {
await AuthStore.clear()
return false
} finally {
AuthStore.refreshing = undefined
}
}
private static fromWire(w: AuthWireResp): TokenPair {
return {
accessToken: w.access_token,
refreshToken: w.refresh_token,
expiresIn: w.expires_in,
refreshExpiresIn: w.refresh_expires_in,
userId: w.user_id
}
}
private static async saveTokens(t: TokenPair): Promise<void> {
AuthStore.tokens = t
await AuthStore.ensurePrefs()
await AuthStore.prefs!.put(KEY_TOKENS, JSON.stringify(t))
await AuthStore.prefs!.flush()
}
private static async ensurePrefs(): Promise<void> {
if (AuthStore.prefs === undefined) {
AuthStore.prefs = await preferences.getPreferences(ContextHolder.get(), { name: PREF_NAME })
}
}
}
@@ -0,0 +1,22 @@
/**
* ContextHolder:UI 上下文的全局挂点。
*
* preferences / http 等系统能力需要 Context;ArkUI 里合法取法是
* getUIContext().getHostContext(),但网络层与页面解耦后统一从 EntryAbility
* 注入一次最简单(EntryAbility.onCreate 里 set)。
*/
export class ContextHolder {
private static context: Context | undefined
static set(context: Context): void {
ContextHolder.context = context
}
static get(): Context {
if (!ContextHolder.context) {
throw new Error('ContextHolder 未初始化:EntryAbility.onCreate 应先调用 set()')
}
return ContextHolder.context
}
}
@@ -0,0 +1,53 @@
import { AbilityConstant, ConfigurationConstant, UIAbility, Want } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { window } from '@kit.ArkUI';
import { ContextHolder } from '../core/ContextHolder';
import { AuthStore } from '../core/AuthStore';
const DOMAIN = 0x0000;
export default class EntryAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
// 全局 Context 挂点:core 层(preferences/http)从这里取,UI 不传参
ContextHolder.set(this.context)
AuthStore.init()
try {
this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET);
} catch (err) {
hilog.error(DOMAIN, 'testTag', 'Failed to set colorMode. Cause: %{public}s', JSON.stringify(err));
}
hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onCreate');
}
onDestroy(): void {
hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onDestroy');
}
onWindowStageCreate(windowStage: window.WindowStage): void {
// Main window is created, set main page for this ability
hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
windowStage.loadContent('pages/Index', (err) => {
if (err.code) {
hilog.error(DOMAIN, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err));
return;
}
hilog.info(DOMAIN, 'testTag', 'Succeeded in loading the content.');
});
}
onWindowStageDestroy(): void {
// Main window is destroyed, release UI related resources
hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');
}
onForeground(): void {
// Ability has brought to foreground
hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onForeground');
}
onBackground(): void {
// Ability has back to background
hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onBackground');
}
}
@@ -0,0 +1,16 @@
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BackupExtensionAbility, BundleVersion } from '@kit.CoreFileKit';
const DOMAIN = 0x0000;
export default class EntryBackupAbility extends BackupExtensionAbility {
async onBackup() {
hilog.info(DOMAIN, 'testTag', 'onBackup ok');
await Promise.resolve();
}
async onRestore(bundleVersion: BundleVersion) {
hilog.info(DOMAIN, 'testTag', 'onRestore ok %{public}s', JSON.stringify(bundleVersion));
await Promise.resolve();
}
}
+17
View File
@@ -0,0 +1,17 @@
/**
* ChatPage —— 占位桩(FE 批次对应任务填充实现)。
* 已注册进 main_pages.json,其它页面可按路径跳转。
*/
@Entry
@Component
struct ChatPage {
build() {
Column() {
Text('ChatPage(建设中)').fontSize(16).fontColor('#666666')
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
}
+17
View File
@@ -0,0 +1,17 @@
/**
* HomePage —— 占位桩(FE 批次对应任务填充实现)。
* 已注册进 main_pages.json,其它页面可按路径跳转。
*/
@Entry
@Component
struct HomePage {
build() {
Column() {
Text('HomePage(建设中)').fontSize(16).fontColor('#666666')
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
}
+29
View File
@@ -0,0 +1,29 @@
/**
* 应用入口:按登录态分流到登录页或主页。
* 页面间一律 router 路径跳转(页面已全部注册 main_pages),跨任务零 import。
*/
import { router } from '@kit.ArkUI'
import { AuthStore } from '../core/AuthStore'
@Entry
@Component
struct Index {
aboutToAppear(): void {
const target = AuthStore.isLoggedIn() ? 'pages/HomePage' : 'pages/LoginPage'
router.replaceUrl({ url: target })
}
build() {
Column() {
LoadingProgress().width(48).height(48)
Text('美搭')
.fontSize(20)
.fontWeight(FontWeight.Bold)
.margin({ top: 12 })
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
}
@@ -0,0 +1,17 @@
/**
* LoginPage —— 占位桩(FE 批次对应任务填充实现)。
* 已注册进 main_pages.json,其它页面可按路径跳转。
*/
@Entry
@Component
struct LoginPage {
build() {
Column() {
Text('LoginPage(建设中)').fontSize(16).fontColor('#666666')
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
}
@@ -0,0 +1,17 @@
/**
* ProfilePage —— 占位桩(FE 批次对应任务填充实现)。
* 已注册进 main_pages.json,其它页面可按路径跳转。
*/
@Entry
@Component
struct ProfilePage {
build() {
Column() {
Text('ProfilePage(建设中)').fontSize(16).fontColor('#666666')
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
}
@@ -0,0 +1,17 @@
/**
* ReportCreatePage —— 占位桩(FE 批次对应任务填充实现)。
* 已注册进 main_pages.json,其它页面可按路径跳转。
*/
@Entry
@Component
struct ReportCreatePage {
build() {
Column() {
Text('ReportCreatePage(建设中)').fontSize(16).fontColor('#666666')
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
}
@@ -0,0 +1,17 @@
/**
* ReportResultPage —— 占位桩(FE 批次对应任务填充实现)。
* 已注册进 main_pages.json,其它页面可按路径跳转。
*/
@Entry
@Component
struct ReportResultPage {
build() {
Column() {
Text('ReportResultPage(建设中)').fontSize(16).fontColor('#666666')
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
}
+53
View File
@@ -0,0 +1,53 @@
{
"module": {
"name": "entry",
"type": "entry",
"description": "$string:module_desc",
"mainElement": "EntryAbility",
"deviceTypes": [
"phone"
],
"deliveryWithInstall": true,
"requestPermissions": [
{ "name": "ohos.permission.INTERNET" }
],
"installationFree": false,
"pages": "$profile:main_pages",
"abilities": [
{
"name": "EntryAbility",
"srcEntry": "./ets/entryability/EntryAbility.ets",
"description": "$string:EntryAbility_desc",
"icon": "$media:layered_image",
"label": "$string:EntryAbility_label",
"startWindowIcon": "$media:startIcon",
"startWindowBackground": "$color:start_window_background",
"exported": true,
"skills": [
{
"entities": [
"entity.system.home"
],
"actions": [
"ohos.want.action.home"
]
}
]
}
],
"extensionAbilities": [
{
"name": "EntryBackupAbility",
"srcEntry": "./ets/entrybackupability/EntryBackupAbility.ets",
"type": "backup",
"exported": false,
"metadata": [
{
"name": "ohos.extension.backup",
"resource": "$profile:backup_config"
}
],
}
]
}
}
@@ -0,0 +1,8 @@
{
"color": [
{
"name": "start_window_background",
"value": "#FFFFFF"
}
]
}
@@ -0,0 +1,8 @@
{
"float": [
{
"name": "page_text_font_size",
"value": "50fp"
}
]
}
@@ -0,0 +1,16 @@
{
"string": [
{
"name": "module_desc",
"value": "module description"
},
{
"name": "EntryAbility_desc",
"value": "description"
},
{
"name": "EntryAbility_label",
"value": "label"
}
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.6 KiB

@@ -0,0 +1,7 @@
{
"layered-image":
{
"background" : "$media:background",
"foreground" : "$media:foreground"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

@@ -0,0 +1,3 @@
{
"allowToBackupRestore": true
}
@@ -0,0 +1,11 @@
{
"src": [
"pages/Index",
"pages/LoginPage",
"pages/HomePage",
"pages/ReportCreatePage",
"pages/ReportResultPage",
"pages/ChatPage",
"pages/ProfilePage"
]
}
@@ -0,0 +1,8 @@
{
"color": [
{
"name": "start_window_background",
"value": "#000000"
}
]
}
+2
View File
@@ -0,0 +1,2 @@
{
}
@@ -0,0 +1,35 @@
import { hilog } from '@kit.PerformanceAnalysisKit';
import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium';
export default function abilityTest() {
describe('ActsAbilityTest', () => {
// Defines a test suite. Two parameters are supported: test suite name and test suite function.
beforeAll(() => {
// Presets an action, which is performed only once before all test cases of the test suite start.
// This API supports only one parameter: preset action function.
})
beforeEach(() => {
// Presets an action, which is performed before each unit test case starts.
// The number of execution times is the same as the number of test cases defined by **it**.
// This API supports only one parameter: preset action function.
})
afterEach(() => {
// Presets a clear action, which is performed after each unit test case ends.
// The number of execution times is the same as the number of test cases defined by **it**.
// This API supports only one parameter: clear action function.
})
afterAll(() => {
// Presets a clear action, which is performed after all test cases of the test suite end.
// This API supports only one parameter: clear action function.
})
it('assertContain', 0, () => {
// Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function.
hilog.info(0x0000, 'testTag', '%{public}s', 'it begin');
let a = 'abc';
let b = 'b';
// Defines a variety of assertion methods, which are used to declare expected boolean conditions.
expect(a).assertContain(b);
expect(a).assertEqual(a);
})
})
}
@@ -0,0 +1,5 @@
import abilityTest from './Ability.test';
export default function testsuite() {
abilityTest();
}
+11
View File
@@ -0,0 +1,11 @@
{
"module": {
"name": "entry_test",
"type": "feature",
"deviceTypes": [
"phone"
],
"deliveryWithInstall": true,
"installationFree": false
}
}
+5
View File
@@ -0,0 +1,5 @@
import localUnitTest from './LocalUnit.test';
export default function testsuite() {
localUnitTest();
}
+33
View File
@@ -0,0 +1,33 @@
import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium';
export default function localUnitTest() {
describe('localUnitTest', () => {
// Defines a test suite. Two parameters are supported: test suite name and test suite function.
beforeAll(() => {
// Presets an action, which is performed only once before all test cases of the test suite start.
// This API supports only one parameter: preset action function.
});
beforeEach(() => {
// Presets an action, which is performed before each unit test case starts.
// The number of execution times is the same as the number of test cases defined by **it**.
// This API supports only one parameter: preset action function.
});
afterEach(() => {
// Presets a clear action, which is performed after each unit test case ends.
// The number of execution times is the same as the number of test cases defined by **it**.
// This API supports only one parameter: clear action function.
});
afterAll(() => {
// Presets a clear action, which is performed after all test cases of the test suite end.
// This API supports only one parameter: clear action function.
});
it('assertContain', 0, () => {
// Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function.
let a = 'abc';
let b = 'b';
// Defines a variety of assertion methods, which are used to declare expected boolean conditions.
expect(a).assertContain(b);
expect(a).assertEqual(a);
});
});
}