An even more educational version of the Bandolier for Learn JS the Hard Way.
https://learnjsthehardway.com/
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
78 lines
2.0 KiB
78 lines
2.0 KiB
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";
|
|
import nunjucks from "nunjucks";
|
|
|
|
export const description = "Runs your app.";
|
|
|
|
export const options = [];
|
|
|
|
export const required = [];
|
|
|
|
let CONFIGURED = false;
|
|
|
|
// nunjucks does it's own reload so let it do that
|
|
nunjucks.configure("templates", { watch: true });
|
|
|
|
const configure = async (fastify, opts) => {
|
|
const app = fastify(opts);
|
|
|
|
// forces reload of the modules
|
|
const control_mod = await import(`../controllers/todo.js?update=${new Date()}`);
|
|
|
|
// TODO: mappings are very simple for now
|
|
for(let [url, controller] of Object.entries(control_mod.default)) {
|
|
const handler = new controller();
|
|
// 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 '/'
|
|
constraints: {}, // optional: default {}
|
|
index: "index.html"
|
|
});
|
|
|
|
return app;
|
|
}
|
|
|
|
const app = await await restartable(configure, { logger: true});
|
|
const host = await app.listen({port: 3000});
|
|
|
|
const reload = () => {
|
|
if(CONFIGURED) {
|
|
app.restart();
|
|
}
|
|
}
|
|
|
|
export const main = async (arg, opts) => {
|
|
try {
|
|
chokidar.watch(["lib","commands","controllers","static","migrations","tests"])
|
|
.on("add", path => reload())
|
|
.on("change", path => reload())
|
|
.on("unlink", path => reload())
|
|
.on("ready", () => CONFIGURED = true);
|
|
} catch(err) {
|
|
fastify.log.error(err);
|
|
process.exit(1);
|
|
}
|
|
}
|
|
|