import { getConversationKey } from "./utils"; let myProfileCache; const profileCache = {}; const groupMembersCache = {}; export default class Service { constructor(config) { this.config = config; } getUserProfile(id) { if (!this.config.getUserProfile) { return Promise.reject(new Error("Method getUserProfile is not defined!")); } if (myProfileCache) { return Promise.resolve(myProfileCache); } return this.config.getUserProfile(id).then(res => { myProfileCache = res; return myProfileCache; }); } getConversationProfile(conversations) { if (!this.config.getConversationProfile) { return Promise.reject( new Error("Method getConversationProfile is not defined!") ); } // 临时存放从缓存取出的数据 const temp = []; for (let i = 0; i < conversations.length; i++) { const conversation = conversations[i]; const key = getConversationKey(conversation); const profile = profileCache[key]; if (profile) { // 缓存中存在的数据,不再查询 conversations.splice(i, 1); temp.push(profile); i--; } } return this.config.getConversationProfile(conversations).then(profiles => { // 对数据进行缓存 profiles.forEach(profile => { if (profile && profile.targetId && profile.conversationType) { const key = getConversationKey(profile); profileCache[key] = profile; } }); // 将之前的临时数据合并 return [...profiles, ...temp]; }); } getGroupMembers(conversation) { if (!this.config.getGroupMembers) { return Promise.reject( new Error("Method getGroupMembers is not defined!") ); } const key = getConversationKey(conversation); if (groupMembersCache[key]) { return Promise.resolve(groupMembersCache[key]); } return this.config.getGroupMembers(conversation).then(res => { console.log(res, "res"); const key = getConversationKey(conversation); if (res) { groupMembersCache[key] = res; return groupMembersCache[key]; } return null; }); } clearMyProfileCache() { myProfileCache = null; } }