Merge pull request #3 from laxect/patch-1

Make state and cache configurable.
main
imspace 2022-10-24 00:48:31 +08:00 committed by GitHub
commit 1c202e03fa
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 32 additions and 10 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,
@ -24,6 +24,8 @@ export type Opts = {
exporter: string;
noProgress: boolean;
monitor: boolean;
cache?: Cache;
stateBackend?: StateBackend;
};
export const DEFAULT_OPTS: Opts = {
@ -156,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,
@ -225,7 +223,7 @@ export class App {
const exporters = await this.getExporters();
const fetcher = new BattleFetcher({
cache: new FileCache(this.state.cacheDir),
cache: this.opts.cache ?? new FileCache(this.state.cacheDir),
state: this.state,
});
console.log("Fetching battle list...");

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);
}
}