+ Error handler and refactoring of the http methods

This commit is contained in:
Alexis
2020-05-16 21:30:35 +02:00
parent 875e92393c
commit 7195b4359b
3 changed files with 184 additions and 111 deletions

13
models/Errors.js Normal file
View File

@@ -0,0 +1,13 @@
// Http error w/ code
class HttpError extends Error {
constructor(code, message) {
super(message)
this.name = "HttpError"
this.code = code
Error.captureStackTrace(this, this.constructor);
}
}
module.exports = {
HttpError
}

View File

@@ -1,8 +1,10 @@
'use strict' 'use strict'
// Router
const express = require('express') const express = require('express')
let router = express.Router() let router = express.Router()
// Connection
const connection = require('../database/connection') const connection = require('../database/connection')
const db = connection.db const db = connection.db
@@ -12,41 +14,32 @@ const v = new Validator()
const School = require("../models/School") const School = require("../models/School")
v.addSchema(School, "/SchoolModel") v.addSchema(School, "/SchoolModel")
// Error handling
const { HttpError } = require('../models/Errors')
// ROUTES
// GET ALL ------------------
const getSchools = () => { const getSchools = () => {
let getSchoolsPromise = new Promise((resolve, reject) => { let getSchoolsPromise = new Promise((resolve, reject) => {
let query = "SELECT DISTINCT * FROM school" let query = "SELECT DISTINCT * FROM school"
db.query(query, async (err, result) => { db.query(query, async (err, result) => {
if (err) return reject if (err) {
if (result.length == 0) { console.log("No school found in database") } reject(new HttpError(500, 'Error: Database error'))
} else if (result.length == 0) {
// Loops over the results to fetch the associated tables reject(new HttpError(404, 'Error: No ressource matching this id'))
for (let i = 0; i < result.length; i++) { } else {
result[i] = await buildSchool(result[i]) result = await buildSchool(result[0])
resolve(result);
} }
resolve(result)
}) })
}) })
.catch(err => { throw err })
return getSchoolsPromise return getSchoolsPromise
} }
const getSchool = (id) => {
let getSchoolPromise = new Promise((resolve, reject) => {
let query = "SELECT * FROM school WHERE id = " + db.escapeId(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) => { router.get('/', async (req, res, next) => {
getSchools() getSchools()
.then(v => { .then(v => {
@@ -54,12 +47,27 @@ router.get('/', async (req, res, next) => {
res.end(JSON.stringify(v)) res.end(JSON.stringify(v))
}) })
.catch(err => { .catch(err => {
console.log(err) res.status(err.code).send(err.message)
next()
}) })
}) })
// Get One
// GET ONE ------------------
const getSchool = (id) => {
let getSchoolPromise = new Promise((resolve, reject) => {
let query = "SELECT * FROM school WHERE id = " + db.escape(id)
db.query(query, async (err, result) => {
if (err) return reject
result = await buildSchool(result[0])
resolve(result);
})
})
.catch(err => { throw err })
return getSchoolPromise
}
router.get('/:id/', async (req, res, next) => { router.get('/:id/', async (req, res, next) => {
getSchool(req.params.id) getSchool(req.params.id)
.then(v => { .then(v => {
@@ -67,8 +75,7 @@ router.get('/:id/', async (req, res, next) => {
res.end(JSON.stringify(v)) res.end(JSON.stringify(v))
}) })
.catch(err => { .catch(err => {
console.log(err) res.status(err.code).send(err.message)
next()
}) })
}) })
@@ -80,18 +87,15 @@ router.param('id', (req, res, next, id) => {
if (regex.test(id)) { if (regex.test(id)) {
next() next()
} else { } else {
let err = { throw new HttpError(403, 'Provided ID must be an integer')
name: "InvalidParameterException",
description: "The parameter is not valid. It should be an integer."
}
throw err
} }
} catch (err) { } catch (err) {
res.status(403).send(err) res.status(err.code).send(err.message)
} }
}) })
// SHARED FUNCTIONS // SHARED FUNCTIONS ------------------
// Builds the associated infos for a given school object // Builds the associated infos for a given school object
const buildSchool = async (school) => { const buildSchool = async (school) => {
@@ -100,17 +104,32 @@ const buildSchool = async (school) => {
let query = let query =
"SELECT ms.id, ms.name " + "SELECT ms.id, ms.name " +
"FROM meta_school AS ms " + "FROM meta_school AS ms " +
"WHERE ms.id = " + db.escapeId(school.id_meta_school) "WHERE ms.id = " + school.id_meta_school
db.query(query, (err, result) => { db.query(query, (err, result) => {
if (err) return reject if (err) {
resolve(result) reject(new HttpError(500, 'Error: Database error'))
} else {
resolve(result);
}
}) })
}) })
.catch(err => {
res.status(403).send(err)
})
// Builds the school and returns it // Builds the school and returns it
school.meta_school = await fetchMetaSchoolData school.meta_school = await fetchMetaSchoolData
return school return school
} }
// Check if spell is null
const isEmptyObject = (obj) => {
if (Object.keys(obj).length === 0 && obj.constructor === Object) {
return true
} else {
return false
}
}
module.exports = router module.exports = router

