Skip to content

Commit

Permalink
chore: use function, not decorator, to server resources (#9)
Browse files Browse the repository at this point in the history
  • Loading branch information
EvanHahn authored Sep 5, 2024
1 parent 8541fed commit 7ed98c5
Showing 1 changed file with 29 additions and 23 deletions.
52 changes: 29 additions & 23 deletions lib/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,54 +5,60 @@
*/
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<PluginOptions>}
* @type {FastifyPluginCallback<PluginOptions>}
*/
export default function (fastify, { filepath, lazy = false }, done) {
/** @type {Reader | undefined} */
let reader
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()
}

0 comments on commit 7ed98c5

Please sign in to comment.