diff --git a/lib/server.js b/lib/server.js index a8946e1..a73107e 100644 --- a/lib/server.js +++ b/lib/server.js @@ -5,11 +5,29 @@ */ import Reader from './reader.js' +/** @import { FastifyPluginCallback, FastifyReply } from 'fastify' */ +/** @import { Resource } from './reader.js' */ + +/** + * @param {FastifyReply} reply + * @param {Resource} resource + * @returns {FastifyReply} reply + */ +function sendResource(reply, resource) { + reply + .type(resource.contentType) + .header('content-length', resource.contentLength) + if (resource.contentEncoding) { + reply.header('content-encoding', resource.contentEncoding) + } + return reply.send(resource.stream) +} + /** * Fastify plugin for serving a styled map package. User `lazy: true` to defer * opening the file until the first request. * - * @type {import("fastify").FastifyPluginCallback} + * @type {FastifyPluginCallback} */ export default function (fastify, { filepath, lazy = false }, done) { /** @type {Reader | undefined} */ @@ -17,42 +35,30 @@ export default function (fastify, { filepath, lazy = false }, done) { if (!lazy) { reader = new Reader(filepath) } - const fd = fastify.decorateReply( - 'sendResource', - /** @param {import('./reader.js').Resource} resource */ - function (resource) { - this.type(resource.contentType).header( - 'content-length', - resource.contentLength, - ) - if (resource.contentEncoding) - this.header('content-encoding', resource.contentEncoding) - // @ts-ignore - return this.send(resource.stream) - }, - ) - fd.get('/style.json', async (request, reply) => { + fastify.get('/style.json', async (_request, reply) => { if (!reader) { reader = new Reader(filepath) } - // @ts-ignore - can't type this and keep it encapsulated - return reply.sendResource(await reader.getStyle(fastify.listeningOrigin)) + return sendResource(reply, await reader.getStyle(fastify.listeningOrigin)) }) - fd.get('*', async (request, reply) => { + + fastify.get('*', async (request, reply) => { if (!reader) { reader = new Reader(filepath) } + + /** @type {Resource} */ + let resource try { - // @ts-ignore - can't type this and keep it encapsulated - return reply.sendResource( - await reader.getResource(decodeURI(request.url)), - ) + resource = await reader.getResource(decodeURI(request.url)) } catch (e) { // @ts-ignore e.statusCode = 404 throw e } + + return sendResource(reply, resource) }) done() }