- Added A TON of stuff, separated everything neatly and cleaned most models

This commit is contained in:
Alexis
2020-06-08 19:55:36 +02:00
parent ce9018f65e
commit 48987b8349
28 changed files with 602 additions and 171 deletions

View File

@@ -8,7 +8,7 @@ const morgan = require('morgan')
const cors = require('cors') // module to format the json response const cors = require('cors') // module to format the json response
// Creates instances of database connections // Creates instances of database connections
const connection = require('./database/connection') const connection = require('./database/bookshelf')
const db = connection.db const db = connection.db
// CONSTANTS // CONSTANTS
@@ -30,4 +30,7 @@ const server = app.listen( port, () => {console.log(`App listening on port ${por
// Routing // Routing
app.use('/api/spells', routes.spells) app.use('/api/spells', routes.spells)
app.use('/api/schools', routes.schools) app.use('/api/schools', routes.schools)
app.use('/api/meta_schools', routes.meta_schools)
app.use('/api/variables', routes.variables)
app.use('/api/ingredients', routes.ingredients)
app.use('/api/users', routes.users) app.use('/api/users', routes.users)

View File

@@ -0,0 +1,13 @@
'use strict'
const bookshelf = require('../database/bookshelf').bookshelf
require('./spell-model')
let Ingredient = bookshelf.Model.extend({
tableName: 'ingredient',
spells() {
return this.belongsToMany( 'Spell', 'spell_ingredient')
}
})
module.exports = bookshelf.model('Ingredient', Ingredient)

View File

@@ -0,0 +1,13 @@
'use strict'
const bookshelf = require('../database/bookshelf').bookshelf
require('./school-model')
let MetaSchool = bookshelf.Model.extend({
tableName: 'meta_school',
schools() {
return this.hasMany( 'School' )
}
})
module.exports = bookshelf.model('MetaSchool', MetaSchool)

17
models/school-model.js Normal file
View File

@@ -0,0 +1,17 @@
'use strict'
const bookshelf = require('../database/bookshelf').bookshelf
require('./spell-model')
require('./meta-school-model')
let School = bookshelf.Model.extend({
tableName: 'school',
spells() {
return this.belongsToMany( 'Spell', 'spell_school')
},
meta_schools() {
return this.belongsTo( 'MetaSchool', 'meta_school_id')
}
})
module.exports = bookshelf.model('School', School)

21
models/spell-model.js Normal file
View File

@@ -0,0 +1,21 @@
'use strict'
const bookshelf = require('../database/bookshelf').bookshelf
require('./school-model')
require('./variable-model')
require('./ingredient-model')
let Spell = bookshelf.Model.extend({
tableName: 'spell',
schools() {
return this.belongsToMany( 'School', 'spell_school' )
},
variables() {
return this.belongsToMany( 'Variable', 'spell_variable' )
},
ingredients() {
return this.belongsToMany( 'Ingredient', 'spell_ingredient' )
}
})
module.exports = bookshelf.model('Spell', Spell)

8
models/user-model.js Normal file
View File

@@ -0,0 +1,8 @@
'use strict'
const bookshelf = require('../database/bookshelf').bookshelf
let User = bookshelf.Model.extend({
tableName: 'user',
})
module.exports = bookshelf.model('User', User)

13
models/variable-model.js Normal file
View File

@@ -0,0 +1,13 @@
'use strict'
const bookshelf = require('../database/bookshelf').bookshelf
require('./spell-model')
let Variable = bookshelf.Model.extend({
tableName: 'variable',
spells() {
return this.belongsToMany( 'Spell', 'spell_variable')
}
})
module.exports = bookshelf.model('Variable', Variable)

View File

@@ -1,27 +1,55 @@
'use strict' 'use strict'
// Bookshelf // Bookshelf
const bookshelf = require('../database/connection').bookshelf const bookshelf = require('../database/bookshelf').bookshelf
const model = require('../models/ingredient-model')
const Spells = require('./spell-repository') // Model validation
const Validator = require('jsonschema').Validator
const v = new Validator()
const IngredientValidation = require("../validations/IngredientValidation")
v.addSchema(IngredientValidation, "/IngredientValidation")
// Validations
const regexXSS = RegExp(/<[^>]*script/)
// Error handling
const { HttpError } = require('../validations/Errors')
class IngredientRepository { class IngredientRepository {
constructor() { constructor() {
this.model = bookshelf.Model.extend({
tableName: 'ingredient',
spells() {
return this.belongsToMany( Spells._model, 'spell_ingredient', 'ingredient_id', 'spell_id')
} }
getAll() {
return new Promise((resolve, reject) => {
model.forge()
.fetchAll({ withRelated: ['spells'] })
.then(v => {
resolve(v.toJSON({ omitPivot: true }))
})
.catch(err => {
console.log(err)
reject(new HttpError(500, "Couldn't get ingredients"))
})
}) })
} }
set model(model) {
this._model = model getOne(id) {
return new Promise((resolve, reject) => {
model.forge()
.where({ 'id' : id })
.fetch({ withRelated: ['spells']})
.then(v => {
resolve(v.toJSON({ omitPivot: true }))
})
.catch(err => {
console.log(err)
reject(new HttpError(500, "Couldn't get ingredient"))
})
})
} }
get model() {
return this._model
}
} }
module.exports = IngredientRepository module.exports = IngredientRepository

View File

@@ -1,27 +1,72 @@
'use strict' 'use strict'
// Bookshelf // Bookshelf
const bookshelf = require('../database/connection').bookshelf const bookshelf = require('../database/bookshelf').bookshelf
const model = require('../models/meta-school-model')
const Schools = require('./school-repository') // Model validation
const Validator = require('jsonschema').Validator
const v = new Validator()
const MetaSchoolValidation = require("../validations/MetaSchoolValidation")
v.addSchema(MetaSchoolValidation, "/MetaSchoolValidation")
// Validations
const regexXSS = RegExp(/<[^>]*script/)
// Error handling
const { HttpError } = require('../validations/Errors')
class MetaSchoolRepository { class MetaSchoolRepository {
constructor() { constructor() {
this.model = bookshelf.Model.extend({
tableName: 'meta_school',
schools() {
return this.hasMany( Schools._model )
} }
getAll() {
return new Promise((resolve, reject) => {
model.forge()
.fetchAll({ withRelated: ['schools'] })
.then(v => {
resolve(v.toJSON({ omitPivot: true }))
})
.catch(err => {
console.log(err)
reject(new HttpError(500, "Couldn't get meta schools"))
})
}) })
} }
set model(model) { getOne(id) {
this._model = model return new Promise((resolve, reject) => {
model.forge()
.where({ 'id' : id })
.fetch({ withRelated: ['schools']})
.then(v => {
resolve(v.toJSON({ omitPivot: true }))
})
.catch(err => {
console.log(err)
reject(new HttpError(500, "Couldn't get meta school"))
})
})
} }
get model() { // Check if object is null
return this._model isEmptyObject = (obj) => {
if (Object.keys(obj).length === 0 && obj.constructor === Object) {
return true
} else {
return false
} }
} }
// Check if script injection attempt
isXSSAttempt = (string) => {
if (regexXSS.test(string)) {
return true
} else {
return false
}
}
}
module.exports = MetaSchoolRepository module.exports = MetaSchoolRepository

View File

@@ -1,49 +1,28 @@
'use strict' 'use strict'
// Bookshelf // Bookshelf
const bookshelf = require('../database/connection').bookshelf const bookshelf = require('../database/bookshelf').bookshelf
const model = require('../models/school-model')
const Spells = require('./spell-repository')
const MetaSchoolRepository = require('./meta-school-repository')
const MetaSchools = new MetaSchoolRepository()
// Model validation // Model validation
const Validator = require('jsonschema').Validator const Validator = require('jsonschema').Validator
const v = new Validator() const v = new Validator()
const SchoolModel = require("../models/SchoolValidation") const SchoolValidation = require("../validations/SchoolValidation")
v.addSchema(SchoolModel, "/SchoolModel") v.addSchema(SchoolValidation, "/SchoolValidation")
// Validations // Validations
const regexXSS = RegExp(/<[^>]*script/) const regexXSS = RegExp(/<[^>]*script/)
// Error handling // Error handling
const { HttpError } = require('../models/Errors') const { HttpError } = require('../validations/Errors')
class SchoolRepository { class SchoolRepository {
constructor() { constructor() {
this.model = bookshelf.Model.extend({
tableName: 'school',
spells() {
return this.belongsToMany( Spells._model, 'spell_school', 'school_id', 'spell_id')
},
meta_schools() {
return this.belongsTo( MetaSchools._model, 'meta_school_id')
}
})
}
set model(model) {
this._model = model
}
get model() {
return this._model
} }
getAll() { getAll() {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this._model.forge() model.forge()
.fetchAll({ withRelated: ['meta_schools'] }) .fetchAll({ withRelated: ['meta_schools'] })
.then(v => { .then(v => {
resolve(v.toJSON({ omitPivot: true })) resolve(v.toJSON({ omitPivot: true }))
@@ -57,7 +36,7 @@ class SchoolRepository {
getOne(id) { getOne(id) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this._model.forge() model.forge()
.where({ 'id' : id }) .where({ 'id' : id })
.fetch({ withRelated: ['meta_schools']}) .fetch({ withRelated: ['meta_schools']})
.then(v => { .then(v => {
@@ -75,13 +54,13 @@ class SchoolRepository {
// Checks if body exists and if the model fits, and throws errors if it doesn't // Checks if body exists and if the model fits, and throws errors if it doesn't
if (this.isEmptyObject(s)) { if (this.isEmptyObject(s)) {
reject(new HttpError(403, "Error: School cannot be nothing !")) reject(new HttpError(403, "Error: School cannot be nothing !"))
} else if (!v.validate(s, SchoolModel).valid) { } else if (!v.validate(s, SchoolValidation).valid) {
reject(new HttpError(403, "Error: Schema is not valid - " + v.validate(s, SchoolModel).errors)) reject(new HttpError(403, "Error: Schema is not valid - " + v.validate(s, SchoolValidation).errors))
} else if (this.isXSSAttempt(s.name) || this.isXSSAttempt(s.description)) { } else if (this.isXSSAttempt(s.name) || this.isXSSAttempt(s.description)) {
reject(new HttpError(403, 'Injection attempt detected, aborting the request.')) reject(new HttpError(403, 'Injection attempt detected, aborting the request.'))
} else { } else {
bookshelf.transaction(t => { bookshelf.transaction(t => {
return this._model.forge({ return model.forge({
'name': s.name, 'name': s.name,
'description': s.description, 'description': s.description,
'meta_school_id': s.meta_school_id, 'meta_school_id': s.meta_school_id,
@@ -111,12 +90,12 @@ class SchoolRepository {
// Checks if body exists and if the model fits, and throws errors if it doesn't // Checks if body exists and if the model fits, and throws errors if it doesn't
if (this.isEmptyObject(s)) { if (this.isEmptyObject(s)) {
reject(new HttpError(403, "Error: School cannot be nothing !")) reject(new HttpError(403, "Error: School cannot be nothing !"))
} else if (!v.validate(s, SchoolModel).valid) { } else if (!v.validate(s, SchoolValidation).valid) {
reject(new HttpError(403, "Error: Schema is not valid - " + v.validate(s, SchoolModel).errors)) reject(new HttpError(403, "Error: Schema is not valid - " + v.validate(s, SchoolValidation).errors))
} else if (this.isXSSAttempt(s.name) || this.isXSSAttempt(s.description)) { } else if (this.isXSSAttempt(s.name) || this.isXSSAttempt(s.description)) {
reject(new HttpError(403, 'Injection attempt detected, aborting the request.')) reject(new HttpError(403, 'Injection attempt detected, aborting the request.'))
} else { } else {
this._model.forge({id: id}) model.forge({id: id})
.fetch({require: true, withRelated: ['meta_schools']}) .fetch({require: true, withRelated: ['meta_schools']})
.then(v => { .then(v => {
bookshelf.transaction(t => { bookshelf.transaction(t => {
@@ -154,11 +133,12 @@ class SchoolRepository {
deleteOne(id) { deleteOne(id) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this._model.forge() model.forge()
.where({ 'id' : id }) .where({ 'id' : id })
.fetch({require: true, withRelated: ['spells', 'meta_schools']}) .fetch({require: true, withRelated: ['spells', 'meta_schools']})
.then(v => { .then(v => {
v.spells().detach()
v.destroy()
}) })
.then(() => { .then(() => {
resolve({ resolve({

View File

@@ -1,57 +1,28 @@
'use strict' 'use strict'
// Bookshelf // Bookshelf
const bookshelf = require('../database/connection').bookshelf const bookshelf = require('../database/bookshelf').bookshelf
const model = require('../models/spell-model')
const SchoolRepository = require('./school-repository')
const Schools = new SchoolRepository()
const IngredientRepository = require('./ingredient-repository')
const Ingredients = new IngredientRepository()
const VariableRepository = require('./variable-repository')
const Variables = new VariableRepository()
// Model validation // Model validation
const Validator = require('jsonschema').Validator const Validator = require('jsonschema').Validator
const v = new Validator() const v = new Validator()
const SpellModel = require("../models/SpellValidation") const SpellValidation = require("../validations/SpellValidation")
v.addSchema(SpellModel, "/SpellModel") v.addSchema(SpellValidation, "/SpellValidation")
// Validations // Validations
const regexXSS = RegExp(/<[^>]*script/) const regexXSS = RegExp(/<[^>]*script/)
// Error handling // Error handling
const { HttpError } = require('../models/Errors') const { HttpError } = require('../validations/Errors')
class SpellRepository { class SpellRepository {
constructor() { constructor() {
this.model = bookshelf.Model.extend({
tableName: 'spell',
schools() {
return this.belongsToMany( Schools._model, 'spell_school', 'spell_id', 'school_id' )
},
variables() {
return this.belongsToMany( Variables._model, 'spell_variable', 'spell_id', 'variable_id' )
},
ingredients() {
return this.belongsToMany( Ingredients._model, 'spell_ingredient', 'spell_id', 'ingredient_id' )
}
})
}
set model(model) {
this._model = model
}
get model() {
return this._model
} }
getAll() { getAll() {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this._model.forge() model.forge()
.fetchAll({ withRelated: ['schools.meta_schools', 'variables', 'ingredients'] }) .fetchAll({ withRelated: ['schools.meta_schools', 'variables', 'ingredients'] })
.then(v => { .then(v => {
resolve(v.toJSON({ omitPivot: true })) resolve(v.toJSON({ omitPivot: true }))
@@ -65,7 +36,7 @@ class SpellRepository {
getOne(id) { getOne(id) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this._model.forge() model.forge()
.where({ 'id' : id }) .where({ 'id' : id })
.fetch({ withRelated: ['schools.meta_schools', 'variables', 'ingredients']}) .fetch({ withRelated: ['schools.meta_schools', 'variables', 'ingredients']})
.then(v => { .then(v => {
@@ -83,13 +54,13 @@ class SpellRepository {
// Checks if body exists and if the model fits, and throws errors if it doesn't // Checks if body exists and if the model fits, and throws errors if it doesn't
if (this.isEmptyObject(s)) { if (this.isEmptyObject(s)) {
reject(new HttpError(403, "Error: Spell cannot be nothing !")) reject(new HttpError(403, "Error: Spell cannot be nothing !"))
} else if (!v.validate(s, SpellModel).valid) { } else if (!v.validate(s, SpellValidation).valid) {
reject(new HttpError(403, "Error: Schema is not valid - " + v.validate(s, SpellModel).errors)) reject(new HttpError(403, "Error: Schema is not valid - " + v.validate(s, SpellValidation).errors))
} else if (this.isXSSAttempt(s.name) || this.isXSSAttempt(s.description) || this.isXSSAttempt(s.cost)) { } else if (this.isXSSAttempt(s.name) || this.isXSSAttempt(s.description) || this.isXSSAttempt(s.cost)) {
reject(new HttpError(403, 'Injection attempt detected, aborting the request.')) reject(new HttpError(403, 'Injection attempt detected, aborting the request.'))
} else { } else {
bookshelf.transaction(t => { bookshelf.transaction(t => {
return this._model.forge({ return model.forge({
'name': s.name, 'name': s.name,
'description': s.description, 'description': s.description,
'level': s.level, 'level': s.level,
@@ -143,12 +114,12 @@ class SpellRepository {
// Checks if body exists and if the model fits, and throws errors if it doesn't // Checks if body exists and if the model fits, and throws errors if it doesn't
if (this.isEmptyObject(s)) { if (this.isEmptyObject(s)) {
reject(new HttpError(403, "Error: Spell cannot be nothing !")) reject(new HttpError(403, "Error: Spell cannot be nothing !"))
} else if (!v.validate(s, SpellModel).valid) { } else if (!v.validate(s, SpellValidation).valid) {
reject(new HttpError(403, "Error: Schema is not valid - " + v.validate(s, SpellModel).errors)) reject(new HttpError(403, "Error: Schema is not valid - " + v.validate(s, SpellValidation).errors))
} else if (this.isXSSAttempt(s.name) || this.isXSSAttempt(s.description) || this.isXSSAttempt(s.cost)) { } else if (this.isXSSAttempt(s.name) || this.isXSSAttempt(s.description) || this.isXSSAttempt(s.cost)) {
reject(new HttpError(403, 'Injection attempt detected, aborting the request.')) reject(new HttpError(403, 'Injection attempt detected, aborting the request.'))
} else { } else {
this._model.forge({id: id}) model.forge({id: id})
.fetch({require: true, withRelated: ['schools.meta_schools', 'variables', 'ingredients']}) .fetch({require: true, withRelated: ['schools.meta_schools', 'variables', 'ingredients']})
.then(v => { .then(v => {
bookshelf.transaction(t => { bookshelf.transaction(t => {
@@ -231,14 +202,14 @@ class SpellRepository {
deleteOne(id) { deleteOne(id) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this._model.forge() model.forge()
.where({ 'id' : id }) .where({ 'id' : id })
.fetch({require: true, withRelated: ['schools.meta_schools', 'variables', 'ingredients']}) .fetch({require: true, withRelated: ['schools.meta_schools', 'variables', 'ingredients']})
.then(v => { .then(v => {
v.schools().detach(); v.schools().detach()
v.variables().detach(); v.variables().detach()
v.ingredients().detach(); v.ingredients().detach()
v.destroy(); v.destroy()
}) })
.then(() => { .then(() => {
resolve({ resolve({

View File

@@ -1,7 +1,7 @@
'use strict' 'use strict'
// Bookshelf // Bookshelf
const bookshelf = require('../database/connection').bookshelf const bookshelf = require('../database/bookshelf').bookshelf
const model = require('../models/user-model')
// Hashing and passwords // Hashing and passwords
const bcrypt = require('bcrypt') const bcrypt = require('bcrypt')
@@ -9,29 +9,18 @@ const bcrypt = require('bcrypt')
// Model validation // Model validation
const Validator = require('jsonschema').Validator const Validator = require('jsonschema').Validator
const v = new Validator() const v = new Validator()
const UserModel = require("../models/UserValidation") const UserValidation = require("../validations/UserValidation")
v.addSchema(UserModel, "/UserModel") v.addSchema(UserValidation, "/UserValidation")
// Validations // Validations
const regexInt = RegExp(/^[1-9]\d*$/)
const regexXSS = RegExp(/<[^>]*script/) const regexXSS = RegExp(/<[^>]*script/)
// Error handling // Error handling
const { HttpError } = require('../models/Errors') const { HttpError } = require('../validations/Errors')
class UserRepository { class UserRepository {
constructor() { constructor() {
this.model = bookshelf.Model.extend({
tableName: 'user',
})
}
set model(model) {
this._model = model
}
get model() {
return this._model
} }
getAll() { getAll() {

View File

@@ -1,26 +1,47 @@
'use strict' 'use strict'
// Bookshelf // Bookshelf
const bookshelf = require('../database/connection').bookshelf const bookshelf = require('../database/bookshelf').bookshelf
const model = require('../models/variable-model')
const Spells = require('./spell-repository') // Model validation
const Validator = require('jsonschema').Validator
const v = new Validator()
const VariableValidation = require("../validations/VariableValidation")
v.addSchema(VariableValidation, "/VariableValidation")
class VariableRepository { class VariableRepository {
constructor() { constructor() {
this.model = bookshelf.Model.extend({
tableName: 'variable',
spells() {
return this.belongsToMany( Spells._model, 'spell_variable', 'variable_id', 'spell_id')
} }
getAll() {
return new Promise((resolve, reject) => {
model.forge()
.fetchAll({ withRelated: ['spells'] })
.then(v => {
resolve(v.toJSON({ omitPivot: true }))
})
.catch(err => {
console.log(err)
reject(new HttpError(500, "Couldn't get variables"))
})
}) })
} }
set model(model) {
this._model = model
}
get model() { getOne(id) {
return this._model return new Promise((resolve, reject) => {
model.forge()
.where({ 'id' : id })
.fetch({ withRelated: ['spells']})
.then(v => {
resolve(v.toJSON({ omitPivot: true }))
})
.catch(err => {
console.log(err)
reject(new HttpError(500, "Couldn't get variable"))
})
})
} }
} }

View File

@@ -1,9 +1,15 @@
const users = require('./users')
const spells = require('./spells') const spells = require('./spells')
const schools = require('./schools') const schools = require('./schools')
const meta_schools = require('./meta_schools')
const variables = require('./variables')
const ingredients = require('./ingredients')
const users = require('./users')
module.exports = { module.exports = {
spells, spells,
schools, schools,
users meta_schools,
ingredients,
variables,
users,
} }

90
routes/ingredients.js Normal file
View File

@@ -0,0 +1,90 @@
'use strict'
// Router
const express = require('express')
let router = express.Router()
// Connection
const connection = require('../database/bookshelf')
const db = connection.db
// Repository
const IngredientRepository = require('../repositories/ingredient-repository');
const Ingredients = new IngredientRepository();
const regexInt = RegExp(/^[1-9]\d*$/)
// Error handling
const { HttpError } = require('../validations/Errors')
// ROUTES
// GET ALL ------------------
const getIngredients = () => {
return Ingredients.getAll()
.catch(err => {
console.log(err)
throw err
})
}
router.get('/', async (req, res) => {
getIngredients()
.then(v => {
res.setHeader('Content-Type', 'application/json;charset=utf-8')
res.end(JSON.stringify(v))
})
.catch(err => {
res.status(err.code).send(JSON.stringify(
{
"error": err.message,
"code": err.code
})
)
})
})
// GET ONE ------------------
const getIngredient = (id) => {
return Ingredients.getOne(id)
.catch(err => {
console.log(err)
throw err
})
}
router.get('/:id/', async (req, res) => {
getIngredient(req.params.id)
.then(v => {
res.setHeader('Content-Type', 'application/json;charset=utf-8')
res.end(JSON.stringify(v))
})
.catch(err => {
res.status(err.code).send(JSON.stringify(
{
"error": err.message,
"code": err.code
})
)
})
})
// Param validation for ID
// (check if id is int) (could be refactored)
router.param('id', (req, res, next, id) => {
try {
if (regexInt.test(id)) {
next()
} else {
throw new Error;
}
} catch (err) {
err = new HttpError(403, 'Provided ID must be an integer and not zero')
res.status(err.code).send(JSON.stringify(
{
"error": err.message,
"code": err.code
})
)
}
})
module.exports = router

91
routes/meta_schools.js Normal file
View File

@@ -0,0 +1,91 @@
'use strict'
// Router
const express = require('express')
let router = express.Router()
// Connection
const connection = require('../database/bookshelf')
const db = connection.db
// Repository
const MetaSchoolRepository = require('../repositories/meta-school-repository');
const MetaSchools = new MetaSchoolRepository();
const regexInt = RegExp(/^[1-9]\d*$/)
// Error handling
const { HttpError } = require('../validations/Errors')
// ROUTES
// GET ALL ------------------
const getMetaSchools = () => {
return MetaSchools.getAll()
.catch(err => {
console.log(err)
throw err
})
}
router.get('/', async (req, res) => {
getMetaSchools()
.then(v => {
res.setHeader('Content-Type', 'application/json;charset=utf-8')
res.end(JSON.stringify(v))
})
.catch(err => {
res.status(err.code).send(JSON.stringify(
{
"error": err.message,
"code": err.code
})
)
})
})
// GET ONE ------------------
const getMetaSchool = (id) => {
return MetaSchools.getOne(id)
.catch(err => {
console.log(err)
throw err
})
}
router.get('/:id/', async (req, res) => {
getMetaSchool(req.params.id)
.then(v => {
res.setHeader('Content-Type', 'application/json;charset=utf-8')
res.end(JSON.stringify(v))
})
.catch(err => {
res.status(err.code).send(JSON.stringify(
{
"error": err.message,
"code": err.code
})
)
})
})
// Param validation for ID
// (check if id is int) (could be refactored)
router.param('id', (req, res, next, id) => {
try {
if (regexInt.test(id)) {
next()
} else {
throw new Error;
}
} catch (err) {
err = new HttpError(403, 'Provided ID must be an integer and not zero')
res.status(err.code).send(JSON.stringify(
{
"error": err.message,
"code": err.code
})
)
}
})
module.exports = router

View File

@@ -5,7 +5,7 @@ const express = require('express')
let router = express.Router() let router = express.Router()
// Connection // Connection
const connection = require('../database/connection') const connection = require('../database/bookshelf')
const db = connection.db const db = connection.db
// Repository // Repository
@@ -15,7 +15,7 @@ const Schools = new SchoolRepository();
const regexInt = RegExp(/^[1-9]\d*$/) const regexInt = RegExp(/^[1-9]\d*$/)
// Error handling // Error handling
const { HttpError } = require('../models/Errors') const { HttpError } = require('../validations/Errors')
// ROUTES // ROUTES
// GET ALL ------------------ // GET ALL ------------------
@@ -162,4 +162,3 @@ router.delete('/:id/', async (req, res) => {
}) })
module.exports = router module.exports = router

View File

@@ -5,7 +5,7 @@ const express = require('express')
let router = express.Router() let router = express.Router()
// Connection // Connection
const connection = require('../database/connection') const connection = require('../database/bookshelf')
const db = connection.db const db = connection.db
// Repository // Repository
@@ -15,7 +15,7 @@ const Spells = new SpellReposity();
const regexInt = RegExp(/^[1-9]\d*$/) const regexInt = RegExp(/^[1-9]\d*$/)
// Error handling // Error handling
const { HttpError } = require('../models/Errors') const { HttpError } = require('../validations/Errors')
// ROUTES // ROUTES
// GET ALL ------------------ // GET ALL ------------------

View File

@@ -5,7 +5,7 @@ const express = require('express')
let router = express.Router() let router = express.Router()
// Connection // Connection
const connection = require('../database/connection') const connection = require('../database/bookshelf')
const db = connection.db const db = connection.db
// Repository // Repository
@@ -15,7 +15,7 @@ const Users = new UserRepository();
const regexInt = RegExp(/^[1-9]\d*$/) const regexInt = RegExp(/^[1-9]\d*$/)
// Error handling // Error handling
const { HttpError } = require('../models/Errors') const { HttpError } = require('../validations/Errors')
// ROUTES // ROUTES
// GET ALL ------------------ // GET ALL ------------------

91
routes/variables.js Normal file
View File

@@ -0,0 +1,91 @@
'use strict'
// Router
const express = require('express')
let router = express.Router()
// Connection
const connection = require('../database/bookshelf')
const db = connection.db
// Repository
const VariableRepository = require('../repositories/variable-repository');
const Variables = new VariableRepository();
const regexInt = RegExp(/^[1-9]\d*$/)
// Error handling
const { HttpError } = require('../validations/Errors')
// ROUTES
// GET ALL ------------------
const getvariables = () => {
return Variables.getAll()
.catch(err => {
console.log(err)
throw err
})
}
router.get('/', async (req, res) => {
getvariables()
.then(v => {
res.setHeader('Content-Type', 'application/json;charset=utf-8')
res.end(JSON.stringify(v))
})
.catch(err => {
res.status(err.code).send(JSON.stringify(
{
"error": err.message,
"code": err.code
})
)
})
})
// GET ONE ------------------
const getVariable = (id) => {
return Variables.getOne(id)
.catch(err => {
console.log(err)
throw err
})
}
router.get('/:id/', async (req, res) => {
getVariable(req.params.id)
.then(v => {
res.setHeader('Content-Type', 'application/json;charset=utf-8')
res.end(JSON.stringify(v))
})
.catch(err => {
res.status(err.code).send(JSON.stringify(
{
"error": err.message,
"code": err.code
})
)
})
})
// Param validation for ID
// (check if id is int) (could be refactored)
router.param('id', (req, res, next, id) => {
try {
if (regexInt.test(id)) {
next()
} else {
throw new Error;
}
} catch (err) {
err = new HttpError(403, 'Provided ID must be an integer and not zero')
res.status(err.code).send(JSON.stringify(
{
"error": err.message,
"code": err.code
})
)
}
})
module.exports = router

View File

@@ -0,0 +1,10 @@
const Ingredient = {
"id": "/IngredientValidation",
"type": Object,
"properties": {
"name": { "type": "string" },
},
"required": ["name"]
}
module.exports = Ingredient

View File

@@ -0,0 +1,12 @@
const MetaSchool = {
"id": "/MetaSchoolValidation",
"type": Object,
"properties": {
"name": { "type": "string" },
"description": { "type": "string" },
"schools": { "type": "array" }
},
"required": ["name", "description"]
}
module.exports = MetaSchool

View File

@@ -1,5 +1,5 @@
const School = { const School = {
"id": "/SchoolModel", "id": "/SchoolValidation",
"type": Object, "type": Object,
"properties": { "properties": {
"name": { "type": "string" }, "name": { "type": "string" },

View File

@@ -1,5 +1,5 @@
const SpellModel = { const Spell = {
"id": "/SpellModel", "id": "/SpellValidation",
"type": Object, "type": Object,
"properties": { "properties": {
"name": { "type": "string" }, "name": { "type": "string" },
@@ -36,4 +36,4 @@ const SpellModel = {
"required": ["name", "description"] "required": ["name", "description"]
} }
module.exports = SpellModel module.exports = Spell

View File

@@ -1,5 +1,5 @@
const User = { const User = {
"id": "/UserModel", "id": "/UserValidation",
"type": Object, "type": Object,
"properties": { "properties": {
"name": { "type": "string" }, "name": { "type": "string" },

View File

@@ -0,0 +1,10 @@
const Variable = {
"id": "/VariableValidation",
"type": Object,
"properties": {
"description": { "type": "string" },
},
"required": ["description"]
}
module.exports = Variable