This commit is contained in:
2026-01-30 11:45:55 +08:00
parent 11cce27665
commit 7211525ef8
2 changed files with 35 additions and 3 deletions

36
App.tsx
View File

@@ -103,10 +103,19 @@ class Api {
private static _instance: Api | null = null;
private ws: WebSocket | null = null;
private clientId: string = '';
private userId: number = 0;
private constructor() {
}
public setUserId(userId: number) {
this.userId = userId;
}
public getUserId(): number {
return this.userId;
}
public static get instance() {
if (Api._instance === null) {
Api._instance = new Api();
@@ -153,10 +162,22 @@ class Api {
private headers(): Record<string, string> {
const h: Record<string, string> = { 'Content-Type': 'application/json' };
if (this.clientId) h['X-Client-ID'] = this.clientId;
if (this.userId) h['X-User-ID'] = String(this.userId);
return h;
}
public async login(username: string, password: string): Promise<number> {
const res = await fetch(`${Api.BASE_URL}/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password }),
});
const data = await res.json();
if (!data.success) throw new Error(data.message);
this.userId = data.data.userId;
return this.userId;
}
public async register(walletType: WalletType, params: any) {
const res = await fetch(`${Api.BASE_URL}/register`, {
method: 'POST',
@@ -217,6 +238,16 @@ export default class App extends Component<AppProps, AppState> {
}
async componentDidMount() {
/* 登录获取 userId */
try {
await Api.instance.login('test123', '123456');
console.log('[登录成功] userId:', Api.instance.getUserId());
} catch (error) {
console.error('[登录失败]', error);
Alert.alert('登录失败', String(error));
return;
}
/* 初始化代理客户端 */
await this.initProxyClient();
@@ -290,7 +321,8 @@ export default class App extends Component<AppProps, AppState> {
ws.send(JSON.stringify({
type: 'register',
clientId: this.clientId,
messageId: 'register_' + Date.now()
messageId: 'register_' + Date.now(),
data: { userId: Api.instance.getUserId() }
}));
Api.instance.setWebSocket(ws, this.clientId);