summaryrefslogtreecommitdiff
path: root/web/source/settings/lib/query/query-modifiers.ts
blob: a80784d04bd88c3e1089da730a742fe55b2be395 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
/*
	GoToSocial
	Copyright (C) GoToSocial Authors admin@gotosocial.org
	SPDX-License-Identifier: AGPL-3.0-or-later

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU Affero General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU Affero General Public License for more details.

	You should have received a copy of the GNU Affero General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

import { gtsApi } from "./gts-api";

import type { 
	Action,
	CacheMutation,
} from "../types/query";

import { NoArg } from "../types/query";

/**
 * Cache mutation creator for pessimistic updates.
 * 
 * Feed it a function that you want to perform on the
 * given draft and updated data, using the given parameters.
 * 
 * https://redux-toolkit.js.org/rtk-query/api/createApi#onquerystarted
 * https://redux-toolkit.js.org/rtk-query/usage/manual-cache-updates#pessimistic-updates
 */
function makeCacheMutation(action: Action): CacheMutation {
	return function cacheMutation(
		queryName: string | ((_arg: any) => string),
		{ key } = {},
	) {
		return {
			onQueryStarted: async(mutationData, { dispatch, queryFulfilled }) => {
				// queryName might be a function that returns
				// a query name; trigger it if so. The returned
				// queryName has to match one of the API endpoints
				// we've defined. So if we have endpoints called
				// (for example) `instanceV1` and `getPosts` then
				// the queryName provided here has to line up with
				// one of those in order to actually do anything.
				if (typeof queryName !== "string") {
					queryName = queryName(mutationData);
				}
				
				if (queryName == "") {
					throw (
						"provided queryName resolved to an empty string;" +
						"double check your mutation definition!"
					);
				}

				try {
					// Wait for the mutation to finish (this
					// is why it's a pessimistic update).
					const { data: newData } = await queryFulfilled;	
					
					// In order for `gtsApi.util.updateQueryData` to
					// actually do something within a dispatch, the
					// first two arguments passed into it have to line
					// up with arguments that were used earlier to
					// fetch the data whose cached version we're now
					// trying to modify.
					// 
					// So, if we earlier fetched all reports with
					// queryName `getReports`, and arg `undefined`,
					// then we now need match those parameters in
					// `updateQueryData` in order to modify the cache.
					//
					// If you pass something like `null` or `""` here
					// instead, then the cache will not get modified!
					// Redux will just quietly discard the thunk action.
					dispatch(
						gtsApi.util.updateQueryData(queryName as any, NoArg, (draft) => {
							if (key != undefined && typeof key !== "string") {
								key = key(draft, newData);
							}
							action(draft, newData, { key });
						})
					);
				} catch (e) {
					// eslint-disable-next-line no-console
					console.error(`rolling back pessimistic update of ${queryName}: ${JSON.stringify(e)}`);
				}
			}
		};
	};
}

/**
 * 
 */
const replaceCacheOnMutation: CacheMutation = makeCacheMutation((draft, newData, _params) => {	
	Object.assign(draft, newData);
});

const appendCacheOnMutation: CacheMutation = makeCacheMutation((draft, newData, _params) => {
	draft.push(newData);
});

const spliceCacheOnMutation: CacheMutation = makeCacheMutation((draft, _newData, { key }) => {
	if (key === undefined) {
		throw ("key undefined");
	}
	
	draft.splice(key, 1);
});

const updateCacheOnMutation: CacheMutation = makeCacheMutation((draft, newData, { key }) => {
	if (key === undefined) {
		throw ("key undefined");
	}

	if (typeof key !== "string") {
		key = key(draft, newData);
	}
	
	draft[key] = newData;
});

const removeFromCacheOnMutation: CacheMutation = makeCacheMutation((draft, newData, { key }) => {
	if (key === undefined) {
		throw ("key undefined");
	}

	if (typeof key !== "string") {
		key = key(draft, newData);
	}
	
	delete draft[key];
});


export {
	replaceCacheOnMutation,
	appendCacheOnMutation,
	spliceCacheOnMutation,
	updateCacheOnMutation,
	removeFromCacheOnMutation,
};