Browse Source

集成缓存处理优化

master
xuhuajiao 1 month ago
parent
commit
bc97655bd1
  1. 27
      pages/home/home.vue
  2. 16
      pages/lendCar/lendCar.vue
  3. 6
      pages/login/login.vue
  4. 74
      pages/user/user.vue
  5. 6
      subpkg/pages/collect-list/collect-list.vue
  6. 11
      subpkg/pages/myLending/myLending.vue
  7. 75
      subpkg/pages/reader-card/reader-card.vue
  8. 181
      utils/storage.js

27
pages/home/home.vue

@ -191,8 +191,7 @@
import { FetchOpenId, FetchFindAllReaderBindByOpenId} from '@/api/user'; import { FetchOpenId, FetchFindAllReaderBindByOpenId} from '@/api/user';
import { FetchInitScreenBookRecommend } from '@/api/book'; import { FetchInitScreenBookRecommend } from '@/api/book';
import config from '@/utils/config'; import config from '@/utils/config';
const READLIST = 'reader-card-list';
import { STORAGE_KEYS } from '@/utils/storage';
export default { export default {
data() { data() {
@ -283,17 +282,17 @@ export default {
// //
this.readerCardList = defaultCard ? [defaultCard, ...otherCards] : res.data; this.readerCardList = defaultCard ? [defaultCard, ...otherCards] : res.data;
uni.setStorageSync(READLIST, this.readerCardList);
uni.setStorageSync('currentReaderCard', defaultCard);
uni.setStorageSync(STORAGE_KEYS.READER_CARD_LIST, this.readerCardList);
uni.setStorageSync(STORAGE_KEYS.CURRENT_READER_CARD, defaultCard);
} else { } else {
this.isBindLibraryCard = false; this.isBindLibraryCard = false;
this.readerCardList = []; this.readerCardList = [];
uni.setStorageSync(READLIST, []);
uni.setStorageSync(STORAGE_KEYS.READER_CARD_LIST, []);
} }
} catch (err) { } catch (err) {
console.error('初始化失败:', err); console.error('初始化失败:', err);
const list = uni.getStorageSync(READLIST) || [];
const list = uni.getStorageSync(STORAGE_KEYS.READER_CARD_LIST) || [];
// //
const defaultCard = list.find(item => item.bindDefault === true); const defaultCard = list.find(item => item.bindDefault === true);
const otherCards = list.filter(item => !item.bindDefault); const otherCards = list.filter(item => !item.bindDefault);
@ -308,10 +307,12 @@ export default {
const res = await FetchInitScreenBookRecommend({ libcode: '1201' }); const res = await FetchInitScreenBookRecommend({ libcode: '1201' });
let books = res.data || []; let books = res.data || [];
// 3Base64
// 3setData
const limit = 3; const limit = 3;
for (let i = 0; i < books.length && i < limit; i++) {
let item = books[i];
const displayBooks = books.slice(0, limit);
for (let i = 0; i < displayBooks.length; i++) {
let item = displayBooks[i];
if (item.imgPath) { if (item.imgPath) {
const imageUrl = this.baseUrl + '/api/fileRelevant/getImg?imgType=2&imgId=' + item.imgPath; const imageUrl = this.baseUrl + '/api/fileRelevant/getImg?imgType=2&imgId=' + item.imgPath;
try { try {
@ -325,12 +326,8 @@ export default {
} }
} }
// 3
for (let i = limit; i < books.length; i++) {
books[i].base64Cover = '';
}
this.recommendedBooks = books;
// 3setData
this.recommendedBooks = displayBooks;
this.isLoading = false; this.isLoading = false;
} catch (err) { } catch (err) {
console.error('获取图书推荐失败:', err); console.error('获取图书推荐失败:', err);

16
pages/lendCar/lendCar.vue

@ -44,7 +44,8 @@
<script> <script>
import { FetchInitScreenSetting } from '@/api/user'; import { FetchInitScreenSetting } from '@/api/user';
import { FetchRdloanlist, FetchRenewbook } from '@/api/book';
import { FetchRdloanlist, FetchRenewbook, FetchDeletebook } from '@/api/book';
import { getCurrentReaderCard } from '@/utils/storage';
export default { export default {
data() { data() {
@ -54,7 +55,7 @@ export default {
screenConfig: {}, screenConfig: {},
}; };
}, },
onLoad() {
onShow() {
this.getConfigAndList(); this.getConfigAndList();
}, },
computed: { computed: {
@ -84,9 +85,13 @@ export default {
async getLendingList() { async getLendingList() {
try { try {
// 使
const currentReaderCard = await getCurrentReaderCard();
console.log('当前证:', currentReaderCard);
const params = { const params = {
...this.screenConfig, ...this.screenConfig,
rdid: uni.getStorageSync('currentReaderCard'),
rdid: currentReaderCard.bindValue,
}; };
const res = await FetchRdloanlist(params); const res = await FetchRdloanlist(params);
const result = typeof res.data === 'string' ? JSON.parse(res.data) : res.data; const result = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
@ -127,9 +132,12 @@ export default {
uni.showLoading({ title: '续借中...' }); uni.showLoading({ title: '续借中...' });
try { try {
// 使
const currentReaderCard = await getCurrentReaderCard();
const params = { const params = {
...this.screenConfig, ...this.screenConfig,
rdid: uni.getStorageSync('currentReaderCard'),
rdid: currentReaderCard.bindValue,
barcode: barcodes, barcode: barcodes,
logtype: '30007' logtype: '30007'
}; };

6
pages/login/login.vue

@ -49,7 +49,7 @@
// //
import { FetchInitScreenSetting, FetchReaderList, FetchBindReadCard,FetchFindAllReaderBindByOpenId } from '@/api/user'; import { FetchInitScreenSetting, FetchReaderList, FetchBindReadCard,FetchFindAllReaderBindByOpenId } from '@/api/user';
import config from '@/utils/config'; import config from '@/utils/config';
const READLIST = 'reader-card-list';
import { STORAGE_KEYS } from '@/utils/storage';
export default { export default {
data() { data() {
@ -220,9 +220,9 @@ export default {
FetchFindAllReaderBindByOpenId(data).then(res => { FetchFindAllReaderBindByOpenId(data).then(res => {
console.log('获取读者证列表',res) console.log('获取读者证列表',res)
if (res.code === 200 && res.data.length > 0) { if (res.code === 200 && res.data.length > 0) {
uni.setStorageSync(READLIST, res.data);
uni.setStorageSync(STORAGE_KEYS.READER_CARD_LIST, res.data);
} else { } else {
uni.setStorageSync(READLIST, []);
uni.setStorageSync(STORAGE_KEYS.READER_CARD_LIST, []);
} }
}) })
.catch(err => { .catch(err => {

74
pages/user/user.vue

@ -53,11 +53,11 @@
</template> </template>
<script> <script>
import config from '@/utils/config'
import { FetchBindRead, FetchFindAllReaderByOpenId } from '@/api/user';
import config from '@/utils/config';
import { FetchFindAllReaderByOpenId } from '@/api/user';
import { getReaderCardList, STORAGE_KEYS } from '@/utils/storage';
const USER_KEY = 'user-info'; const USER_KEY = 'user-info';
const READLIST = 'reader-card-list';
export default { export default {
data() { data() {
@ -66,10 +66,11 @@ export default {
cardNo: "", cardNo: "",
isBindLibraryCard: false, isBindLibraryCard: false,
base64Img: "", base64Img: "",
loading: false,
}; };
}, },
onLoad() { onLoad() {
// this.loadUserInfo();
this.loadUserInfo();
}, },
onShow() { onShow() {
this.loadUserInfo(); this.loadUserInfo();
@ -81,13 +82,14 @@ export default {
}); });
}, },
//
async loadUserInfo() { async loadUserInfo() {
if (this.loading) return;
this.loading = true;
try { try {
const openId = uni.getStorageSync('wx_login_code');
const readerList = uni.getStorageSync(READLIST) || [];
const readerList = await getReaderCardList();
const openId = uni.getStorageSync(STORAGE_KEYS.WX_LOGIN_CODE);
//
if (openId) { if (openId) {
const res = await FetchFindAllReaderByOpenId({ const res = await FetchFindAllReaderByOpenId({
libcode: '1201', libcode: '1201',
@ -95,14 +97,20 @@ export default {
}); });
if (res.code === 200 && res.data) { if (res.code === 200 && res.data) {
//
this.userInfo = { this.userInfo = {
nickname: res.data.nickname || '', nickname: res.data.nickname || '',
avatarId: res.data.avatar || '' avatarId: res.data.avatar || ''
}; };
if (res.data.avatar) {
const imageUrl = config.baseUrl + '/api/fileRelevant/getImg?imgType=5&imgId=' + res.data.avatar; const imageUrl = config.baseUrl + '/api/fileRelevant/getImg?imgType=5&imgId=' + res.data.avatar;
try {
const base64 = await this.urlToBase64(imageUrl); const base64 = await this.urlToBase64(imageUrl);
this.base64Img = base64; this.base64Img = base64;
} catch (err) {
console.error('[User] Failed to load avatar:', err);
}
}
uni.setStorageSync(USER_KEY, this.userInfo); uni.setStorageSync(USER_KEY, this.userInfo);
} else { } else {
@ -112,36 +120,32 @@ export default {
this.userInfo = uni.getStorageSync(USER_KEY) || {}; this.userInfo = uni.getStorageSync(USER_KEY) || {};
} }
//
const defaultCard = readerList.find(item => item.bindDefault === true); const defaultCard = readerList.find(item => item.bindDefault === true);
this.cardNo = defaultCard ? defaultCard.bindValue : (readerList[0]?.bindValue || ''); this.cardNo = defaultCard ? defaultCard.bindValue : (readerList[0]?.bindValue || '');
this.isBindLibraryCard = readerList.length > 0; this.isBindLibraryCard = readerList.length > 0;
} catch (err) { } catch (err) {
//
console.error('加载用户信息失败:', err)
const readerList = uni.getStorageSync(READLIST) || [];
console.error('[User] Failed to load user info:', err);
const readerList = uni.getStorageSync(STORAGE_KEYS.READER_CARD_LIST) || [];
this.userInfo = uni.getStorageSync(USER_KEY) || {}; this.userInfo = uni.getStorageSync(USER_KEY) || {};
const defaultCard = readerList.find(item => item.bindDefault === true); const defaultCard = readerList.find(item => item.bindDefault === true);
this.cardNo = defaultCard ? defaultCard.bindValue : (readerList[0]?.bindValue || ''); this.cardNo = defaultCard ? defaultCard.bindValue : (readerList[0]?.bindValue || '');
this.isBindLibraryCard = readerList.length > 0; this.isBindLibraryCard = readerList.length > 0;
} finally {
this.loading = false;
} }
}, },
//
toCheckLogin(pageName) {
const readerList = uni.getStorageSync(READLIST) || [];
async toCheckLogin(pageName) {
const readerList = await getReaderCardList();
//
if (readerList.length === 0) { if (readerList.length === 0) {
this.dialogToggle(); this.dialogToggle();
return; return;
} }
//
const routeMap = { const routeMap = {
'收藏': '/subpkg/pages/collect-list/collect-list', '收藏': '/subpkg/pages/collect-list/collect-list',
// switch_tab_index = 0
'借阅': () => { '借阅': () => {
uni.setStorageSync('switch_tab_index', 0); uni.setStorageSync('switch_tab_index', 0);
uni.navigateTo({ uni.navigateTo({
@ -150,22 +154,26 @@ export default {
}, },
'我的留言': '/subpkg/pages/feedback-list/feedback-list', '我的留言': '/subpkg/pages/feedback-list/feedback-list',
'解绑读者证': '/subpkg/pages/reader-card/reader-card' '解绑读者证': '/subpkg/pages/reader-card/reader-card'
}
};
const target = routeMap[pageName]
const target = routeMap[pageName];
if (typeof target === 'function') { if (typeof target === 'function') {
target() // +
target();
} else if (target) { } else if (target) {
uni.navigateTo({ url: target })
uni.navigateTo({ url: target });
} }
}, },
dialogToggle() { dialogToggle() {
this.$refs.alertDialog.open(); this.$refs.alertDialog.open();
}, },
dialogConfirm() { dialogConfirm() {
uni.navigateTo({ url: "/pages/login/login" }); uni.navigateTo({ url: "/pages/login/login" });
}, },
dialogClose() {},
urlToBase64(url) { urlToBase64(url) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
uni.request({ uni.request({
@ -174,11 +182,6 @@ export default {
responseType: 'arraybuffer', responseType: 'arraybuffer',
success: (res) => { success: (res) => {
try { try {
const buffer = new Uint8Array(res.data);
let binary = '';
for (let i = 0; i < buffer.length; i++) {
binary += String.fromCharCode(buffer[i]);
}
const base64 = uni.arrayBufferToBase64(res.data); const base64 = uni.arrayBufferToBase64(res.data);
const dataUri = 'data:image/jpeg;base64,' + base64; const dataUri = 'data:image/jpeg;base64,' + base64;
resolve(dataUri); resolve(dataUri);
@ -186,28 +189,28 @@ export default {
reject(e); reject(e);
} }
}, },
fail: reject
fail: (err) => {
console.error('[User] Failed to fetch image:', err);
reject(err);
}
}); });
}); });
}, },
dialogClose() {},
// 退
toLogOut() { toLogOut() {
uni.showModal({ uni.showModal({
title: '确认退出', title: '确认退出',
content: '确定要退出当前账号吗?', content: '确定要退出当前账号吗?',
success: (res) => { success: (res) => {
if (res.confirm) { if (res.confirm) {
//
uni.removeStorageSync(USER_KEY); uni.removeStorageSync(USER_KEY);
uni.removeStorageSync(READLIST);
uni.removeStorageSync(STORAGE_KEYS.READER_CARD_LIST);
uni.removeStorageSync(STORAGE_KEYS.CURRENT_READER_CARD);
//
this.userInfo = {}; this.userInfo = {};
this.cardNo = ""; this.cardNo = "";
this.isBindLibraryCard = false; this.isBindLibraryCard = false;
this.base64Img = "";
uni.showToast({ title: '退出成功', icon: 'success' }); uni.showToast({ title: '退出成功', icon: 'success' });
uni.switchTab({ url: "/pages/home/home" }); uni.switchTab({ url: "/pages/home/home" });
@ -270,7 +273,6 @@ export default {
.user-card{ .user-card{
margin-top: 5px; margin-top: 5px;
font-size: 13px; font-size: 13px;
// font-weight: bold;
color: #fff; color: #fff;
line-height: 17px; line-height: 17px;
} }

6
subpkg/pages/collect-list/collect-list.vue

@ -10,7 +10,8 @@
<!-- 图书收藏 --> <!-- 图书收藏 -->
<view v-if="activeTab === 1" class="tab-content"> <view v-if="activeTab === 1" class="tab-content">
<view class="empty" v-if="bookCollectList.length === 0"> <view class="empty" v-if="bookCollectList.length === 0">
暂无收藏的图书
<uni-icons style="margin-left: 20px;" custom-prefix="iconfont" type="icon-kongshuju" size="80"></uni-icons>
<text style="margin-top: 20px;">暂无收藏的图书~</text>
</view> </view>
<view class="recommendation-list" v-else> <view class="recommendation-list" v-else>
<view <view
@ -32,7 +33,8 @@
<!-- 活动收藏 --> <!-- 活动收藏 -->
<view v-if="activeTab === 2" class="tab-content"> <view v-if="activeTab === 2" class="tab-content">
<view class="empty" v-if="activityCollectList.length === 0"> <view class="empty" v-if="activityCollectList.length === 0">
暂无收藏的活动
<uni-icons style="margin-left: 20px;" custom-prefix="iconfont" type="icon-kongshuju" size="80"></uni-icons>
<text style="margin-top: 20px;">暂无收藏的活动~</text>
</view> </view>
<view class="activity-list" v-else> <view class="activity-list" v-else>
<view <view

11
subpkg/pages/myLending/myLending.vue

@ -70,6 +70,7 @@ import { FetchInitScreenSetting } from '@/api/user';
import { FetchHistoryloan, FetchRdloanlist, FetchCoverByISBN } from '@/api/book'; import { FetchHistoryloan, FetchRdloanlist, FetchCoverByISBN } from '@/api/book';
import myTabs from "@/components/my-tabs/my-tabs.vue"; import myTabs from "@/components/my-tabs/my-tabs.vue";
import lendingListItem from "@/components/lending-list-item/lending-list-item.vue"; import lendingListItem from "@/components/lending-list-item/lending-list-item.vue";
import { getCurrentReaderCard } from '@/utils/storage';
export default { export default {
components: { myTabs, lendingListItem }, components: { myTabs, lendingListItem },
@ -172,9 +173,12 @@ export default {
} }
try { try {
// 使
const currentReaderCard = await getCurrentReaderCard();
const params = { const params = {
...this.screenConfig, ...this.screenConfig,
rdid: uni.getStorageSync('currentReaderCard'),
rdid: currentReaderCard.bindValue,
logtype: '30002', logtype: '30002',
page: this.pageAll, page: this.pageAll,
rows: 10, rows: 10,
@ -205,9 +209,12 @@ export default {
async getLendingList() { async getLendingList() {
this.loadingLending = true; this.loadingLending = true;
try { try {
// 使
const currentReaderCard = await getCurrentReaderCard();
const params = { const params = {
...this.screenConfig, ...this.screenConfig,
rdid: uni.getStorageSync('currentReaderCard'),
rdid: currentReaderCard.bindValue,
}; };
const res = await FetchRdloanlist(params); const res = await FetchRdloanlist(params);
const result = typeof res.data === 'string' ? JSON.parse(res.data) : res.data; const result = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;

75
subpkg/pages/reader-card/reader-card.vue

@ -72,8 +72,7 @@ import {
FetchSetDefaultReadCard, FetchSetDefaultReadCard,
FetchUnbindReadCard FetchUnbindReadCard
} from '@/api/user'; } from '@/api/user';
const READLIST = 'reader-card-list';
import { getReaderCardList, getOpenId, setCurrentReaderCard, STORAGE_KEYS } from '@/utils/storage';
export default { export default {
data() { data() {
@ -81,61 +80,50 @@ export default {
isEditMode: false, isEditMode: false,
selectedValue: '', selectedValue: '',
cardList: [], cardList: [],
qrcodeText: '' //
qrcodeText: '',
loading: false,
} }
}, },
onShow() { onShow() {
this.getBindReaderCardList(); this.getBindReaderCardList();
}, },
methods: { methods: {
//
formatCardNo(cardNo) { formatCardNo(cardNo) {
if (!cardNo) return ''; if (!cardNo) return '';
const str = String(cardNo); const str = String(cardNo);
const len = str.length; const len = str.length;
if (len > 8) { if (len > 8) {
// 2 + * + 2
const front = str.substring(0, 2); const front = str.substring(0, 2);
const end = str.substring(len - 2); const end = str.substring(len - 2);
const star = '*'.repeat(len - 4); //
const star = '*'.repeat(len - 4);
return front + star + end; return front + star + end;
} else { } else {
// 8*** + 2
return '***' + str.substring(len - 2); return '***' + str.substring(len - 2);
} }
}, },
// +
toggleEditMode() { toggleEditMode() {
this.isEditMode = !this.isEditMode; this.isEditMode = !this.isEditMode;
this.selectedValue = ''; this.selectedValue = '';
}, },
//
async getBindReaderCardList() {
try {
const openId = uni.getStorageSync('wx_login_code');
if (!openId) return;
async getBindReaderCardList(forceRefresh = false) {
if (this.loading) return;
this.loading = true;
const res = await FetchFindAllReaderBindByOpenId({
libcode: '1201',
openId: openId
});
if (res.code === 200 && res.data.length > 0) {
this.cardList = res.data;
uni.setStorageSync(READLIST, res.data);
} else {
this.cardList = [];
this.selectedValue = '';
uni.setStorageSync(READLIST, []);
}
try {
const readerList = await getReaderCardList(forceRefresh);
this.cardList = readerList;
} catch (err) { } catch (err) {
this.cardList = uni.getStorageSync(READLIST) || [];
console.error('[ReaderCard] Failed to load reader card list:', err);
const cachedList = uni.getStorageSync(STORAGE_KEYS.READER_CARD_LIST) || [];
this.cardList = cachedList;
} finally {
this.loading = false;
} }
}, },
// 使
handleSelectItem(value) { handleSelectItem(value) {
if (this.isEditMode) { if (this.isEditMode) {
this.selectedValue = this.selectedValue === value ? '' : value; this.selectedValue = this.selectedValue === value ? '' : value;
@ -149,7 +137,12 @@ export default {
return; return;
} }
const openId = uni.getStorageSync('wx_login_code');
const openId = await getOpenId();
if (!openId) {
uni.showToast({ title: '获取用户信息失败', icon: 'none' });
return;
}
uni.showModal({ uni.showModal({
title: '提示', title: '提示',
content: '确定设为默认读者证吗?', content: '确定设为默认读者证吗?',
@ -162,35 +155,40 @@ export default {
libcode: '1201', libcode: '1201',
openid: openId openid: openId
}); });
uni.setStorageSync('currentReaderCard', value);
await this.getBindReaderCardList();
setCurrentReaderCard(value);
await this.getBindReaderCardList(true);
uni.showToast({ title: '设置成功', icon: 'success' }); uni.showToast({ title: '设置成功', icon: 'success' });
} catch (err) { } catch (err) {
console.error('[ReaderCard] Failed to set default card:', err);
uni.showToast({ title: '设置失败', icon: 'none' }); uni.showToast({ title: '设置失败', icon: 'none' });
} }
} }
}); });
}, },
// ========== ==========
showQrcode(bindValue) { showQrcode(bindValue) {
this.qrcodeText = bindValue; this.qrcodeText = bindValue;
this.$refs.popup.open(); this.$refs.popup.open();
}, },
closePopup() { closePopup() {
console.log('关闭弹窗'); console.log('关闭弹窗');
this.qrcodeText = ''; this.qrcodeText = '';
this.$refs.popup.close(); this.$refs.popup.close();
}, },
//
async handleUnbind() { async handleUnbind() {
if (!this.selectedValue) { if (!this.selectedValue) {
uni.showToast({ title: '请选择要解绑的读者证', icon: 'none' }); uni.showToast({ title: '请选择要解绑的读者证', icon: 'none' });
return; return;
} }
const openId = uni.getStorageSync('wx_login_code');
const openId = await getOpenId();
if (!openId) {
uni.showToast({ title: '获取用户信息失败', icon: 'none' });
return;
}
const unbindItem = this.cardList.find(item => item.bindValue === this.selectedValue); const unbindItem = this.cardList.find(item => item.bindValue === this.selectedValue);
const isUnbindDefault = unbindItem?.bindDefault === true; const isUnbindDefault = unbindItem?.bindDefault === true;
@ -211,7 +209,7 @@ export default {
if (result.code === 200) { if (result.code === 200) {
uni.showToast({ title: '解绑成功', icon: 'success' }); uni.showToast({ title: '解绑成功', icon: 'success' });
this.selectedValue = ''; this.selectedValue = '';
await this.getBindReaderCardList();
await this.getBindReaderCardList(true);
if (isUnbindDefault && this.cardList.length > 0) { if (isUnbindDefault && this.cardList.length > 0) {
const newValue = this.cardList[0].bindValue; const newValue = this.cardList[0].bindValue;
@ -221,8 +219,8 @@ export default {
libcode: '1201', libcode: '1201',
openid: openId openid: openId
}); });
uni.setStorageSync('currentReaderCard', newValue);
await this.getBindReaderCardList();
setCurrentReaderCard(newValue);
await this.getBindReaderCardList(true);
} }
if (this.cardList.length === 0) { if (this.cardList.length === 0) {
@ -230,6 +228,7 @@ export default {
} }
} }
} catch (err) { } catch (err) {
console.error('[ReaderCard] Failed to unbind card:', err);
uni.showToast({ title: '解绑失败', icon: 'none' }); uni.showToast({ title: '解绑失败', icon: 'none' });
} }
} }
@ -264,7 +263,6 @@ export default {
font-size: 15px; font-size: 15px;
} }
//
.card-list{ .card-list{
position: absolute; position: absolute;
left: 0; left: 0;
@ -329,7 +327,6 @@ export default {
} }
} }
.add-card-btn { .add-card-btn {
display: flex; display: flex;
align-items: center; align-items: center;

181
utils/storage.js

@ -0,0 +1,181 @@
/**
* 缓存工具函数
* 提供缓存降级策略先从缓存获取缓存不存在则调用接口重新获取
*/
import { FetchOpenId, FetchFindAllReaderBindByOpenId } from '@/api/user';
// 缓存键名常量
export const STORAGE_KEYS = {
CURRENT_READER_CARD: 'currentReaderCard',
READER_CARD_LIST: 'readList',
WX_LOGIN_CODE: 'wx_login_code',
};
/**
* 获取微信 openId带缓存降级
* 参考 home.vue 中的 initUserAndCheckBind 方法
* @returns {Promise<string|null>} 微信 openId
*/
export async function getOpenId() {
try {
// 1. 先看缓存有没有 openId
let openId = uni.getStorageSync(STORAGE_KEYS.WX_LOGIN_CODE);
// 2. 有缓存,直接返回
if (openId) {
return openId;
}
// 3. 没有 → 走微信登录流程
const loginRes = await new Promise((resolve, reject) => {
uni.login({
success: resolve,
fail: reject
});
});
if (!loginRes.code) {
console.warn('[Storage] WeChat login failed');
return null;
}
// 4. 获取 openId
const openRes = await FetchOpenId({
libcode: '1201',
code: loginRes.code
});
if (openRes.code !== 200 || !openRes.data) {
console.warn('[Storage] Failed to fetch openId');
return null;
}
openId = openRes.data;
uni.setStorageSync(STORAGE_KEYS.WX_LOGIN_CODE, openId);
return openId;
} catch (err) {
console.error('[Storage] Error in getOpenId:', err);
return null;
}
}
/**
* 获取当前读者证信息带缓存降级
* @returns {Promise<Object|null>} 当前读者证信息
*/
export async function getCurrentReaderCard() {
// 1. 先从缓存获取
const cachedCard = uni.getStorageSync(STORAGE_KEYS.CURRENT_READER_CARD);
// 2. 如果缓存存在且有效,直接返回
if (cachedCard && Object.keys(cachedCard).length > 0) {
return cachedCard;
}
// 3. 缓存不存在,尝试从接口获取
try {
// 使用带缓存降级的函数获取 openId
const openId = await getOpenId();
if (!openId) {
console.warn('[Storage] No openId found, cannot fetch reader card');
return null;
}
const res = await FetchFindAllReaderBindByOpenId({
libcode: '1201',
openId: openId
});
if (res.code === 200 && res.data.length > 0) {
// 默认证排第一位
const defaultCard = res.data.find(item => item.bindDefault === true);
const otherCards = res.data.filter(item => !item.bindDefault);
// 合并:默认在前,其他在后
const readerCardList = defaultCard ? [defaultCard, ...otherCards] : res.data;
const resultCard = defaultCard || res.data[0];
// 更新缓存
uni.setStorageSync(STORAGE_KEYS.CURRENT_READER_CARD, resultCard);
uni.setStorageSync(STORAGE_KEYS.READER_CARD_LIST, readerCardList);
return resultCard;
}
} catch (err) {
console.error('[Storage] Failed to fetch reader card:', err);
}
return null;
}
/**
* 获取读者证列表带缓存降级
* @param {boolean} forceRefresh - 是否强制刷新默认 false
* @returns {Promise<Array>} 读者证列表
*/
export async function getReaderCardList(forceRefresh = false) {
// 1. 如果不是强制刷新,先从缓存获取
if (!forceRefresh) {
const cachedList = uni.getStorageSync(STORAGE_KEYS.READER_CARD_LIST);
// 如果缓存存在且有效,直接返回
if (cachedList && Array.isArray(cachedList) && cachedList.length > 0) {
return cachedList;
}
}
// 2. 缓存不存在或强制刷新时,尝试从接口获取
try {
// 使用带缓存降级的函数获取 openId
const openId = await getOpenId();
if (!openId) {
console.warn('[Storage] No openId found, cannot fetch reader card list');
return [];
}
const res = await FetchFindAllReaderBindByOpenId({
libcode: '1201',
openId: openId
});
if (res.code === 200 && res.data.length > 0) {
// 默认证排第一位
const defaultCard = res.data.find(item => item.bindDefault === true);
const otherCards = res.data.filter(item => !item.bindDefault);
// 合并:默认在前,其他在后
const readerCardList = defaultCard ? [defaultCard, ...otherCards] : res.data;
// 更新缓存
uni.setStorageSync(STORAGE_KEYS.READER_CARD_LIST, readerCardList);
// 同时更新当前读者证
if (defaultCard) {
uni.setStorageSync(STORAGE_KEYS.CURRENT_READER_CARD, defaultCard);
}
return readerCardList;
}
} catch (err) {
console.error('[Storage] Failed to fetch reader card list:', err);
}
return [];
}
/**
* 设置当前读者证
* @param {Object} card - 读者证信息
*/
export function setCurrentReaderCard(card) {
uni.setStorageSync(STORAGE_KEYS.CURRENT_READER_CARD, card);
}
/**
* 清除读者证相关缓存
*/
export function clearReaderCardCache() {
uni.removeStorageSync(STORAGE_KEYS.CURRENT_READER_CARD);
uni.removeStorageSync(STORAGE_KEYS.READER_CARD_LIST);
}
Loading…
Cancel
Save