diff --git a/lib/index.js b/lib/index.js index 0ab7b71..ea82d2c 100644 --- a/lib/index.js +++ b/lib/index.js @@ -15,9 +15,9 @@ const serverPath = isWindows ? serverFile.replaceAll("\\", "//") : serverFile; * @typedef {import('astro').AstroUserConfig} AstroUserConfig @typedef {import('astro').AstroConfig} AstroConfig * @typedef {import('vite').Plugin} VitePlugin -* +* * @typedef {import('./types').IntegrationOptions} IntegrationOptions -* +* */ /** @@ -38,42 +38,42 @@ function vitePlugin(options) { return { name: '@matthewp/astro-fastify:vite', async configureServer(server) { - const nextSymbol = Symbol('next'); - - /** @type {import('fastify').FastifyServerFactory} */ - const serverFactory = (handler, opts) => { - server.middlewares.use((req, res, next) => { - req[nextSymbol] = next; - handler(req, res); + return async () => { + const nextSymbol = Symbol('next'); + /** @type {import('fastify').FastifyServerFactory} */ + const serverFactory = (handler, opts) => { + server.middlewares.use((req, res, next) => { + req[nextSymbol] = next; + handler(req, res); + }); + return /** @type {import('http').Server} */(server.httpServer ?? new http.Server()); + } + + const fastify = Fastify({ + logger: options?.logger ?? true, + serverFactory }); - return /** @type {import('http').Server} */(server.httpServer ?? new http.Server()); - } - - const fastify = Fastify({ - logger: options?.logger ?? true, - serverFactory - }); - - if(options?.entry) { - const entry = entryToPath(options.entry); - const entryModule = await server.ssrLoadModule(entry); - const setupRoutes = entryModule.default; - if(typeof setupRoutes !== 'function') { - throw new Error(`@matthewp/astro-fastify: ${entry} should export a default function.`); + + if(options?.entry) { + const entry = entryToPath(options.entry); + const entryModule = await server.ssrLoadModule(entry); + const setupRoutes = entryModule.default; + if(typeof setupRoutes !== 'function') { + throw new Error(`@matthewp/astro-fastify: ${entry} should export a default function.`); + } + setupRoutes(fastify); } - setupRoutes(fastify); + + // Final catch-all route forwards back to the Vite server + fastify.all('/*', function (request) { + /** @type {import('connect').NextFunction} */ + const next = request.raw[nextSymbol]; + if (typeof next === "function") { + next(); + } + }); + await fastify.ready(); } - - // Final catch-all route forwards back to the Vite server - fastify.all('/*', function (request) { - /** @type {import('connect').NextFunction} */ - const next = request.raw[nextSymbol]; - if (typeof next === "function") { - next(); - } - }); - - await fastify.ready(); }, transform(code, id) { if(options?.entry && id.includes('@matthewp/astro-fastify/lib/server.js')) {