diff --git a/src/lib/server/db.ts b/src/lib/server/db.ts index dc31867..949fab8 100644 --- a/src/lib/server/db.ts +++ b/src/lib/server/db.ts @@ -5,11 +5,12 @@ import { isTruthy } from '$lib/truthyString'; import sqlite3 from 'sqlite3'; const { DEV } = import.meta.env; -const db: sqlite3.Database = new sqlite3.Database('moshingmammut.db'); +const db: sqlite3.Database = new sqlite3.Database('moshingmammut3.db'); const ignoredUsers: string[] = IGNORE_USERS === undefined ? [] : IGNORE_USERS.split(',').map((u) => (u.startsWith('@') ? u.substring(1) : u)); +let databaseReady = false; if (DEV && isTruthy(env.VERBOSE)) { sqlite3.verbose(); @@ -39,13 +40,25 @@ db.on('open', () => { db.all('SELECT id FROM migrations', (err, rows) => { if (err !== null) { console.error('Could not fetch existing migrations', err); + databaseReady = true; return; } console.debug('Already applied migrations', rows); const appliedMigrations: Set = new Set(rows.map((row: any) => row['id'])); const toApply = getMigrations().filter((m) => !appliedMigrations.has(m.id)); + let remaining = toApply.length; + if (remaining === 0) { + databaseReady = true; + return; + } for (const migration of toApply) { db.exec(migration.statement, (err) => { + remaining--; + // This will set databaseReady to true before the migration has been inserted as applies, + // but that doesn't matter. It's only important that is has been applied + if (remaining === 0) { + databaseReady = true; + } if (err !== null) { console.error(`Failed to apply migration ${migration.name}`, err); return; @@ -104,7 +117,28 @@ function getMigrations(): Migration[] { ]; } +async function waitReady(): Promise { + // Simpler than a semaphore and is really only needed on startup + return new Promise((resolve) => { + const interval = setInterval(() => { + if (DEV) { + console.debug('Waiting for database to be ready'); + } + if (databaseReady) { + if (DEV) { + console.debug('DB is ready'); + } + clearInterval(interval); + resolve(undefined); + } + }, 100); + }); +} + export async function savePost(post: Post): Promise { + if (!databaseReady) { + await waitReady(); + } return new Promise((resolve, reject) => { console.debug(`Saving post ${post.url}`); const account = post.account; @@ -198,6 +232,9 @@ export async function savePost(post: Post): Promise { } export async function getPosts(since: string | null, before: string | null, limit: number) { + if (!databaseReady) { + await waitReady(); + } const promise = await new Promise((resolve, reject) => { let filter_query = ''; const params: any = { $limit: limit }; diff --git a/src/routes/+page.svelte b/src/routes/+page.svelte index 19f7b81..72cd412 100644 --- a/src/routes/+page.svelte +++ b/src/routes/+page.svelte @@ -155,7 +155,7 @@
{#if data.posts.length === 0} - Sorry, no posts recommending music aave been found yet + Sorry, no posts recommending music have been found yet {/if} {#each data.posts as post (post.url)}