jormungandr-bite/packages/backend/src/misc/fetch-meta.ts

73 lines
1.7 KiB
TypeScript
Raw Normal View History

2023-01-12 21:40:33 -07:00
import { db } from "@/db/postgre.js";
import { Meta } from "@/models/entities/meta.js";
2019-04-23 17:11:19 -06:00
let cache: Meta;
2023-06-08 12:01:00 -06:00
export function metaToPugArgs(meta: Meta): object {
let motd = ["Loading..."];
if (meta.customMOTD.length > 0) {
motd = meta.customMOTD;
}
let splashIconUrl = meta.iconUrl;
if (meta.customSplashIcons.length > 0) {
splashIconUrl =
meta.customSplashIcons[
Math.floor(Math.random() * meta.customSplashIcons.length)
];
}
return {
img: meta.bannerUrl,
title: meta.name || "Calckey",
instanceName: meta.name || "Calckey",
desc: meta.description,
icon: meta.iconUrl,
splashIcon: splashIconUrl,
themeColor: meta.themeColor,
randomMOTD: motd[Math.floor(Math.random() * motd.length)],
privateMode: meta.privateMode,
2023-06-08 12:01:00 -06:00
};
}
2019-04-23 17:11:19 -06:00
export async function fetchMeta(noCache = false): Promise<Meta> {
if (!noCache && cache) return cache;
2023-01-12 21:40:33 -07:00
return await db.transaction(async (transactionalEntityManager) => {
// New IDs are prioritized because multiple records may have been created due to past bugs.
2022-03-27 01:16:13 -06:00
const metas = await transactionalEntityManager.find(Meta, {
order: {
2023-01-12 21:40:33 -07:00
id: "DESC",
2021-12-09 07:58:30 -07:00
},
});
2022-03-27 01:16:13 -06:00
const meta = metas[0];
if (meta) {
2019-04-23 17:11:19 -06:00
cache = meta;
return meta;
} else {
// 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.
const saved = await transactionalEntityManager
.upsert(
Meta,
{
2023-01-12 21:40:33 -07:00
id: "x",
},
2023-01-12 21:40:33 -07:00
["id"],
)
2023-01-12 21:40:33 -07:00
.then((x) =>
transactionalEntityManager.findOneByOrFail(Meta, x.identifiers[0]),
);
2019-04-23 17:11:19 -06:00
cache = saved;
return saved;
}
});
}
2019-04-23 17:11:19 -06:00
setInterval(() => {
2023-01-12 21:40:33 -07:00
fetchMeta(true).then((meta) => {
2019-04-23 17:11:19 -06:00
cache = meta;
});
2021-03-19 03:22:34 -06:00
}, 1000 * 10);