this repo has no description
at main 114 lines 2.6 kB view raw
1import { api } from './api'; 2import pmem from './pmem'; 3import store from './store'; 4 5const FETCH_MAX_AGE = 1000 * 60; // 1 minute 6const MAX_AGE = 24 * 60 * 60 * 1000; // 1 day 7 8export const fetchLists = pmem( 9 async () => { 10 const { masto } = api(); 11 const lists = await masto.v1.lists.list(); 12 lists.sort((a, b) => a.title.localeCompare(b.title)); 13 14 if (lists.length) { 15 setTimeout(() => { 16 // Save to local storage, with saved timestamp 17 store.account.set('lists', { 18 lists, 19 updatedAt: Date.now(), 20 }); 21 }, 1); 22 } 23 24 return lists; 25 }, 26 { 27 maxAge: FETCH_MAX_AGE, 28 }, 29); 30 31export async function getLists() { 32 try { 33 const { lists, updatedAt } = store.account.get('lists') || {}; 34 if (!lists?.length) return await fetchLists(); 35 if (Date.now() - updatedAt > MAX_AGE) { 36 // Stale-while-revalidate 37 fetchLists(); 38 return lists; 39 } 40 return lists; 41 } catch (e) { 42 return []; 43 } 44} 45 46export const fetchList = pmem( 47 (id) => { 48 const { masto } = api(); 49 return masto.v1.lists.$select(id).fetch(); 50 }, 51 { 52 maxAge: FETCH_MAX_AGE, 53 }, 54); 55 56export async function getList(id) { 57 const { lists } = store.account.get('lists') || {}; 58 console.log({ lists }); 59 if (lists?.length) { 60 const theList = lists.find((l) => l.id === id); 61 if (theList) return theList; 62 } 63 try { 64 return fetchList(id); 65 } catch (e) { 66 return null; 67 } 68} 69 70export async function getListTitle(id) { 71 const list = await getList(id); 72 return list?.title || ''; 73} 74 75export function addListStore(list) { 76 const { lists } = store.account.get('lists') || {}; 77 if (lists?.length) { 78 lists.push(list); 79 lists.sort((a, b) => a.title.localeCompare(b.title)); 80 store.account.set('lists', { 81 lists, 82 updatedAt: Date.now(), 83 }); 84 } 85} 86 87export function updateListStore(list) { 88 const { lists } = store.account.get('lists') || {}; 89 if (lists?.length) { 90 const index = lists.findIndex((l) => l.id === list.id); 91 if (index !== -1) { 92 lists[index] = list; 93 lists.sort((a, b) => a.title.localeCompare(b.title)); 94 store.account.set('lists', { 95 lists, 96 updatedAt: Date.now(), 97 }); 98 } 99 } 100} 101 102export function deleteListStore(listID) { 103 const { lists } = store.account.get('lists') || {}; 104 if (lists?.length) { 105 const index = lists.findIndex((l) => l.id === listID); 106 if (index !== -1) { 107 lists.splice(index, 1); 108 store.account.set('lists', { 109 lists, 110 updatedAt: Date.now(), 111 }); 112 } 113 } 114}