+ Added GET one and GET all for schools

This commit is contained in:
Alexis
2020-05-16 14:58:40 +02:00
parent c58a1bae71
commit bf8205c679
2 changed files with 181 additions and 6 deletions

116
routes/schools.js Normal file
View File

@@ -0,0 +1,116 @@
'use strict'
const express = require('express')
let router = express.Router()
const connection = require('../database/connection')
const db = connection.db
// Model validation
const Validator = require('jsonschema').Validator
const v = new Validator()
const School = require("../models/School")
v.addSchema(School, "/SchoolModel")
const getSchools = () => {
let getSchoolsPromise = new Promise((resolve, reject) => {
let query = "SELECT DISTINCT * FROM school"
db.query(query, async (err, result) => {
if (err) return reject
if (result.length == 0) { console.log("No school found in database") }
// Loops over the results to fetch the associated tables
for (let i = 0; i < result.length; i++) {
result[i] = await buildSchool(result[i])
}
resolve(result)
})
})
return getSchoolsPromise
}
const getSchool = (id) => {
let getSchoolPromise = new Promise((resolve, reject) => {
let query = "SELECT * FROM school WHERE id = " + id
db.query(query, async (err, result) => {
if (err) return reject
result = await buildSchool(result[0])
resolve(result);
})
})
return getSchoolPromise
}
// ROUTES
// Get All
router.get('/', async (req, res, next) => {
getSchools()
.then(v => {
res.setHeader('Content-Type', 'application/json;charset=utf-8')
res.end(JSON.stringify(v))
})
.catch(err => {
console.log(err)
next()
})
})
// Get One
router.get('/:id/', async (req, res, next) => {
getSchool(req.params.id)
.then(v => {
res.setHeader('Content-Type', 'application/json;charset=utf-8')
res.end(JSON.stringify(v))
})
.catch(err => {
console.log(err)
next()
})
})
// Param validation for single school
// (check if id is int) (could be refactored)
router.param('id', (req, res, next, id) => {
const regex = RegExp(/^[1-9]\d*$/);
try {
if (regex.test(id)) {
next()
} else {
let err = {
name: "InvalidParameterException",
description: "The parameter is not valid. It should be an integer."
}
throw err
}
} catch (err) {
res.status(403).send(err)
}
})
// SHARED FUNCTIONS
// Builds the associated infos for a given school object
const buildSchool = async (school) => {
// Fetches the school's parent school
let fetchMetaSchoolData = new Promise((resolve, reject) => {
let query =
"SELECT ms.id, ms.name " +
"FROM meta_school AS ms " +
"WHERE ms.id = " + school.id_meta_school
db.query(query, (err, result) => {
if (err) return reject
resolve(result)
})
})
// Builds the school and returns it
school.meta_school = await fetchMetaSchoolData
return school
}
module.exports = router

View File

@@ -6,15 +6,20 @@ let router = express.Router()
const connection = require('../database/connection') const connection = require('../database/connection')
const db = connection.db const db = connection.db
// Model validation
const Validator = require('jsonschema').Validator
const v = new Validator()
const Spell = require("../models/Spell")
v.addSchema(Spell, "/SpellModel")
const getSpells = () => { const getSpells = () => {
let fetchSpellsData = new Promise((resolve, reject) => { let getSpellsPromise = new Promise((resolve, reject) => {
let query = "SELECT DISTINCT * FROM spell" let query = "SELECT DISTINCT * FROM spell"
db.query(query, async (err, result) => { db.query(query, async (err, result) => {
if (err) { return reject } if (err) return reject
if (result.length == 0) { console.log("No spells found") } if (result.length == 0) { console.log("No spell found in database") }
// Loops over the results to fetch the associated tables // Loops over the results to fetch the associated tables
for (let i = 0; i < result.length; i++) { for (let i = 0; i < result.length; i++) {
@@ -23,11 +28,11 @@ const getSpells = () => {
resolve(result) resolve(result)
}) })
}) })
return fetchSpellsData return getSpellsPromise
} }
const getSpell = (id) => { const getSpell = (id) => {
let fetchSpellData = new Promise((resolve, reject) => { let getSpellPromise = new Promise((resolve, reject) => {
let query = "SELECT * FROM spell WHERE id = " + id let query = "SELECT * FROM spell WHERE id = " + id
@@ -37,10 +42,38 @@ const getSpell = (id) => {
resolve(result); resolve(result);
}) })
}) })
return fetchSpellData return getSpellPromise
}
const addSpell = (spell) => {
let addSpellPromise = new Promise((resolve, reject) => {
// Checks if body is empty
if(Object.keys(spell).length === 0 && spell.constructor === Object) {
reject("You can't add an empty spell !")
}
// Check if model validation goes through
if (!v.validate(spell, Spell).valid) {
reject("Schema is not valid")
} else {
resolve(spell)
}
})
return addSpellPromise
}
const updateSpell = (spell) => {
return null;
}
const deleteSpell = (id) => {
return null;
} }
// ROUTES // ROUTES
// Get All
router.get('/', async (req, res, next) => { router.get('/', async (req, res, next) => {
getSpells() getSpells()
.then(v => { .then(v => {
@@ -52,6 +85,8 @@ router.get('/', async (req, res, next) => {
next() next()
}) })
}) })
// Get One
router.get('/:id/', async (req, res, next) => { router.get('/:id/', async (req, res, next) => {
getSpell(req.params.id) getSpell(req.params.id)
.then(v => { .then(v => {
@@ -64,6 +99,30 @@ router.get('/:id/', async (req, res, next) => {
}) })
}) })
// Add One
router.post('/', async (req, res, next) => {
console.log(req.body)
addSpell(req.body)
.then(v => {
res.setHeader('Content-Type', 'application/json;charset=utf-8')
res.send(JSON.stringify(v))
})
.catch(err => {
console.log(err)
next()
})
})
// Update One
router.put('/:id/', async (req, res, next) => {
})
// Delete One
router.delete('/:id/', async (req, res, next) => {
})
// Param validation for single spell // Param validation for single spell
// (check if id is int) (could be refactored) // (check if id is int) (could be refactored)
router.param('id', (req, res, next, id) => { router.param('id', (req, res, next, id) => {