lib.js (2350B)
1 /* 2 GoToSocial 3 Copyright (C) GoToSocial Authors admin@gotosocial.org 4 SPDX-License-Identifier: AGPL-3.0-or-later 5 6 This program is free software: you can redistribute it and/or modify 7 it under the terms of the GNU Affero General Public License as published by 8 the Free Software Foundation, either version 3 of the License, or 9 (at your option) any later version. 10 11 This program is distributed in the hope that it will be useful, 12 but WITHOUT ANY WARRANTY; without even the implied warranty of 13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 GNU Affero General Public License for more details. 15 16 You should have received a copy of the GNU Affero General Public License 17 along with this program. If not, see <http://www.gnu.org/licenses/>. 18 */ 19 20 "use strict"; 21 22 const syncpipe = require("syncpipe"); 23 const base = require("./base"); 24 25 module.exports = { 26 unwrapRes(res) { 27 if (res.error != undefined) { 28 throw res.error; 29 } else { 30 return res.data; 31 } 32 }, 33 domainListToObject: (data) => { 34 // Turn flat Array into Object keyed by block's domain 35 return syncpipe(data, [ 36 (_) => _.map((entry) => [entry.domain, entry]), 37 (_) => Object.fromEntries(_) 38 ]); 39 }, 40 replaceCacheOnMutation: makeCacheMutation((draft, newData) => { 41 Object.assign(draft, newData); 42 }), 43 appendCacheOnMutation: makeCacheMutation((draft, newData) => { 44 draft.push(newData); 45 }), 46 spliceCacheOnMutation: makeCacheMutation((draft, newData, { key }) => { 47 draft.splice(key, 1); 48 }), 49 updateCacheOnMutation: makeCacheMutation((draft, newData, { key }) => { 50 draft[key] = newData; 51 }), 52 removeFromCacheOnMutation: makeCacheMutation((draft, newData, { key }) => { 53 delete draft[key]; 54 }), 55 editCacheOnMutation: makeCacheMutation((draft, newData, { update }) => { 56 update(draft, newData); 57 }) 58 }; 59 60 // https://redux-toolkit.js.org/rtk-query/usage/manual-cache-updates#pessimistic-updates 61 function makeCacheMutation(action) { 62 return function cacheMutation(queryName, { key, findKey, arg, ...opts } = {}) { 63 return { 64 onQueryStarted: (_, { dispatch, queryFulfilled }) => { 65 queryFulfilled.then(({ data: newData }) => { 66 dispatch(base.util.updateQueryData(queryName, arg, (draft) => { 67 if (findKey != undefined) { 68 key = findKey(draft, newData); 69 } 70 action(draft, newData, { key, ...opts }); 71 })); 72 }); 73 } 74 }; 75 }; 76 }