|
| 1 | +/* |
| 2 | +*/ |
| 3 | + |
| 4 | +// |
| 5 | +import express from 'express'; |
| 6 | + |
| 7 | +const app = express(); |
| 8 | +app.use(express.json()); |
| 9 | + |
| 10 | +// STATUS CODES |
| 11 | +const OK = 200; |
| 12 | +const NOT_FOUND = 404; |
| 13 | +const CREATED = 201; |
| 14 | + |
| 15 | +// test data |
| 16 | +const testSkins = [ |
| 17 | + { |
| 18 | + id: 1228, |
| 19 | + name: 'Temukau', |
| 20 | + wapon: 'M4A4', |
| 21 | + team: 'CT', |
| 22 | + }, |
| 23 | + { |
| 24 | + id: 1221, |
| 25 | + name: 'Head Shot', |
| 26 | + wapon: 'AK-47', |
| 27 | + team: 'T', |
| 28 | + }, |
| 29 | + { |
| 30 | + id: 1222, |
| 31 | + name: 'Duality', |
| 32 | + wapon: 'AWP', |
| 33 | + team: 'BOTH', |
| 34 | + }, |
| 35 | + { |
| 36 | + id: 1229, |
| 37 | + name: 'Sakkaku', |
| 38 | + wapon: 'MAC-10', |
| 39 | + team: 'T', |
| 40 | + }, |
| 41 | +]; |
| 42 | + |
| 43 | +app.get('/', (_request, response) => response.status(OK).json({ message: '[fapi] - running' })); |
| 44 | + |
| 45 | +// CREATE |
| 46 | +app.post('/skins', (request, response) => { |
| 47 | + const newData = { ...request.body }; |
| 48 | + // add data from body |
| 49 | + testSkins.push(newData); |
| 50 | + |
| 51 | + response.status(CREATED).json({ testSkins: newData }); |
| 52 | +}); |
| 53 | + |
| 54 | +// READ |
| 55 | +app.get('/skins', (_request, response) => response.status(OK).json({ testSkins })); |
| 56 | + |
| 57 | +// UPDATE |
| 58 | +app.put('/skins/:id', (request, response) => { |
| 59 | + const { id } = request.params; |
| 60 | + const { name, team } = request.body; |
| 61 | + |
| 62 | + // find skin inside the 'global' array by the id from the request params |
| 63 | + const updateSkins = testSkins.find((skin) => skin.id === +id); // every data received from "params" is a string |
| 64 | + // so we have to "convert" it to a number or w/e data you might need |
| 65 | + if (!updateSkins) { |
| 66 | + response.status(NOT_FOUND).json({ message: '[fapi] - skin not found' }); |
| 67 | + } |
| 68 | + |
| 69 | + // update data |
| 70 | + updateSkins.name = name; |
| 71 | + updateSkins.team = team; |
| 72 | + |
| 73 | + // change the api response with the found skin |
| 74 | + response.status(OK).json({ updateSkins }); |
| 75 | +}); |
| 76 | + |
| 77 | +// DELETE |
| 78 | +app.delete('/skins/:id', (request, response) => { |
| 79 | + const { id } = request.params; |
| 80 | + |
| 81 | + const arrayPosition = testSkins.findIndex((skin) => skin.id === +id); |
| 82 | + testSkins.splice(arrayPosition, 1); |
| 83 | + |
| 84 | + // send response in case everything goes well |
| 85 | + response.status(OK).end(); |
| 86 | +}); |
| 87 | + |
| 88 | +export default app; |
0 commit comments