Exercise #05 - On/Off switch
Write a server that exposes a /onoff-switch
route.
The server will maintain the state of a switch. The state can either be "Off" or "On".
The switch will start in the "Off" position. Everytime a request is sent, flip the
switch and return the current state.
POST /onoff-switch >>> expected "On" POST /onoff-switch >>> expected "Off" POST /onoff-switch >>> expected "On"
You'll need a StatefulHandler
for this exercise, so that state can be kept
across requests. Read more on Dealing with mutable state.
If you're unsure on how to proceed, read more on how to setup your Local dev environment to complete the exercises.
Refresh the page to run the tests again.
Reference node.js implementation
const app = require("express")()
// Mutable state!
let currentState = "Off"
app.post("/onoff-switch", (req, res) => {
currentState = currentState === "Off" ? "On" : "Off"
res.send(currentState)
})
console.log("Starting server...")
app.listen(7879)
Where to get help
Got stuck? Don't worry! Join the discussion on Github (issue #5). It might be that the exercise could be clearer or there's something you really can't wrap your head around. That's totally fine! 🙂
You can also have a look at my solution. No shame in having a peek. 🧐
But do share your thoughts on the exercises, it would be really helpful!