forked from cloud-annotations/docusaurus-openapi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpersistanceMiddleware.ts
More file actions
66 lines (56 loc) · 2.09 KB
/
persistanceMiddleware.ts
File metadata and controls
66 lines (56 loc) · 2.09 KB
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
/* ============================================================================
* Copyright (c) Cloud Annotations
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* ========================================================================== */
import { Middleware } from "@reduxjs/toolkit";
import { setAuthData, setSelectedAuth } from "./Authorization/slice";
import { setServer, setServerVariable } from "./Server/slice";
import { createStorage, hashArray } from "./storage-utils";
import { AppDispatch, RootState } from "./store";
import { ThemeConfig } from "../../types";
export function createPersistanceMiddleware(options: ThemeConfig["api"]) {
const persistanceMiddleware: Middleware<{}, RootState, AppDispatch> =
(storeAPI) => (next) => (action) => {
const result = next(action);
const state = storeAPI.getState();
const storage = createStorage(options?.authPersistance);
if (setAuthData.match(action)) {
for (const [key, value] of Object.entries(state.auth.data)) {
if (Object.values(value).filter(Boolean).length > 0) {
storage.setItem(key, JSON.stringify(value));
} else {
storage.removeItem(key);
}
}
}
if (setSelectedAuth.match(action)) {
if (state.auth.selected) {
storage.setItem(
hashArray(Object.keys(state.auth.options)),
state.auth.selected
);
}
}
if (setServer.match(action)) {
if (state.server.value?.url) {
// FIXME What to use as key?
storage.setItem(
`docusaurus.openapi.server/${state.server.value?.url}`,
JSON.stringify(state.server.value)
);
}
}
if (setServerVariable.match(action)) {
if (state.server.value?.url) {
storage.setItem(
`docusaurus.openapi.server/${state.server.value?.url}`,
JSON.stringify(state.server.value)
);
}
}
return result;
};
return persistanceMiddleware;
}