refactor: introduce bindThis decorator to bind this automaticaly
This commit is contained in:
@@ -1,3 +1,5 @@
|
||||
import { bindThis } from '@/decorators.js';
|
||||
|
||||
export class Cache<T> {
|
||||
public cache: Map<string | null, { date: number; value: T; }>;
|
||||
private lifetime: number;
|
||||
@@ -7,6 +9,7 @@ export class Cache<T> {
|
||||
this.lifetime = lifetime;
|
||||
}
|
||||
|
||||
@bindThis
|
||||
public set(key: string | null, value: T): void {
|
||||
this.cache.set(key, {
|
||||
date: Date.now(),
|
||||
@@ -14,6 +17,7 @@ export class Cache<T> {
|
||||
});
|
||||
}
|
||||
|
||||
@bindThis
|
||||
public get(key: string | null): T | undefined {
|
||||
const cached = this.cache.get(key);
|
||||
if (cached == null) return undefined;
|
||||
@@ -24,6 +28,7 @@ export class Cache<T> {
|
||||
return cached.value;
|
||||
}
|
||||
|
||||
@bindThis
|
||||
public delete(key: string | null) {
|
||||
this.cache.delete(key);
|
||||
}
|
||||
@@ -32,6 +37,7 @@ export class Cache<T> {
|
||||
* キャッシュがあればそれを返し、無ければfetcherを呼び出して結果をキャッシュ&返します
|
||||
* optional: キャッシュが存在してもvalidatorでfalseを返すとキャッシュ無効扱いにします
|
||||
*/
|
||||
@bindThis
|
||||
public async fetch(key: string | null, fetcher: () => Promise<T>, validator?: (cachedValue: T) => boolean): Promise<T> {
|
||||
const cachedValue = this.get(key);
|
||||
if (cachedValue !== undefined) {
|
||||
@@ -56,6 +62,7 @@ export class Cache<T> {
|
||||
* キャッシュがあればそれを返し、無ければfetcherを呼び出して結果をキャッシュ&返します
|
||||
* optional: キャッシュが存在してもvalidatorでfalseを返すとキャッシュ無効扱いにします
|
||||
*/
|
||||
@bindThis
|
||||
public async fetchMaybe(key: string | null, fetcher: () => Promise<T | undefined>, validator?: (cachedValue: T) => boolean): Promise<T | undefined> {
|
||||
const cachedValue = this.get(key);
|
||||
if (cachedValue !== undefined) {
|
||||
|
@@ -5,12 +5,13 @@ export class I18n<T extends Record<string, any>> {
|
||||
this.locale = locale;
|
||||
|
||||
//#region BIND
|
||||
this.t = this.t.bind(this);
|
||||
//this.t = this.t.bind(this);
|
||||
//#endregion
|
||||
}
|
||||
|
||||
// string にしているのは、ドット区切りでのパス指定を許可するため
|
||||
// なるべくこのメソッド使うよりもlocale直接参照の方がvueのキャッシュ効いてパフォーマンスが良いかも
|
||||
@bindThis
|
||||
public t(key: string, args?: Record<string, any>): string {
|
||||
try {
|
||||
let str = key.split('.').reduce((o, i) => o[i], this.locale) as string;
|
||||
|
Reference in New Issue
Block a user