diff options
| author | syuilo <Syuilotan@yahoo.co.jp> | 2022-09-18 03:27:08 +0900 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2022-09-18 03:27:08 +0900 |
| commit | b75184ec8e3436200bacdcd832e3324702553d20 (patch) | |
| tree | 8b7e316f29e95df921db57289c8b8da476d18f07 /packages/backend/src/core/MetaService.ts | |
| parent | Update ROADMAP.md (diff) | |
| download | sharkey-b75184ec8e3436200bacdcd832e3324702553d20.tar.gz sharkey-b75184ec8e3436200bacdcd832e3324702553d20.tar.bz2 sharkey-b75184ec8e3436200bacdcd832e3324702553d20.zip | |
なんかもうめっちゃ変えた
Diffstat (limited to 'packages/backend/src/core/MetaService.ts')
| -rw-r--r-- | packages/backend/src/core/MetaService.ts | 63 |
1 files changed, 63 insertions, 0 deletions
diff --git a/packages/backend/src/core/MetaService.ts b/packages/backend/src/core/MetaService.ts new file mode 100644 index 0000000000..b5bd423765 --- /dev/null +++ b/packages/backend/src/core/MetaService.ts @@ -0,0 +1,63 @@ +import { Inject, Injectable } from '@nestjs/common'; +import { DataSource } from 'typeorm'; +import type { UsersRepository } from '@/models/index.js'; +import { DI } from '@/di-symbols.js'; +import { Meta } from '@/models/entities/Meta.js'; +import type { OnApplicationShutdown } from '@nestjs/common'; + +@Injectable() +export class MetaService implements OnApplicationShutdown { + #cache: Meta | undefined; + #intervalId: NodeJS.Timer; + + constructor( + @Inject(DI.db) + private db: DataSource, + ) { + if (process.env.NODE_ENV !== 'test') { + this.#intervalId = setInterval(() => { + this.fetch(true).then(meta => { + this.#cache = meta; + }); + }, 1000 * 10); + } + } + + async fetch(noCache = false): Promise<Meta> { + if (!noCache && this.#cache) return this.#cache; + + return await this.db.transaction(async transactionalEntityManager => { + // 過去のバグでレコードが複数出来てしまっている可能性があるので新しいIDを優先する + const metas = await transactionalEntityManager.find(Meta, { + order: { + id: 'DESC', + }, + }); + + const meta = metas[0]; + + if (meta) { + this.#cache = meta; + return meta; + } else { + // metaが空のときfetchMetaが同時に呼ばれるとここが同時に呼ばれてしまうことがあるのでフェイルセーフなupsertを使う + const saved = await transactionalEntityManager + .upsert( + Meta, + { + id: 'x', + }, + ['id'], + ) + .then((x) => transactionalEntityManager.findOneByOrFail(Meta, x.identifiers[0])); + + this.#cache = saved; + return saved; + } + }); + } + + public onApplicationShutdown(signal?: string | undefined) { + clearInterval(this.#intervalId); + } +} |