From d9b4ba3c5ad7cff16dda8e1b8cf456533d959657 Mon Sep 17 00:00:00 2001 From: tamaina Date: Wed, 10 Feb 2021 23:50:38 +0900 Subject: [PATCH] :v: --- src/client/sw/lang.ts | 30 ++++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/src/client/sw/lang.ts b/src/client/sw/lang.ts index f0d3544c73..247452de3d 100644 --- a/src/client/sw/lang.ts +++ b/src/client/sw/lang.ts @@ -14,30 +14,32 @@ class SwLang { return prelang; }); - public i18n: Promise> | null = null; - public setLang(newLang: string) { this.lang = Promise.resolve(newLang); set('lang', newLang); return this.fetchLocale(); } - public async fetchLocale() { + public i18n: Promise> | null = null; + + public fetchLocale() { + return this.i18n = this._fetch(); + } + + private async _fetch() { // Service Workerは何度も起動しそのたびにlocaleを読み込むので、CacheStorageを使う - return this.i18n = new Promise(async (res, rej) => { - const localeUrl = `/assets/locales/${await this.lang}.${_VERSION_}.json`; - let localeRes = await caches.match(localeUrl); + const localeUrl = `/assets/locales/${await this.lang}.${_VERSION_}.json`; + let localeRes = await caches.match(localeUrl); - if (!localeRes) { - localeRes = await fetch(localeUrl); - const clone = localeRes?.clone(); - if (!clone?.clone().ok) rej('locale fetching error'); + if (!localeRes) { + localeRes = await fetch(localeUrl); + const clone = localeRes?.clone(); + if (!clone?.clone().ok) Error('locale fetching error'); - caches.open(this.cacheName).then(cache => cache.put(localeUrl, clone)); - } + caches.open(this.cacheName).then(cache => cache.put(localeUrl, clone)); + } - res(new I18n(await localeRes.json())); - }); + return new I18n(await localeRes.json()); } }