my-kaiqiuwang/src/hooks/useAuthHeaders.tsx
kyuuseiryuu defd95c218 refactor(push): unify notification payload structure and handling
Refactor the notification handling logic to use a unified `topic` based payload structure. This change replaces the flat `NotificationData` interface with a typed `topic` and `data` separation, enabling stricter type checking for different notification types (e.g., `SERVER_PUSH`).

Key changes:
- Updated `NotificationData` type to include `topic` and `data` fields, referencing `TopicPayload`.
- Modified `sw.js` to parse incoming `MessagePayload` using `fromMessagePayload`, ensuring the topic is `SERVER_PUSH` before extracting `title` and `options`.
- Renamed internal types in `utils/common.ts` to `ServerSendTopicPayload` and `Topics` for clarity.
- Updated `firebase-admin.ts` to wrap data in a `payload` JSON string before sending to Firebase Cloud Messaging, and added logic to clean up unregistered tokens.
- Added backward compatibility support for older clients by sending a secondary legacy-formatted message when a `SERVER_PUSH` topic is detected.
- Moved `NOTIFICATION_TOKEN_KEY` constant to `utils/constants.ts` and updated related hooks to use it for consistency.
- Updated `logger.ts` to comment out file logging during development/testing to reduce disk I/O.

This refactor improves type safety, reduces code duplication in payload handling, and ensures better compatibility between the web client and the service worker.
2026-03-27 01:05:01 +09:00

30 lines
1021 B
TypeScript

import { useLogto } from "@logto/react"
import { useEffect, useState } from "react";
import { LOGTO_RESOURCE } from "@/utils/constants";
import { App, Button } from "antd";
import useAutoLogin from "./useAutoLogin";
export const useAuthHeaders = (): HeadersInit | undefined => {
const { isAuthenticated, getAccessToken } = useLogto();
const [headers, setHeaders] = useState<HeadersInit | undefined>();
const { autoSignIn } = useAutoLogin();
const app = App.useApp();
useEffect(() => {
if (!isAuthenticated) return;
getAccessToken(LOGTO_RESOURCE)
.then(token => {
if (token) {
setHeaders({ Authorization: `Bearer ${token}` })
return;
}
app.notification.warning({
key: 'use-auth-headers-login-expired',
title: '登陆已过期',
actions: [
<Button key='auto-signin' type="primary" onClick={() => autoSignIn() }></Button>
],
});
});
}, [isAuthenticated]);
return headers;
}