2023-04-05 20:40:17 +01:00
|
|
|
import { StorageBackend } from "@types";
|
2023-03-17 21:58:37 +00:00
|
|
|
import { ReactNative as RN } from "@metro/common";
|
2023-04-05 20:40:17 +01:00
|
|
|
import { MMKVManager, FileManager } from "@lib/native";
|
2023-02-06 08:48:55 +01:00
|
|
|
|
|
|
|
|
export const createMMKVBackend = (store: string): StorageBackend => ({
|
2023-02-26 01:34:16 +01:00
|
|
|
get: async () => JSON.parse((await MMKVManager.getItem(store)) ?? "{}"),
|
|
|
|
|
set: (data) => MMKVManager.setItem(store, JSON.stringify(data)),
|
2023-02-06 08:48:55 +01:00
|
|
|
});
|
|
|
|
|
|
2023-02-06 09:27:20 +01:00
|
|
|
export const createFileBackend = (file: string): StorageBackend => {
|
2023-03-17 21:58:37 +00:00
|
|
|
const filePathFixer: (file: string) => string = RN.Platform.select({
|
|
|
|
|
default: (f) => f,
|
2023-04-08 14:10:46 -04:00
|
|
|
ios: (f) => FileManager.saveFileToGallery ? f : `Documents/${f}`,
|
2023-03-17 21:58:37 +00:00
|
|
|
});
|
|
|
|
|
|
2023-02-26 01:34:16 +01:00
|
|
|
let created: boolean;
|
|
|
|
|
return {
|
|
|
|
|
get: async () => {
|
2023-04-05 20:40:17 +01:00
|
|
|
const path = `${FileManager.getConstants().DocumentsDirPath}/${file}`;
|
|
|
|
|
if (!created && !(await FileManager.fileExists(path))) return (created = true), FileManager.writeFile("documents", filePathFixer(file), "{}", "utf8");
|
|
|
|
|
return JSON.parse(await FileManager.readFile(path, "utf8"));
|
2023-02-26 01:34:16 +01:00
|
|
|
},
|
2023-04-05 22:18:22 +02:00
|
|
|
set: async (data) => void await FileManager.writeFile("documents", filePathFixer(file), JSON.stringify(data), "utf8"),
|
2023-02-26 01:34:16 +01:00
|
|
|
};
|
2023-04-05 22:18:22 +02:00
|
|
|
};
|