2023-01-13 13:40:33 +09:00
|
|
|
import { db } from "@/db/postgre.js";
|
|
|
|
import { Meta } from "@/models/entities/meta.js";
|
2018-11-06 07:14:43 +09:00
|
|
|
|
2019-04-24 08:11:19 +09:00
|
|
|
let cache: Meta;
|
|
|
|
|
|
|
|
export async function fetchMeta(noCache = false): Promise<Meta> {
|
|
|
|
if (!noCache && cache) return cache;
|
|
|
|
|
2023-01-13 13:40:33 +09:00
|
|
|
return await db.transaction(async (transactionalEntityManager) => {
|
2022-12-03 09:23:02 +09:00
|
|
|
// New IDs are prioritized because multiple records may have been created due to past bugs.
|
2022-03-27 16:16:13 +09:00
|
|
|
const metas = await transactionalEntityManager.find(Meta, {
|
2019-04-17 00:45:33 +09:00
|
|
|
order: {
|
2023-01-13 13:40:33 +09:00
|
|
|
id: "DESC",
|
2021-12-09 23:58:30 +09:00
|
|
|
},
|
2019-04-17 00:45:33 +09:00
|
|
|
});
|
|
|
|
|
2022-03-27 16:16:13 +09:00
|
|
|
const meta = metas[0];
|
|
|
|
|
2019-04-17 00:45:33 +09:00
|
|
|
if (meta) {
|
2019-04-24 08:11:19 +09:00
|
|
|
cache = meta;
|
2019-04-17 00:45:33 +09:00
|
|
|
return meta;
|
|
|
|
} else {
|
2022-12-03 09:23:02 +09:00
|
|
|
// If fetchMeta is called at the same time when meta is empty, this part may be called at the same time, so use fail-safe upsert.
|
2022-05-14 15:16:45 +09:00
|
|
|
const saved = await transactionalEntityManager
|
|
|
|
.upsert(
|
|
|
|
Meta,
|
|
|
|
{
|
2023-01-13 13:40:33 +09:00
|
|
|
id: "x",
|
2022-05-14 15:16:45 +09:00
|
|
|
},
|
2023-01-13 13:40:33 +09:00
|
|
|
["id"],
|
2022-05-14 15:16:45 +09:00
|
|
|
)
|
2023-01-13 13:40:33 +09:00
|
|
|
.then((x) =>
|
|
|
|
transactionalEntityManager.findOneByOrFail(Meta, x.identifiers[0]),
|
|
|
|
);
|
2019-04-24 08:11:19 +09:00
|
|
|
|
|
|
|
cache = saved;
|
|
|
|
return saved;
|
2019-04-17 00:45:33 +09:00
|
|
|
}
|
|
|
|
});
|
2018-11-06 07:14:43 +09:00
|
|
|
}
|
2019-04-24 08:11:19 +09:00
|
|
|
|
|
|
|
setInterval(() => {
|
2023-01-13 13:40:33 +09:00
|
|
|
fetchMeta(true).then((meta) => {
|
2019-04-24 08:11:19 +09:00
|
|
|
cache = meta;
|
|
|
|
});
|
2021-03-19 18:22:34 +09:00
|
|
|
}, 1000 * 10);
|