From 1ae2da84fe7b93920a8e21cd06549cf57dc2bc0c Mon Sep 17 00:00:00 2001 From: redstonekasi Date: Mon, 6 Feb 2023 09:27:20 +0100 Subject: [PATCH] [Backends] Create if file does not exist --- src/lib/storage/backends.ts | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/src/lib/storage/backends.ts b/src/lib/storage/backends.ts index d8ebb1e..9060709 100644 --- a/src/lib/storage/backends.ts +++ b/src/lib/storage/backends.ts @@ -16,9 +16,15 @@ export const createMMKVBackend = (store: string): StorageBackend => ({ set: (data) => MMKVManager.setItem(store, JSON.stringify(data)), }); -export const createFileBackend = (file: string): StorageBackend => ({ - get: async function() { - return JSON.parse((await DCDFileManager.readFile(`${DCDFileManager.getConstants().DocumentsDirPath}/${file}`, "utf8")) ?? "{}"); - }, - set: (data) => void DCDFileManager.writeFile("documents", filePathFixer(file), JSON.stringify(data), "utf8"), -}); +export const createFileBackend = (file: string): StorageBackend => { + let created: boolean; + return { + get: async function() { + const path = `${DCDFileManager.getConstants().DocumentsDirPath}/${file}`; + if (!created && !await DCDFileManager.fileExists(path)) + return (created = true, DCDFileManager.writeFile("documents", filePathFixer(file), "{}", "utf8")); + return JSON.parse((await DCDFileManager.readFile(path, "utf8"))); + }, + set: (data) => void DCDFileManager.writeFile("documents", filePathFixer(file), JSON.stringify(data), "utf8"), + }; +};