YANG QIA 474b09c7f2
perf(server): optimize performance of APIs (#3079)
* perf: add perf_hooks

* perf: add cache

* fix: test

* feat: support bloom filter

* feat: caching token black list

* perf: caching i18n instance

* fix: test

* fix: test

* chore: remove prePerfHooks on app

* chore: improve i18n instances cache

* chore: remove performance measure

* fix: package.json

* perf: optimize cache strategy

* fix: test

* fix: bug

* test: storer of auth-manager

* fix: afterDestroy hook when updating null value

* fix: version

* chore: fix bug and add test

* fix: test

* fix: test
2023-12-12 23:02:09 +08:00

54 lines
1.7 KiB
TypeScript

import { Storer as IStorer } from '@nocobase/auth';
import { Cache } from '@nocobase/cache';
import { Database, Model } from '@nocobase/database';
import { AuthModel } from './model/authenticator';
export class Storer implements IStorer {
db: Database;
cache: Cache;
key = 'authenticators';
constructor({ db, cache }: { db: Database; cache: Cache }) {
this.db = db;
this.cache = cache;
this.db.on('authenticators.afterSave', async (model: AuthModel) => {
if (!model.enabled) {
await this.cache.delValueInObject(this.key, model.name);
return;
}
await this.cache.setValueInObject(this.key, model.name, model);
});
this.db.on('authenticators.afterDestroy', async (model: AuthModel) => {
await this.cache.delValueInObject(this.key, model.name);
});
}
async getCache(): Promise<AuthModel[]> {
const authenticators = (await this.cache.get(this.key)) as Record<string, AuthModel>;
if (!authenticators) {
return [];
}
return Object.values(authenticators);
}
async setCache(authenticators: AuthModel[]) {
const obj = authenticators.reduce((obj, authenticator) => {
obj[authenticator.name] = authenticator;
return obj;
}, {});
await this.cache.set(this.key, obj);
}
async get(name: string) {
let authenticators = await this.getCache();
if (!authenticators.length) {
const repo = this.db.getRepository('authenticators');
authenticators = await repo.find({ filter: { enabled: true } });
await this.setCache(authenticators);
}
const authenticator = authenticators.find((authenticator: Model) => authenticator.name === name);
return authenticator || authenticators[0];
}
}