|
| 1 | +# Heater Activity / Example |
| 2 | + |
| 3 | +## Activity |
| 4 | + |
| 5 | +Create a heater endpoint that requires an integer value for mode. Valid values accepted for mode are `0` for normal and `1` for energy saving. If mode value is incorrect return HTTP code 422 with an error message. The endpoint should also have a required value of temperature which accepts an integer. |
| 6 | + |
| 7 | +The end-point should be protected so be sure to require a JWT for use as was done in exercise 6. |
| 8 | + |
| 9 | +## Solution |
| 10 | + |
| 11 | +1. Create a new route file at `routes/devices/heater.js `, it should use express-validator to check that temperature and mode is numeric, it should also check that mode is minimum 0 and maximum 1. If error checking passes it should return a success message using the values provided: |
| 12 | + |
| 13 | + const express = require('express'); |
| 14 | + const { check, validationResult } = require('express-validator/check'); |
| 15 | + const router = express.Router(); |
| 16 | + |
| 17 | + // Function to run if user sends a PUT request |
| 18 | + router.put(['/', '/actions/fade'], [ |
| 19 | + check('mode').isNumeric().isLength({ min: 0, max: 1 }), |
| 20 | + check('temperature').isNumeric() |
| 21 | + ], |
| 22 | + (req, res) => { |
| 23 | + const errors = validationResult(req); |
| 24 | + if (!errors.isEmpty()) { |
| 25 | + return res.status(422).json({ errors: errors.array() }); |
| 26 | + } |
| 27 | + let temperature = req.body.temperature; |
| 28 | + let mode = req.body.mode; |
| 29 | + |
| 30 | + let message = `success: temperature set to ${temperature} mode is ${mode}`; |
| 31 | + res.json({"message": message}); |
| 32 | + }); |
| 33 | + |
| 34 | + // Export route so it is available to import |
| 35 | + module.exports = router; |
| 36 | + |
| 37 | + |
| 38 | +2. Import `routes/devices/heater.js` in `server.js`: |
| 39 | + |
| 40 | + let heater = require('./routes/devices/heater'); |
| 41 | + |
| 42 | +3. Associate `heater` with route `/devices/heater`, making sure to pass the `isCheckedIn` middleware: |
| 43 | + |
| 44 | + app.use('/devices/heater', isCheckedIn, heater); |
| 45 | + |
| 46 | +4. Start the project by running `npm start`. |
| 47 | + |
| 48 | +5. In another window first get a valid JWT with curl: |
| 49 | + |
| 50 | + TOKEN=$(curl -sd "name=john" -X POST http://localhost:3000/check-in \ |
| 51 | + | jq -r ".token") |
| 52 | + |
| 53 | + |
| 54 | +6. Test the endpoint with correct values like so, it should return a success message: |
| 55 | + |
| 56 | + curl -sd "mode=0&temperature=25" -X PUT \ |
| 57 | + -H "Authorization: Bearer ${TOKEN}" \ |
| 58 | + http://localhost:3000/devices/heater \ |
| 59 | + | jq |
| 60 | + |
| 61 | +7. Finally test with some false value like so: |
| 62 | + |
| 63 | + |
| 64 | + curl -sd "mode=9&temperature=25" -X PUT \ |
| 65 | + http://localhost:3000/devices/heater \ |
| 66 | + | jq |
| 67 | + |
0 commit comments