|
|
|
@ -1,6 +1,7 @@ |
|
|
|
|
import Fastify from "fastify"; |
|
|
|
|
import { restartable } from "@fastify/restartable"; |
|
|
|
|
import FastifyStatic from "@fastify/static"; |
|
|
|
|
import Formbody from "@fastify/formbody"; |
|
|
|
|
import path from "path"; |
|
|
|
|
import fs from "fs"; |
|
|
|
|
import chokidar from "chokidar"; |
|
|
|
@ -20,30 +21,30 @@ nunjucks.configure("templates", { watch: true }); |
|
|
|
|
const configure = async (fastify, opts) => { |
|
|
|
|
const app = fastify(opts); |
|
|
|
|
|
|
|
|
|
// MAGIC: this is how you trick the importer to reload modules
|
|
|
|
|
// that have changed. Since it uses a URL you can add a query
|
|
|
|
|
// to it, but that isn't parsed as the file. Using a date then
|
|
|
|
|
// tags the module as being "new" when it's still the same file
|
|
|
|
|
// TODO: maybe use fs timestamps instead?
|
|
|
|
|
// BUG: sometimes reload is too fast for vim and crashes
|
|
|
|
|
// forces reload of the modules
|
|
|
|
|
const control_mod = await import(`../controllers/todo.js?update=${new Date()}`); |
|
|
|
|
|
|
|
|
|
// this is a sample that uses the handler we dynamic load
|
|
|
|
|
// to handle the /todo but not sure how to work the actual
|
|
|
|
|
// URL mappings for it. Also not sure about using classes
|
|
|
|
|
// TODO: mappings are very simple for now
|
|
|
|
|
for(let [url, controller] of Object.entries(control_mod.default)) { |
|
|
|
|
const handler = new controller(); |
|
|
|
|
app.get(`/${url}`, async (req, rep) => { |
|
|
|
|
try { |
|
|
|
|
await handler.get(req, rep); |
|
|
|
|
} catch(error) { |
|
|
|
|
console.error(error); |
|
|
|
|
console.error(error.stack); |
|
|
|
|
console.error(error.source); |
|
|
|
|
// this goes through all the allowed verbs
|
|
|
|
|
for(let verb of ["get", "post", "put", "delete"]) { |
|
|
|
|
if(verb in handler) { |
|
|
|
|
app[verb](`/${url}`, async (req, rep) => { |
|
|
|
|
try { |
|
|
|
|
await handler[verb](req, rep); |
|
|
|
|
} catch(error) { |
|
|
|
|
console.error(error); |
|
|
|
|
console.error(error.stack); |
|
|
|
|
console.error(error.source); |
|
|
|
|
} |
|
|
|
|
}); |
|
|
|
|
} |
|
|
|
|
}); |
|
|
|
|
} |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
app.register(Formbody); |
|
|
|
|
|
|
|
|
|
app.register(FastifyStatic, { |
|
|
|
|
root: path.join(path.resolve("."), 'static'), |
|
|
|
|
prefix: '/', // optional: default '/'
|
|
|
|
@ -51,15 +52,6 @@ const configure = async (fastify, opts) => { |
|
|
|
|
index: "index.html" |
|
|
|
|
}); |
|
|
|
|
|
|
|
|
|
// this is from fastify/restartable
|
|
|
|
|
app.addHook('onClose', async () => { |
|
|
|
|
if(!app.closingRestartable) { |
|
|
|
|
console.log('closing the app because of restart') |
|
|
|
|
} else{ |
|
|
|
|
console.log('closing the app because server is stopping') |
|
|
|
|
} |
|
|
|
|
}) |
|
|
|
|
|
|
|
|
|
return app; |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|