feat: serve built SPA with fallback and artwork cache
This commit is contained in:
@@ -1,6 +1,9 @@
|
||||
import Fastify, { FastifyInstance } from 'fastify'
|
||||
import Database from 'better-sqlite3'
|
||||
import cookie from '@fastify/cookie'
|
||||
import fastifyStatic from '@fastify/static'
|
||||
import path from 'node:path'
|
||||
import { existsSync } from 'node:fs'
|
||||
import type { Config } from './config.js'
|
||||
import { SerialQueue } from './queue.js'
|
||||
import { SyncManager } from './sync.js'
|
||||
@@ -27,6 +30,8 @@ export interface AppOptions {
|
||||
db: Database.Database
|
||||
config: Config
|
||||
fetchImpl?: typeof fetch
|
||||
/** Directory of the built SPA. Defaults to web/dist when it exists. */
|
||||
webDist?: string
|
||||
}
|
||||
|
||||
export async function buildApp(opts: AppOptions): Promise<FastifyInstance> {
|
||||
@@ -44,6 +49,30 @@ export async function buildApp(opts: AppOptions): Promise<FastifyInstance> {
|
||||
await registerCollectionRoutes(app)
|
||||
await registerLibraryRoutes(app)
|
||||
|
||||
// artwork cache (always available)
|
||||
await app.register(fastifyStatic, {
|
||||
root: opts.config.artworkDir,
|
||||
prefix: '/artwork/',
|
||||
decorateReply: false,
|
||||
})
|
||||
|
||||
const webDist = opts.webDist ?? path.resolve('web/dist')
|
||||
const hasWeb = existsSync(webDist)
|
||||
if (hasWeb) {
|
||||
await app.register(fastifyStatic, { root: webDist, prefix: '/' })
|
||||
}
|
||||
|
||||
app.setNotFoundHandler((request, reply) => {
|
||||
const url = request.raw.url ?? ''
|
||||
if (url.startsWith('/api')) {
|
||||
return reply.code(404).send({ error: 'not_found' })
|
||||
}
|
||||
if (hasWeb) {
|
||||
return reply.sendFile('index.html')
|
||||
}
|
||||
return reply.code(404).send({ error: 'not_found' })
|
||||
})
|
||||
|
||||
app.get('/api/health', async () => ({ ok: true }))
|
||||
return app
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user