View File

@@ -1,8 +1,10 @@
'use strict' 'use strict'
// Router
const express = require('express') const express = require('express')
let router = express.Router() let router = express.Router()
// Connection
const connection = require('../database/connection') const connection = require('../database/connection')
const db = connection.db const db = connection.db
@@ -12,68 +14,34 @@ const v = new Validator()
const Spell = require("../models/Spell") const Spell = require("../models/Spell")
v.addSchema(Spell, "/SpellModel") v.addSchema(Spell, "/SpellModel")
// Error handling
const { HttpError } = require('../models/Errors')
// ROUTES
// GET ALL ------------------
const getSpells = () => { const getSpells = () => {
let getSpellsPromise = 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) {
if (result.length == 0) { console.log("No spell found in database") } reject(new HttpError(500, 'Database error'))
} else if (result.length == 0) {
// Loops over the results to fetch the associated tables reject(new HttpError(404, 'No spells were found'))
for (let i = 0; i < result.length; i++) { } else {
result[i] = await buildSpell(result[i]) // Loops over the results to fetch the associated tables
for (let i = 0; i < result.length; i++) {
result[i] = await buildSpell(result[i])
}
resolve(result)
} }
resolve(result)
}) })
}) })
.catch(err => { throw err })
return getSpellsPromise return getSpellsPromise
} }
const getSpell = (id) => {
let getSpellPromise = new Promise((resolve, reject) => {
let query = "SELECT * FROM spell WHERE id = " + db.escapeId(id)
db.query(query, async (err, result) => {
if (err) return reject
result = await buildSpell(result[0])
resolve(result);
})
})
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
// Get All
router.get('/', async (req, res, next) => { router.get('/', async (req, res, next) => {
getSpells() getSpells()
.then(v => { .then(v => {
@@ -81,12 +49,33 @@ router.get('/', async (req, res, next) => {
res.end(JSON.stringify(v)) res.end(JSON.stringify(v))
}) })
.catch(err => { .catch(err => {
console.log(err) res.status(err.code).send(err.message)
next()
}) })
}) })
// Get One
// GET ONE ------------------
const getSpell = (id) => {
let getSpellPromise = new Promise((resolve, reject) => {
let query = "SELECT * FROM spell WHERE id = " + db.escape(id)
db.query(query, async (err, result) => {
if (err) {
reject(new HttpError(500, 'Error: Database error'))
} else if (result.length == 0) {
reject(new HttpError(404, 'Error: No ressource matching this id'))
} else {
result = await buildSpell(result[0])
resolve(result);
}
})
})
.catch(err => { throw err })
return getSpellPromise
}
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 => {
@@ -94,12 +83,28 @@ router.get('/:id/', async (req, res, next) => {
res.end(JSON.stringify(v)) res.end(JSON.stringify(v))
}) })
.catch(err => { .catch(err => {
console.log(err) res.status(err.code).send(err.message)
next()
}) })
}) })
// Add One
// CREATE ONE ------------------
const addSpell = (spell) => {
let addSpellPromise = new Promise((resolve, reject) => {
// Checks if body is empty and
if (isEmptyObject(spell)) {
reject(new Error("Spell cannot be nothing !"))
} else if (!v.validate(spell, Spell).valid) {
reject(new Error("Schema is not valid"))
} else {
resolve(spell)
}
})
.catch(err => { throw err })
return addSpellPromise
}
router.post('/', async (req, res, next) => { router.post('/', async (req, res, next) => {
console.log(req.body) console.log(req.body)
addSpell(req.body) addSpell(req.body)
@@ -108,21 +113,29 @@ router.post('/', async (req, res, next) => {
res.send(JSON.stringify(v)) res.send(JSON.stringify(v))
}) })
.catch(err => { .catch(err => {
console.log(err) res.status(err.code).send(err.message)
next()
}) })
}) })
// Update One
// UPDATE ONE ------------------
const updateSpell = (spell) => {
return null;
}
router.put('/:id/', async (req, res, next) => { router.put('/:id/', async (req, res, next) => {
}) })
// Delete One
// DELETE ONE ------------------
const deleteSpell = (id) => {
return null;
}
router.delete('/:id/', async (req, res, next) => { 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) => {
@@ -142,7 +155,8 @@ router.param('id', (req, res, next, id) => {
} }
}) })
// SHARED FUNCTIONS // SHARED FUNCTIONS ------------------
// Builds the associated infos for a given spell object // Builds the associated infos for a given spell object
const buildSpell = async (spell) => { const buildSpell = async (spell) => {
@@ -152,13 +166,19 @@ const buildSpell = async (spell) => {
"SELECT school.id, school.name " + "SELECT school.id, school.name " +
"FROM spells_schools AS sc " + "FROM spells_schools AS sc " +
"INNER JOIN school AS school ON sc.id_school = school.id " + "INNER JOIN school AS school ON sc.id_school = school.id " +
"WHERE sc.id_spell = " + db.escapeId(spell.id) "WHERE sc.id_spell = " + spell.id
db.query(query, (err, result) => { db.query(query, (err, result) => {
if (err) return reject if (err) {
resolve(result) reject(new HttpError(500, 'Error: Database error'))
} else {
resolve(result);
}
}) })
}) })
.catch(err => {
res.status(403).send(err)
})
// Fetches the spell's variables // Fetches the spell's variables
let fetchSpellVariablesData = new Promise((resolve, reject) => { let fetchSpellVariablesData = new Promise((resolve, reject) => {
@@ -166,13 +186,19 @@ const buildSpell = async (spell) => {
"SELECT variable.id, variable.description " + "SELECT variable.id, variable.description " +
"FROM spells_variables AS sv " + "FROM spells_variables AS sv " +
"INNER JOIN variable AS variable ON sv.id_variable = variable.id " + "INNER JOIN variable AS variable ON sv.id_variable = variable.id " +
"WHERE sv.id_spell = " + db.escapeId(spell.id) "WHERE sv.id_spell = " + spell.id
db.query(query, (err, result) => { db.query(query, (err, result) => {
if (err) return reject if (err) {
resolve(result) reject(new HttpError(500, 'Error: Database error'))
} else {
resolve(result);
}
}) })
}) })
.catch(err => {
res.status(403).send(err)
})
// Fetches the spell's ingredients // Fetches the spell's ingredients
let fetchSpellIngredientsData = new Promise((resolve, reject) => { let fetchSpellIngredientsData = new Promise((resolve, reject) => {
@@ -180,13 +206,19 @@ const buildSpell = async (spell) => {
"SELECT ingredient.id, ingredient.name " + "SELECT ingredient.id, ingredient.name " +
"FROM spells_ingredients AS si " + "FROM spells_ingredients AS si " +
"INNER JOIN ingredient AS ingredient ON si.id_ingredient = ingredient.id " + "INNER JOIN ingredient AS ingredient ON si.id_ingredient = ingredient.id " +
"WHERE si.id_spell = " + db.escapeId(spell.id) "WHERE si.id_spell = " + spell.id
db.query(query, (err, result) => { db.query(query, (err, result) => {
if (err) return reject if (err) {
resolve(result) reject(new HttpError(500, 'Error: Database error'))
} else {
resolve(result)
}
}) })
}) })
.catch(err => {
res.status(403).send(err)
})
// Builds the spell and returns it // Builds the spell and returns it
spell.schools = await fetchSpellSchoolData spell.schools = await fetchSpellSchoolData
@@ -195,4 +227,13 @@ const buildSpell = async (spell) => {
return spell return spell
} }
module.exports = router // Check if spell is null
const isEmptyObject = (obj) => {
if (Object.keys(obj).length === 0 && obj.constructor === Object) {
return true
} else {
return false
}
}
module.exports = router