| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- import { request } from '@/utils/request'
-
- export const readingService = {
- // 保存阅读进度
- async saveProgress(progress) {
- // 本地保存
- const key = `progress_${progress.novelId}_${progress.chapterId}`
- uni.setStorageSync(key, JSON.stringify(progress))
-
- // 用户登录时同步到服务器
- if (uni.getStorageSync('token')) {
- try {
- await request({
- url: '/reading/progress',
- method: 'POST',
- data: progress,
- headers: {
- 'Content-Type': 'application/json',
- 'Authorization': `Bearer ${uni.getStorageSync('token')}`
- }
- })
- } catch (e) {
- console.error('进度同步失败', e)
- }
- }
- },
-
- // 获取阅读进度
- async getProgress(novelId, chapterId) {
- // 优先从本地获取
- const key = `progress_${novelId}_${chapterId}`
- const localData = uni.getStorageSync(key)
- if (localData) {
- return JSON.parse(localData)
- }
-
- // 用户登录时从服务器获取
- if (uni.getStorageSync('token')) {
- try {
- const res = await request({
- url: `/reading/progress?novelId=${novelId}&chapterId=${chapterId}`,
- method: 'GET',
- headers: {
- 'Authorization': `Bearer ${uni.getStorageSync('token')}`
- }
- })
-
- if (res.data.success) {
- return res.data.data
- }
- } catch (e) {
- console.error('进度获取失败', e)
- }
- }
-
- return null
- },
-
- // 同步所有本地进度
- async syncAllLocalProgress() {
- if (!uni.getStorageSync('token')) return
-
- const allKeys = uni.getStorageInfoSync().keys
- const progressKeys = allKeys.filter(key => key.startsWith('progress_'))
-
- for (const key of progressKeys) {
- const progress = JSON.parse(uni.getStorageSync(key))
- try {
- await request({
- url: '/reading/progress',
- method: 'POST',
- data: progress,
- headers: {
- 'Content-Type': 'application/json',
- 'Authorization': `Bearer ${uni.getStorageSync('token')}`
- }
- })
-
- // 同步成功后移除本地记录
- uni.removeStorageSync(key)
- } catch (e) {
- console.error(`进度同步失败: ${key}`, e)
- }
- }
- }
- }
|