GoonCord/src/lib/storage/backends.ts

26 lines
1.1 KiB
TypeScript
Raw Normal View History

2023-04-05 20:40:17 +01:00
import { StorageBackend } from "@types";
import { ReactNative as RN } from "@metro/common";
2023-04-05 20:40:17 +01:00
import { MMKVManager, FileManager } from "@lib/native";
export const createMMKVBackend = (store: string): StorageBackend => ({
get: async () => JSON.parse((await MMKVManager.getItem(store)) ?? "{}"),
set: (data) => MMKVManager.setItem(store, JSON.stringify(data)),
});
export const createFileBackend = (file: string): StorageBackend => {
const filePathFixer: (file: string) => string = RN.Platform.select({
default: (f) => f,
ios: (f) => FileManager.saveFileToGallery ? f : `Documents/${f}`,
});
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-04-05 22:18:22 +02:00
set: async (data) => void await FileManager.writeFile("documents", filePathFixer(file), JSON.stringify(data), "utf8"),
};
2023-04-05 22:18:22 +02:00
};