Files
utd-singularity/server.js
T

77 lines
2.0 KiB
JavaScript

const path = require("path");
// Require the framework and instantiate it
const fastify = require("fastify")({
logger: true
});
// Setup our static files
fastify.register(require("fastify-static"), {
root: path.join(__dirname, "public"),
prefix: "/" // optional: default '/'
});
// fastify-formbody lets us parse incoming forms
fastify.register(require("fastify-formbody"));
// point-of-view is a templating manager for fastify
fastify.register(require("point-of-view"), {
engine: {
handlebars: require("handlebars")
}
});
// load and parse SEO data
const seo = require("./src/seo.json");
if (seo.url === "glitch-default") {
seo.url = `https://${process.env.PROJECT_DOMAIN}.glitch.me`;
}
// Our home page route, this pulls from src/pages/index.hbs
fastify.get("/", function(request, reply) {
let params = { seo: seo };
if (request.query.randomize) {
const colors = require("./src/colors.json");
const allColors = Object.keys(colors);
let currentColor = allColors[(allColors.length * Math.random()) << 0];
params = {
color: colors[currentColor],
colorError: null,
seo: seo
};
}
reply.view("/src/pages/index.hbs", params);
});
// A route to handle form submissions and output the main page with custom colors
fastify.post("/", function(request, reply) {
let params = { seo: seo };
let color = request.body.color;
if (color) {
const colors = require("./src/colors.json");
color = color.toLowerCase().replace(/\s/g, "");
if (colors[color]) {
params = {
color: colors[color],
colorError: null,
seo: seo
};
} else {
params = {
colorError: request.body.color,
seo: seo
};
}
}
reply.view("/src/pages/index.hbs", params);
});
// Run the server and report out to the logs
fastify.listen(process.env.PORT, function(err, address) {
if (err) {
fastify.log.error(err);
process.exit(1);
}
fastify.log.info(`server listening on ${address}`);
});