初期値にデフォルト値を挿入する & JSON.parse/stringify操作をdeepcopyに

This commit is contained in:
tamaina 2022-01-09 02:55:27 +09:00
parent dfa9359555
commit dbd46fbeb5
4 changed files with 43 additions and 26 deletions

View file

@ -55,6 +55,7 @@
"css-loader": "6.5.1",
"cssnano": "5.0.14",
"date-fns": "2.28.0",
"deepcopy": "2.1.0",
"escape-regexp": "0.0.1",
"eslint": "8.6.0",
"eslint-plugin-vue": "8.2.0",

View file

@ -4,6 +4,7 @@ import { api } from './os';
import { get, set } from './scripts/idb-proxy';
import { defaultStore } from './store';
import { stream } from './stream';
import * as deepcopy from 'deepcopy';
// SafariがBroadcastChannel未実装なのでライブラリを使う
import { BroadcastChannel } from 'broadcast-channel';
@ -20,7 +21,7 @@ type ArrayElement<A> = A extends readonly (infer T)[] ? T : never;
type PizzaxChannelMessage<T extends StateDef> = {
where: 'device' | 'deviceAccount';
key: keyof T;
value: T[keyof T];
value: T[keyof T]['default'];
userId?: string;
};
@ -38,8 +39,8 @@ export class Storage<T extends StateDef> {
public readonly def: T;
// TODO: これが実装されたらreadonlyにしたい: https://github.com/microsoft/TypeScript/issues/37487
public readonly state = {} as State<T>;
public readonly reactiveState = {} as ReactiveState<T>;
public readonly state: State<T>;
public readonly reactiveState: ReactiveState<T>;
private pizzaxChannel: BroadcastChannel<PizzaxChannelMessage<T>>;
@ -63,6 +64,14 @@ export class Storage<T extends StateDef> {
this.pizzaxChannel = new BroadcastChannel(`pizzax::${key}`);
this.state = {} as State<T>;
this.reactiveState = {} as ReactiveState<T>;
for (const [k, v] of Object.entries(def) as [keyof T, T[keyof T]['default']][]) {
this.state[k] = v.default;
this.reactiveState[k] = ref(v.default);
}
this.ready = this.init();
this.loaded = this.ready.then(() => this.load());
}
@ -74,28 +83,24 @@ export class Storage<T extends StateDef> {
const deviceAccountState = $i ? await get(this.deviceAccountStateKeyName) || {} : {};
const registryCache = $i ? await get(this.registryCacheKeyName) || {} : {};
for (const [k, v] of Object.entries(this.def) as [keyof T, T[keyof T]][]) {
for (const [k, v] of Object.entries(this.def) as [keyof T, T[keyof T]['default']][]) {
if (v.where === 'device' && Object.prototype.hasOwnProperty.call(deviceState, k)) {
this.state[k] = deviceState[k];
this.reactiveState[k].value = this.state[k] = deviceState[k];
} else if (v.where === 'account' && $i && Object.prototype.hasOwnProperty.call(registryCache, k)) {
this.state[k] = registryCache[k];
this.reactiveState[k].value = this.state[k] = registryCache[k];
} else if (v.where === 'deviceAccount' && Object.prototype.hasOwnProperty.call(deviceAccountState, k)) {
this.state[k] = deviceAccountState[k];
this.reactiveState[k].value = this.state[k] = deviceAccountState[k];
} else {
this.state[k] = v.default;
this.reactiveState[k].value = this.state[k] = v.default;
if (_DEV_) console.log('Use default value', k, v.default);
}
}
for (const [k, v] of Object.entries(this.state) as [keyof T, T[keyof T]][]) {
this.reactiveState[k] = ref(v);
}
this.pizzaxChannel.addEventListener('message', ({ where, key, value, userId }) => {
// アカウント変更すればunisonReloadが効くため、このreturnが発火することは
// まずないと思うけど一応弾いておく
if (where === 'deviceAccount' && !($i && userId !== $i.id)) return;
this.state[key] = value;
this.reactiveState[key].value = value;
this.reactiveState[key].value = this.state[key] = value;
});
if ($i) {
@ -103,8 +108,7 @@ export class Storage<T extends StateDef> {
connection?.on('registryUpdated', ({ scope, key, value }: { scope?: string[], key: keyof T, value: T[typeof key]['default'] }) => {
if (!scope || scope.length !== 2 || scope[0] !== 'client' || scope[1] !== this.key || this.state[key] === value) return;
this.state[key] = value;
this.reactiveState[key].value = value;
this.reactiveState[key].value = this.state[key] = value;
this.addIdbSetJob(async () => {
const cache = await get(this.registryCacheKeyName);
@ -126,16 +130,14 @@ export class Storage<T extends StateDef> {
api('i/registry/get-all', { scope: ['client', this.key] })
.then(kvs => {
const cache = {};
for (const [k, v] of Object.entries(this.def)) {
const cache: Partial<T> = {};
for (const [k, v] of Object.entries(this.def) as [keyof T, T[keyof T]['default']][]) {
if (v.where === 'account') {
if (Object.prototype.hasOwnProperty.call(kvs, k)) {
this.state[k as keyof T] = kvs[k];
this.reactiveState[k as keyof T].value = kvs[k as string];
cache[k] = kvs[k];
this.reactiveState[k].value = this.state[k] = (kvs as Partial<T>)[k];
cache[k] = (kvs as Partial<T>)[k];
} else {
this.state[k as keyof T] = v.default;
this.reactiveState[k].value = v.default;
this.reactiveState[k].value = this.state[k] = v.default;
}
}
}
@ -151,12 +153,13 @@ export class Storage<T extends StateDef> {
}
public set<K extends keyof T>(key: K, value: T[K]['default']): Promise<void> {
const rawValue = JSON.parse(JSON.stringify(value));
// IndexedDBやBroadcastChannelで扱うために単純なオブジェクトにする
// (JSON.parse(JSON.stringify(value))の代わり)
const rawValue = deepcopy(value);
if (_DEV_) console.log('set', key, rawValue, value);
this.state[key] = rawValue;
this.reactiveState[key].value = rawValue;
this.reactiveState[key].value = this.state[key] = rawValue;
return this.addIdbSetJob(async () => {
if (_DEV_) console.log(`set ${key} start`);
@ -192,7 +195,7 @@ export class Storage<T extends StateDef> {
await set(this.registryCacheKeyName, cache);
await api('i/registry/set', {
scope: ['client', this.key],
key: key,
key: key.toString(),
value: rawValue
});
break;

View file

@ -12,6 +12,7 @@
"target": "es2017",
"module": "esnext",
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
"removeComments": false,
"noLib": false,
"strict": true,

View file

@ -2097,6 +2097,13 @@ deep-is@^0.1.3:
resolved "https://registry.yarnpkg.com/deep-is/-/deep-is-0.1.3.tgz#b369d6fb5dbc13eecf524f91b070feedc357cf34"
integrity sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ=
deepcopy@2.1.0:
version "2.1.0"
resolved "https://registry.yarnpkg.com/deepcopy/-/deepcopy-2.1.0.tgz#2deb0dd52d079c2ecb7924b640a7c3abd4db1d6d"
integrity sha512-8cZeTb1ZKC3bdSCP6XOM1IsTczIO73fdqtwa2B0N15eAz7gmyhQo+mc5gnFuulsgN3vIQYmTgbmQVKalH1dKvQ==
dependencies:
type-detect "^4.0.8"
define-properties@^1.1.2, define-properties@^1.1.3:
version "1.1.3"
resolved "https://registry.yarnpkg.com/define-properties/-/define-properties-1.1.3.tgz#cf88da6cbee26fe6db7094f61d870cbd84cee9f1"
@ -5934,6 +5941,11 @@ type-check@^0.4.0, type-check@~0.4.0:
dependencies:
prelude-ls "^1.2.1"
type-detect@^4.0.8:
version "4.0.8"
resolved "https://registry.yarnpkg.com/type-detect/-/type-detect-4.0.8.tgz#7646fb5f18871cfbb7749e69bd39a6388eb7450c"
integrity sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==
type-fest@^0.20.2:
version "0.20.2"
resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.20.2.tgz#1bf207f4b28f91583666cb5fbd327887301cd5f4"