a way to persist data

This commit is contained in:
Nikita Galaiko 2023-02-02 16:26:38 +01:00
parent d77198638e
commit b42db79501
No known key found for this signature in database
GPG Key ID: EBAB54E845BA519D
7 changed files with 70 additions and 1 deletions

View File

@ -16,7 +16,7 @@ tauri-build = { version = "1.2", features = [] }
[dependencies]
serde_json = "1.0"
serde = { version = "1.0", features = ["derive"] }
tauri = { version = "1.2", features = ["dialog-open", "window-start-dragging"] }
tauri = { version = "1.2", features = ["dialog-open", "fs-create-dir", "fs-exists", "fs-read-file", "fs-write-file", "path-all", "window-start-dragging"] }
tauri-plugin-fs-watch = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "dev" }
[features]

0
src-tauri/projects.json Normal file
View File

View File

@ -20,6 +20,17 @@
"window": {
"all": false,
"startDragging": true
},
"path": {
"all": true
},
"fs": {
"all": false,
"readFile": true,
"writeFile": true,
"exists": true,
"createDir": true,
"scope": ["$APPLOCALDATA/databases", "$APPLOCALDATA/databases/*.json"]
}
},
"bundle": {

34
src/lib/database.ts Normal file
View File

@ -0,0 +1,34 @@
import {
exists,
readTextFile,
BaseDirectory,
writeTextFile,
createDir,
} from "@tauri-apps/api/fs";
import { join } from "@tauri-apps/api/path";
const options = {
dir: BaseDirectory.AppLocalData,
};
export const json = async <T extends any>(filename: string) => {
await createDir("databases", { ...options, recursive: true });
const path = await join("databases", filename);
return {
read: async (): Promise<T | undefined> => {
const isExists = await exists(path, {
dir: BaseDirectory.AppLocalData,
});
if (!isExists) {
return undefined;
} else {
const contents = await readTextFile(path, options);
return JSON.parse(contents) as T;
}
},
write: async (value: T): Promise<void> => {
await writeTextFile(path, JSON.stringify(value), options);
},
};
};

View File

@ -1,3 +1,5 @@
export * as tauri from "./tauri";
export * as watch from "./watch";
export * as crdt from "./crdt";
export * as database from "./database";
export * as projects from "./projects";

15
src/lib/projects.ts Normal file
View File

@ -0,0 +1,15 @@
import { database } from "$lib";
import { writable } from "svelte/store";
export type Project = {
id: string;
path: string;
};
export const store = async () => {
const db = await database.json<Project[]>("projects.json");
const fromDisk = await db.read();
const store = writable<Project[]>(fromDisk);
store.subscribe(db.write);
return store;
};

View File

@ -1,3 +1,10 @@
import type { LayoutLoad } from "./$types";
import { projects } from "$lib";
export const ssr = false;
export const prerender = true;
export const csr = true;
export const load: LayoutLoad = () => ({
projects: projects.store(),
});