Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: use function, not decorator, to server resources #9

Merged
merged 2 commits into from
Sep 5, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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()
}