|
| 1 | +const express = require('express'); |
| 2 | +const cors = require('cors'); |
| 3 | +const bodyParser = require('body-parser'); |
| 4 | +const Repository = require('./repository'); |
| 5 | + |
| 6 | +const server = express(); |
| 7 | +server.use(cors()); |
| 8 | +server.use(bodyParser.json()); |
| 9 | +server.use(bodyParser.urlencoded({extended: true})); |
| 10 | + |
| 11 | +// Load data into a repository |
| 12 | +const animalRepository = new Repository(); |
| 13 | +const data = require('./data/animalData.json'); |
| 14 | +data.reduce( (a, v) => { |
| 15 | + v.id = a + 1; |
| 16 | + animalRepository.insert(v); |
| 17 | + return a + 1; |
| 18 | +}, 0); |
| 19 | + |
| 20 | +// Suggestions function: |
| 21 | +// Given availability and sex, find available suitors... |
| 22 | +const availableAnimals = () => { |
| 23 | + return animalRepository.fetchAll().filter(a => { |
| 24 | + return a.eligibility.available |
| 25 | + }); |
| 26 | +} |
| 27 | + |
| 28 | +// Get all animals |
| 29 | +server.get('/animals', (req, res) => { |
| 30 | + res.json(animalRepository.fetchAll()); |
| 31 | +}); |
| 32 | + |
| 33 | +// Get all animals |
| 34 | +server.get('/animals/available', (req, res) => { |
| 35 | + res.json(availableAnimals()); |
| 36 | +}); |
| 37 | + |
| 38 | +// Find an animal by ID |
| 39 | +server.get('/animals/:id', (req, res) => { |
| 40 | + const response = animalRepository.getById(req.params.id); |
| 41 | + if (response) { |
| 42 | + res.writeHead(200, {'Content-Type': 'application/json'}); |
| 43 | + res.end(JSON.stringify(response)); |
| 44 | + } else { |
| 45 | + res.writeHead(404); |
| 46 | + res.end(); |
| 47 | + } |
| 48 | +}); |
| 49 | + |
| 50 | +// Register a new Animal for the service |
| 51 | +server.post('/animals', (req, res) => { |
| 52 | + const animal = req.body; |
| 53 | + |
| 54 | + // Really basic validation |
| 55 | + if (!animal || !animal.first_name) { |
| 56 | + res.writeHead(400); |
| 57 | + res.end(); |
| 58 | + |
| 59 | + return; |
| 60 | + } |
| 61 | + |
| 62 | + animal.id = animalRepository.fetchAll().length;; |
| 63 | + animalRepository.insert(animal); |
| 64 | + |
| 65 | + res.writeHead(200); |
| 66 | + res.end(); |
| 67 | +}); |
| 68 | + |
| 69 | +module.exports = server; |
0 commit comments