diff --git a/denops/traqvim/model.ts b/denops/traqvim/model.ts index b33350d..7478397 100644 --- a/denops/traqvim/model.ts +++ b/denops/traqvim/model.ts @@ -15,32 +15,53 @@ export type channelMessageOptions = { order?: "asc" | "desc"; }; +// TODO: ↓チャンネル周りはclassに分離しても良いかも +const channelMapCache: Map = new Map(); + +const getChannelMapCache = () => { + return channelMapCache; +}; + +const makeChannelMapCache = async () => { + const channelsRes = await api.api.getChannels(); + const channels = channelsRes.data; + channels.public.forEach((channel: traq.Channel) => { + setCacheChannel(channel); + }); +}; + +const setCacheChannel = (channel: traq.Channel) => { + channelMapCache.set(channel.id, channel); +}; + +const getCacheChannel = (channelId: string): traq.Channel | undefined => { + return channelMapCache.get(channelId); +}; + const makeChannelPath = ( - channels: traq.Channel[], - channel: traq.Channel, + channelCache: Map, + channelId: string, ): string => { - const parentChannel = channels.find((c: traq.Channel) => - c.id === channel.parentId - ); - if (!parentChannel) { - return "#" + channel.name; + if (getCacheChannel(channelId) === undefined) { + throw new Error("channel not found"); + } + const parentId = getCacheChannel(channelId)?.parentId; + if (parentId === null || parentId === undefined) { + return "#" + getCacheChannel(channelId)?.name; } else { - return makeChannelPath(channels, parentChannel) + "/" + channel.name; + return ( + makeChannelPath(channelCache, parentId) + "/" + + getCacheChannel(channelId)?.name + ); } }; // channelUUIDに対応するchannelPathを生成する export const channelPath = async (channelUUID: string): Promise => { - const channelsRes = await api.api.getChannels(); - const publicChannels = channelsRes.data.public; - const channel = publicChannels.find((c: traq.Channel) => - c.id === channelUUID - ); - if (!channel) { - return ""; - } else { - return makeChannelPath(publicChannels, channel); + if (getCacheChannel(channelUUID) === undefined) { + await makeChannelMapCache(); } + return makeChannelPath(getChannelMapCache(), channelUUID); }; // 自身のユーザー情報を取得する @@ -138,11 +159,16 @@ export const channelTimeline = async ( export const channelsRecursive = async (): Promise => { const channelsRes = await api.api.getChannels(); const publicChannels = channelsRes.data.public; + publicChannels.forEach((channel: traq.Channel) => { + if (getCacheChannel(channel.id) === undefined) { + setCacheChannel(channel); + } + }); const channelsConverted: Channel[] = publicChannels.map( (channel: traq.Channel) => { return { ...channel, - path: makeChannelPath(publicChannels, channel), + path: makeChannelPath(getChannelMapCache(), channel.id), }; }, );