feat: Add StateBackend type.

main
ギャラ 2022-10-23 17:25:10 +09:00
parent fa6893eeb3
commit 5a89163ca7
No known key found for this signature in database
GPG Key ID: 686F3411A9823621
2 changed files with 30 additions and 9 deletions

View File

@ -1,6 +1,6 @@
import { getBulletToken, getGToken, loginManually } from "./iksm.ts";
import { MultiProgressBar, Mutex } from "../deps.ts";
import { DEFAULT_STATE, State } from "./state.ts";
import { DEFAULT_STATE, FileStateBackend, State, StateBackend } from "./state.ts";
import {
checkToken,
getBankaraBattleHistories,
@ -25,6 +25,7 @@ export type Opts = {
noProgress: boolean;
monitor: boolean;
cache?: Cache;
stateBackend?: StateBackend;
};
export const DEFAULT_OPTS: Opts = {
@ -157,22 +158,18 @@ type Progress = {
export class App {
state: State = DEFAULT_STATE;
stateBackend: StateBackend;
constructor(public opts: Opts) {
this.stateBackend = opts.stateBackend ?? new FileStateBackend(opts.profilePath);
}
async writeState(newState: State) {
this.state = newState;
const encoder = new TextEncoder();
const data = encoder.encode(JSON.stringify(this.state, undefined, 2));
const swapPath = `${this.opts.profilePath}.swap`;
await Deno.writeFile(swapPath, data);
await Deno.rename(swapPath, this.opts.profilePath);
await this.stateBackend.write(newState);
}
async readState() {
const decoder = new TextDecoder();
try {
const data = await Deno.readFile(this.opts.profilePath);
const json = JSON.parse(decoder.decode(data));
const json = await this.stateBackend.read();
this.state = {
...DEFAULT_STATE,
...json,

View File

@ -24,3 +24,27 @@ export const DEFAULT_STATE: State = {
fileExportPath: "./export",
monitorInterval: 500,
};
export type StateBackend = {
read: () => Promise<State>;
write: (newState: State) => Promise<void>;
};
export class FileStateBackend implements StateBackend {
constructor(private path: string) {}
async read(): Promise<State> {
const decoder = new TextDecoder();
const data = await Deno.readFile(this.path);
const json = JSON.parse(decoder.decode(data));
return json;
}
async write(newState: State): Promise<void> {
const encoder = new TextEncoder();
const data = encoder.encode(JSON.stringify(newState, undefined, 2));
const swapPath = `${this.path}.swap`;
await Deno.writeFile(swapPath, data);
await Deno.rename(swapPath, this.path);
}
}