Scripts: create server script for pmtiles

This commit is contained in:
Pieter Vander Vennet 2025-09-26 01:53:34 +02:00
parent 1527627cd0
commit 676bb8a250
6 changed files with 175 additions and 60 deletions

View file

@ -1,14 +1,22 @@
import http from "node:http"
import { ServerResponse } from "http"
import { createReadStream } from "node:fs"
export interface Handler {
mustMatch: string | RegExp
mimetype: string
addHeaders?: Record<string, string>
/**
* IF set, do not write headers and result; only close.
* Use this if you want to send binary data
*/
unmanaged?: boolean
handle: (
path: string,
queryParams: URLSearchParams,
req: http.IncomingMessage,
body: string | undefined
body: string | undefined,
res: http.ServerResponse
) => Promise<string>
}
@ -112,7 +120,11 @@ export class Server {
}
try {
const result = await handler.handle(path, url.searchParams, req, body)
const result = await handler.handle(path, url.searchParams, req, body, res)
if(handler.unmanaged){
res.end()
return
}
if (result === undefined) {
res.writeHead(500)
res.write("Could not fetch this website, probably blocked by them")
@ -129,14 +141,18 @@ export class Server {
result
)
}
const extraHeaders = handler.addHeaders ?? {}
res.writeHead(200, { "Content-Type": handler.mimetype, ...extraHeaders })
res.write("" + result)
res.end()
} catch (e) {
console.error("Could not handle request:", e)
res.writeHead(500)
res.write(e)
res.write("Internal server error - something went wrong:")
res.write(e.toString())
res.end()
}
} catch (e) {
@ -145,8 +161,19 @@ export class Server {
}
}).listen(port)
console.log(
"Server is running on port " + port,
"Server is running on http://127.0.0.1:" + port,
". Supported endpoints are: " + handle.map((h) => h.mustMatch).join(", ")
)
}
/**
* Sends a file straight from disk.
* Assumes that headers have been set on res
* @param path
* @param res
*/
public static sendFile(path: string, res: ServerResponse){
createReadStream(path).pipe(res);
}
}