Created
October 22, 2022 12:23
-
-
Save GitHub30/b88bac0f8ffda58a3410799766579d4b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* This is the main Node.js server script for your project | |
* Check out the two endpoints this back-end API provides in fastify.get and fastify.post below | |
*/ | |
const path = require("path"); | |
const fetch = require('node-fetch'); | |
// Require the fastify framework and instantiate it | |
const fastify = require("fastify")({ | |
// Set this to true for detailed logging: | |
logger: false, | |
}); | |
// ADD FAVORITES ARRAY VARIABLE FROM TODO HERE | |
// Setup our static files | |
fastify.register(require("@fastify/static"), { | |
root: path.join(__dirname, "public"), | |
prefix: "/", // optional: default '/' | |
}); | |
// Formbody lets us parse incoming forms | |
fastify.register(require("@fastify/formbody")); | |
// View is a templating manager for fastify | |
fastify.register(require("@fastify/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 | |
* | |
* Returns src/pages/index.hbs with data built into it | |
*/ | |
fastify.get("/", function (request, reply) { | |
// params is an object we'll pass to our handlebars template | |
let params = { seo: seo }; | |
// If someone clicked the option for a random color it'll be passed in the querystring | |
if (request.query.randomize) { | |
// We need to load our color data file, pick one at random, and add it to the params | |
const colors = require("./src/colors.json"); | |
const allColors = Object.keys(colors); | |
let currentColor = allColors[(allColors.length * Math.random()) << 0]; | |
// Add the color properties to the params object | |
params = { | |
color: colors[currentColor], | |
colorError: null, | |
seo: seo, | |
}; | |
} | |
// The Handlebars code will be able to access the parameter values and build them into the page | |
return reply.view("/src/pages/index.hbs", params); | |
}); | |
/** | |
* Our POST route to handle and react to form submissions | |
* | |
* Accepts body data indicating the user choice | |
*/ | |
fastify.post("/", function (request, reply) { | |
// Build the params object to pass to the template | |
let params = { seo: seo }; | |
// If the user submitted a color through the form it'll be passed here in the request body | |
let color = request.body.color; | |
// If it's not empty, let's try to find the color | |
if (color) { | |
// ADD CODE FROM TODO HERE TO SAVE SUBMITTED FAVORITES | |
// Load our color data file | |
const colors = require("./src/colors.json"); | |
// Take our form submission, remove whitespace, and convert to lowercase | |
color = color.toLowerCase().replace(/\s/g, ""); | |
// Now we see if that color is a key in our colors object | |
if (colors[color]) { | |
// Found one! | |
params = { | |
color: colors[color], | |
colorError: null, | |
seo: seo, | |
}; | |
} else { | |
// No luck! Return the user value as the error property | |
params = { | |
colorError: request.body.color, | |
seo: seo, | |
}; | |
} | |
} | |
// The Handlebars template will use the parameter values to update the page with the chosen color | |
return reply.view("/src/pages/index.hbs", params); | |
}); | |
/** | |
* Executes a shell command and return it as a Promise. | |
* @param cmd {string} | |
* @return {Promise<string>} | |
*/ | |
function execShellCommand(cmd) { | |
const exec = require('child_process').exec; | |
return new Promise((resolve, reject) => { | |
exec(cmd, (error, stdout, stderr) => { | |
if (error) { | |
console.warn(error); | |
} | |
resolve(stdout? stdout : stderr); | |
}); | |
}); | |
} | |
fastify.get("/hello", async function (request, reply) { | |
// https://ali-dev.medium.com/how-to-use-promise-with-exec-in-node-js-a39c4d7bbf77 | |
console.log(await fetch('http://httpbin.org/ip').then(r=>r.json())); | |
const javaInfo = await execShellCommand('curl https://storage.googleapis.com/gcping-release/gcping_linux_amd64_latest > gcping && chmod +x gcping && ./gcping'); | |
console.log(javaInfo); | |
// The Handlebars code will be able to access the parameter values and build them into the page | |
return JSON.stringify(process.env, null, 2); | |
}); | |
// Run the server and report out to the logs | |
fastify.listen( | |
{ port: process.env.PORT, host: "0.0.0.0" }, | |
function (err, address) { | |
if (err) { | |
fastify.log.error(err); | |
process.exit(1); | |
} | |
console.log(`Your app is listening on ${address}`); | |
fastify.log.info(`server listening on ${address}`); | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment