Browse Source

feat: 缓存修改

tall
wally 4 years ago
parent
commit
63e1f0d81f
  1. 3
      CHANGELOG.md
  2. 2
      src/apis/tall.js
  3. 4
      src/main.js
  4. 12
      src/pages/index/index.vue
  5. 13
      src/pages/test/test.vue
  6. 53
      src/utils/cache.js
  7. 32
      src/utils/cacheAndRequest.js
  8. 2
      src/utils/indexedDB.js
  9. 5
      src/utils/request.js
  10. 2
      src/utils/storage.js
  11. 8
      src/utils/tall.js

3
CHANGELOG.md

@ -1,4 +1,4 @@
# 0.1.0 (2021-08-16) # 0.1.0 (2021-08-17)
### 🌟 新功能 ### 🌟 新功能
范围|描述|commitId 范围|描述|commitId
@ -55,6 +55,7 @@
范围|描述|commitId 范围|描述|commitId
--|--|-- --|--|--
- | calendar注释 | a2ec112 - | calendar注释 | a2ec112
- | indexedDB.js格式整理 | b0d3a36
- | 代码审查 | d75134c - | 代码审查 | d75134c
- | 代码格式细节调整 | cb2532b - | 代码格式细节调整 | cb2532b
- | 任务快捷方式图标增加 | 4aba872 - | 任务快捷方式图标增加 | 4aba872

2
src/apis/tall.js

