impress-2020/build-cached-data.js
Matchu 0f7ab9d10e cache zone data
I noticed that, while looking up zone data from the db is near instant when you're on the same box, it's like 300ms here!

In this change, we start downloading zone data into the build process. That way, we can have a very fast and practically-up-to-date cache (I'm not sure I've changed it in many years), while being confident that it's in sync with the database source of truth (for things like join queries).
2020-08-17 15:28:05 -07:00

49 lines
1.3 KiB
JavaScript

const fs = require("fs").promises;
const path = require("path");
const connectToDb = require("./src/server/db");
const { normalizeRow } = require("./src/server/util");
const cachedDataPath = path.join(__dirname, "build", "cached-data");
async function buildZonesCache(db) {
const [rows] = await db.query(`SELECT * FROM zones;`);
const entities = rows.map(normalizeRow);
const filePath = path.join(cachedDataPath, "zones.json");
fs.writeFile(filePath, JSON.stringify(entities, null, 4), "utf8");
console.log(`📚 Wrote zones to ${path.relative(process.cwd(), filePath)}`);
}
async function buildZoneTranslationsCache(db) {
const [rows] = await db.query(
`SELECT * FROM zone_translations WHERE locale = "en";`
);
const entities = rows.map(normalizeRow);
const filePath = path.join(cachedDataPath, "zone_translations.json");
fs.writeFile(filePath, JSON.stringify(entities, null, 4), "utf8");
console.log(
`📚 Wrote zone translations to ${path.relative(process.cwd(), filePath)}`
);
}
async function main() {
const db = await connectToDb();
await fs.mkdir(cachedDataPath, { recursive: true });
try {
await Promise.all([buildZonesCache(db), buildZoneTranslationsCache(db)]);
} catch (e) {
db.close();
throw e;
}
db.close();
}
main().catch((e) => {
console.error(e);
process.exitCode = 1;
});