@ -1,5 +1,5 @@
const apiUrl = process.env.VUE_APP_API_URL; const apiUrl = process.env.VUE_APP_API_URL;
const tall = `${apiUrl}/tall3/v3.0`; export const tall = `${apiUrl}/tall3/v3.0`;
const install = (Vue, vm) => { const install = (Vue, vm) => {
vm.$u.api = { ...vm.$u.api } || {}; vm.$u.api = { ...vm.$u.api } || {};

4
src/main.js

@ -12,8 +12,8 @@ import AlloyFinger from 'alloyfinger';
import AlloyFingerPlugin from 'alloyfinger/vue/alloy_finger_vue'; import AlloyFingerPlugin from 'alloyfinger/vue/alloy_finger_vue';
Vue.use(AlloyFingerPlugin, { AlloyFinger }); Vue.use(AlloyFingerPlugin, { AlloyFinger });
// indexedDB // indexedDB
import indexedDB from '@/utils/indexedDB'; // import indexedDB from '@/utils/indexedDB';
Vue.use(indexedDB); // Vue.use(indexedDB);
//#endif //#endif
Vue.config.productionTip = false; Vue.config.productionTip = false;

12
src/pages/index/index.vue

@ -52,13 +52,15 @@ export default {
...mapMutations('project', ['setProjects', 'setDotList']), ...mapMutations('project', ['setProjects', 'setDotList']),
// //
async getProjects(start = this.$moment().startOf('day').valueOf(), end = this.$moment().endOf('day').valueOf()) { getProjects(start = this.$moment().startOf('day').valueOf(), end = this.$moment().endOf('day').valueOf()) {
try { // const data = await this.$u.api.getProjects(start, end);
const data = await this.$u.api.getProjects(start, end); this.$t.$q.getProjects(start, end, (err, data) => {
this.setProjects(data); if (err) {
} catch (error) {
console.error('error: ', error); console.error('error: ', error);
} else {
this.setProjects(data);
} }
});
}, },
/** /**

13
src/pages/test/test.vue

@ -12,15 +12,16 @@
<script> <script>
export default { export default {
created() { created() {
// this.getProjects(this.$moment().startOf('day').valueOf(), this.$moment().endOf('day').valueOf()); // this.$t.$q.getProjects(this.$moment().startOf('day').valueOf(), this.$moment().endOf('day').valueOf(), (err, data) => {
// if (err) {
// console.error(err);
// } else {
// console.log('data: ' + data);
// }
// });
}, },
methods: { methods: {
async getProjects(startTime, endTime) {
const data = await this.$t.$q.getProjects(startTime, endTime);
console.log('data: ', data);
},
add() { add() {
this.$db.create('projects', { id: '124', sex: ' man' }); this.$db.create('projects', { id: '124', sex: ' man' });
}, },

53
src/utils/cache.js

@ -1,8 +1,9 @@
export const filter = { export const filter = {
/** /**
* 过滤获取到的数据 * 过滤获取到的数据 根据开始截止时间
* @param {number} start * @param {object} data 缓存拿到的数据
* @param {number} end * @param {number} start ms
* @param {number} end ms
* @returns * @returns
*/ */
projects(data, start, end) { projects(data, start, end) {
@ -13,20 +14,50 @@ export const filter = {
export default { export default {
/** /**
* 获取项目列表 * 项目列表某天的 获取
* @param {number} startTime * @param {number} startTime
* @param {number} endTime * @param {number} endTime
* @returns * @returns
*/ */
async getProjects(startTime, endTime) { async getProjectsByDay(startTime, endTime) {
try { try {
let data = null; const data = await uni.$t.storage.getStorage('projects');
// #ifdef H5 return filter.projects(JSON.parse(data), startTime, endTime);
data = await window.vm.$db.find('projects');
// #endif
return filter.projects(data, startTime, endTime);
} catch (error) { } catch (error) {
throw new Error(error); console.log('error: ', error);
return [];
}
},
/**
* 项目列表
* @param {array} data
*/
putProjects(data) {
try {
if (!data || !data.length) return; // 服务端没数据不做操作
let locals = JSON.parse(uni.$t.storage.getStorageSync('projects')) || [];
if (!locals || !locals.length) {
// 本地没数据
locals = data || [];
} else {
// 本地有数据
data.forEach(item => {
let localData = locals.find(local => item.id === local.id);
if (localData) {
// 有相同数据 就用新的data里的数据
localData = item;
} else {
// 没有就直接存本地
locals.push(item);
}
});
}
uni.$t.storage.setStorage('projects', locals);
} catch (error) {
console.error('error: ', error);
uni.$t.storage.setStorage('projects', []);
} }
}, },
}; };

32
src/utils/cacheAndRequest.js

@ -1,28 +1,46 @@
/**
* 等待token执行api
* 没有token 就延时执行自己 直到有了token在请求
* @param {function} requestFn 执行请求的函数
*/
export const waitTokenRequest = requestFn => {
if (!requestFn || typeof requestFn !== 'function') throw new Error(`requestFn must be a function`);
if (uni.$t.storage.getStorageSync(uni.$t.app.tokenKey)) {
requestFn();
} else {
setTimeout(() => waitTokenRequest(requestFn), 10);
}
};
export default { export default {
/** /**
* 获取项目列表 * 获取项目列表
* @param {number} startTime 起始时间 * @param {number} startTime 起始时间
* @param {number} endTime 截止时间 * @param {number} endTime 截止时间
*/ */
getProjects(startTime, endTime) { getProjects(startTime, endTime, fn) {
return new Promise((resolve, reject) => {
let remote = false; let remote = false;
// 有缓存 且 服务端数据未返回 就先返回缓存 // 有缓存 且 服务端数据未返回 就先返回缓存
uni.$t.cache uni.$t.cache
.getProjects(startTime, endTime) .getProjectsByDay(startTime, endTime)
.then(data => { .then(data => {
!remote && resolve(data); // console.log('cache data: ', data);
!remote && fn(null, data);
}) })
.catch(err => !remote && reject(err)); .catch(err => !remote && fn(err));
waitTokenRequest(() => {
// 拿到api数据后 再用api的数据 // 拿到api数据后 再用api的数据
uni.$u.api uni.$u.api
.getProjects(startTime, endTime) .getProjects(startTime, endTime)
.then(data => { .then(data => {
// console.log('api data: ', data);
remote = true; remote = true;
resolve(data); fn(null, data);
// 存api到cache里
uni.$t.cache.putProjects(data);
}) })
.catch(err => reject(err)); .catch(err => fn(err));
}); });
}, },
}; };

2
src/utils/indexedDB.js

@ -137,7 +137,7 @@ export const curriedUpdate = curry(update);
export const curriedIndex = curry(createIndexAndFind); export const curriedIndex = curry(createIndexAndFind);
const install = Vue => { const install = Vue => {
Vue.prototype.$db = {}; uni.$db = Vue.prototype.$db = {};
Vue.prototype.$db.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB; Vue.prototype.$db.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
const request = Vue.prototype.$db.indexedDB.open(name, Date.now()); // IDBRequest 对象 const request = Vue.prototype.$db.indexedDB.open(name, Date.now()); // IDBRequest 对象
request.onerror = error => console.error('打开数据库失败', error); request.onerror = error => console.error('打开数据库失败', error);

5
src/utils/request.js

@ -11,8 +11,9 @@ const install = (Vue, vm) => {
// 请求拦截部分,如配置,每次请求前都会执行 // 请求拦截部分,如配置,每次请求前都会执行
Vue.prototype.$u.http.interceptor.request = config => { Vue.prototype.$u.http.interceptor.request = config => {
if (vm.$store.state.user.token) { const token = vm.$store.state.user.token || uni.$t.storage.getStorageSync(uni.$t.app.tokenKey);
config.header.Authorization = `Bearer ${vm.$store.state.user.token}`; if (token) {
config.header.Authorization = `Bearer ${token}`;
} }
return config; return config;

2
src/utils/storage.js

@ -67,7 +67,7 @@ export default {
resolve(res.data); resolve(res.data);
}, },
fail(error) { fail(error) {
reject(`数据${key}获取失败, error: ${error}`); reject(`数据${key}获取失败, error: ${error.errMsg}`);
}, },
}); });
}); });

8
src/utils/tall.js

@ -6,8 +6,8 @@ import storage from '@/utils/storage.js';
import time from '@/utils/time.js'; import time from '@/utils/time.js';
import ui from '@/utils/ui.js'; import ui from '@/utils/ui.js';
import upload from '@/utils/upload.js'; import upload from '@/utils/upload.js';
// import cacheAndRequest from '@/utils/cacheAndRequest.js'; import cacheAndRequest from '@/utils/cacheAndRequest.js';
// import cache from '@/utils/cache.js'; import cache from '@/utils/cache.js';
const gateway = process.env.VUE_APP_API_URL; const gateway = process.env.VUE_APP_API_URL;
@ -21,8 +21,8 @@ const $t = {
ui, // ui界面提示相关 ui, // ui界面提示相关
chooseAndUpload: upload.chooseAndUpload, // 选择并上传单个文件相关的封装 chooseAndUpload: upload.chooseAndUpload, // 选择并上传单个文件相关的封装
domain: `${gateway}/defaultwbs`, domain: `${gateway}/defaultwbs`,
// cache, // 本地存储相关 cache, // 本地存储相关
// $q: cacheAndRequest, $q: cacheAndRequest,
}; };
uni.$t = $t; uni.$t = $t;

Loading…
Cancel
Save