Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const Sequelize = require('sequelize');
- var Validator = require('jsonschema').Validator;
- const bodyParser = require('body-parser');
- var schemas = require('./schemas')
- const db = new Sequelize('','', '', {
- host: 'localhost',
- dialect: 'mysql',
- operatorsAliases: false,
- pool: {
- max: 5,
- min: 0,
- acquire: 30000,
- idle: 10000
- },
- });
- db.authenticate().then(() => {
- console.log('Connection has been established successfully.');
- }).catch(err => {
- console.error('Unable to connect to the database');
- });
- //Model definition
- const models = {
- facultad: db.define('faculta', {
- uuid: {
- type: Sequelize.UUID,
- defaultValue: Sequelize.UUIDV1,
- primaryKey: true
- },
- nombre: Sequelize.STRING
- }),
- grado: db.define('grado', {
- uuid: {
- type: Sequelize.UUID,
- defaultValue: Sequelize.UUIDV1,
- primaryKey: true
- },
- nombre: Sequelize.STRING
- }),
- curso: db.define('curso', {
- uuid: {
- type: Sequelize.UUID,
- defaultValue: Sequelize.UUIDV1,
- primaryKey: true
- },
- nombre: Sequelize.STRING
- }),
- materia: db.define('materia', {
- uuid: {
- type: Sequelize.UUID,
- defaultValue: Sequelize.UUIDV1,
- primaryKey: true
- },
- nombre: Sequelize.STRING,
- abreviatura: Sequelize.STRING
- }),
- grupo: db.define('grupo', {
- uuid: {
- type: Sequelize.UUID,
- defaultValue: Sequelize.UUIDV1,
- primaryKey: true
- },
- nombre: Sequelize.STRING
- }),
- tipo_clase: db.define('tipo_clase', {
- uuid: {
- type: Sequelize.UUID,
- defaultValue: Sequelize.UUIDV1,
- primaryKey: true
- },
- nombre: Sequelize.STRING
- }),
- horario: db.define('horario', {
- uuid: {
- type: Sequelize.UUID,
- defaultValue: Sequelize.UUIDV1,
- primaryKey: true
- },
- nombre: Sequelize.STRING
- }),
- clase: db.define('clase', {
- uuid: {
- type: Sequelize.UUID,
- defaultValue: Sequelize.UUIDV1,
- primaryKey: true
- },
- nombre: Sequelize.STRING,
- horaInicio: Sequelize.TIME,
- horaFinal: Sequelize.TIME
- }),
- }
- //Relation definition
- models.grado.belongsTo(models.facultad)
- models.curso.belongsTo(models.grado)
- models.materia.belongsTo(models.horario)
- models.horario.belongsTo(models.curso)
- models.clase.belongsTo(models.horario)
- models.clase.belongsTo(models.materia)
- models.tipo_clase.belongsTo(models.horario)
- models.grupo.belongsTo(models.tipo_clase)
- function data_test() {
- console.log("ejecutando test de datos")
- models.facultad.build({ nombre: 'Facultad de medicina' }).save().then((cat) => {
- models.grado.build({ nombre: 'Grado en Enfermeria', facultumUuid: cat.dataValues.uuid, isCourse: false }).save().then((cat) => {
- models.curso.build({ nombre: '1-Primer Curso', gradoUuid: cat.dataValues.uuid, isCourse: true }).save().then((curso)=>{
- models.horario.build({cursoUuid: curso.dataValues.uuid}).save().then()
- })
- models.curso.build({ nombre: '2-Segundo Curso', gradoUuid: cat.dataValues.uuid, isCourse: true }).save()
- models.curso.build({ nombre: '3-Tercer Curso', gradoUuid: cat.dataValues.uuid, isCourse: true }).save()
- models.curso.build({ nombre: '4-Cuarto Curso', gradoUuid: cat.dataValues.uuid, isCourse: true }).save()
- })
- models.grado.build({ nombre: 'Grado en Medicina', facultumUuid: cat.dataValues.uuid, isCourse: false }).save().then((cat) => {
- models.curso.build({ nombre: '1-Primer Curso', gradoUuid: cat.dataValues.uuid, isCourse: true }).save()
- models.curso.build({ nombre: '2-Segundo Curso', gradoUuid: cat.dataValues.uuid, isCourse: true }).save()
- models.curso.build({ nombre: '3-Tercer Curso', gradoUuid: cat.dataValues.uuid, isCourse: true }).save()
- models.curso.build({ nombre: '4-Cuarto Curso', gradoUuid: cat.dataValues.uuid, isCourse: true }).save()
- models.curso.build({ nombre: '5-Tercer Curso', gradoUuid: cat.dataValues.uuid, isCourse: true }).save()
- models.curso.build({ nombre: '6-Cuarto Curso', gradoUuid: cat.dataValues.uuid, isCourse: true }).save()
- })
- })
- }
- //Database rebooting
- db.query("SET FOREIGN_KEY_CHECKS = 0")
- .then(function(result){
- return db.sync({force: true});
- }).then(function(){
- return db.query("SET FOREIGN_KEY_CHECKS = 1");
- }).catch(function(err){
- console.log(err)
- });
- const express = require('express');
- const basicAuth = require('express-basic-auth')
- const app = express();
- app.use(function(req,res,next){
- res.setHeader("Access-Control-Allow-Origin","*")
- res.setHeader("Access-Control-Allow-Methods","PUT,")
- res.setHeader('Access-Control-Allow-Headers', 'Content-Type')
- next()
- })
- app.use(bodyParser.json());
- app.get('/', function (req, res) {
- res.send('Uniovi UnOficial API');
- });
- app.get('/facultad/lista', function (req, res) {
- models.facultad.findAll(
- {
- attributes: ["uuid", "nombre"]
- }
- ).then((facultades) => {
- res.send(JSON.stringify(facultades))
- })
- });
- app.get('/grado/lista/:facultumuuid', function (req, res) {
- res.setHeader("content-type", "application/json")
- models.grado.findAll({
- where: {facultumUuid: req.params.facultumuuid}
- }).then((grados) => {
- if (grados.length == 0) {
- res.send({
- error: "Not grades found"
- })
- } else {
- res.send(JSON.stringify(grados))
- }
- console.log()
- })
- });
- app.get('/curso/lista/:gradouuid', function (req, res,next) {
- res.setHeader("content-type", "application/json")
- models.curso.findAll(
- {
- where: { gradouuid: req.params.gradouuid }
- }
- ).then((cursos) => {
- if (cursos.length == 0) {
- error=new Error();
- error.code=4
- error.message="curso no encontrado"
- next(error)
- } else {
- res.json(cursos)
- }
- })
- });
- app.get('/horario/lista/:cursouuid',function(req,res,next) {
- models.horario.findAll({
- where:{cursoUuid: req.params.cursouuid},
- order:[
- ['createdAt', 'ASC']
- ]
- }).then((horarios) => {
- if (horarios.length == 0) {
- error=new Error();
- error.code=4
- error.message="horario no encontrado"
- next(error)
- } else {
- res.json(horarios)
- }
- })
- })
- app.get('/materias/lista/:horariouuid',function(req,res,next) {
- models.materia.findAll({
- where:{horariouuid: req.params.horariouuid}
- }).then((tipoclases) => {
- if (tipoclases.length == 0) {
- error=new Error();
- error.code=4
- error.message="horario no encontrado"
- next(error)
- } else {
- res.json(tipoclases)
- }
- })
- })
- app.get('/tipoclases/lista/:horariouuid',function(req,res,next) {
- models.grupo_materia.findAll({
- where:{horariouuid: req.params.horariouuid}
- }).then((tipoclases) => {
- if (tipoclases.length == 0) {
- error=new Error();
- error.code=4
- error.message="horario no encontrado"
- next(error)
- } else {
- res.json(tipoclases)
- }
- })
- })
- app.get('/clase/lista/:horariouuid',function(req,res,next) {
- models.dia.findAll({
- where:{horariouuid: req.params.horariouuid},
- include: [{
- model: models.materia,
- where: {
- state: Sequelize.col('project.state'),
- include: [{
- model: Task,
- where: { state: Sequelize.col('project.state') }
- }]
- }
- }]
- }).then((tipoclases) => {
- if (tipoclases.length == 0) {
- error=new Error();
- error.code=4
- error.message="horario no encontrado"
- next(error)
- } else {
- res.json(tipoclases)
- }
- })
- })
- const requireadmin=false
- if(requireadmin){
- app.use('/admin', basicAuth({
- users: {
- 'admin': 'supersecret',
- 'adam': 'password1234',
- 'eve': 'asdfghjkl',
- },
- unauthorizedResponse: (req) => {
- return req.auth
- ? ('Credentials ' + req.auth.user + ':' + req.auth.password + ' rejected')
- : 'No credentials provided'
- }
- }))
- }
- app.put("/admin/horario/add/:cursouuid", function (req, res, next) {
- horariojson=req.body
- if(horariojson===undefined){
- next({
- code:5,
- message:"Bad JSON"
- })
- }else{
- models.curso.findAll({
- where:{uuid: req.params.cursouuid}
- }).then(r =>{
- if(r.length>0){
- models.horario.create({
- cursoUuid:req.params.cursouuid,
- nombre:horariojson.nombre
- })
- res.json({status:"ok"})
- }else{
- next({
- code:4,
- message:"Not found curso"
- })
- }
- })
- }
- })
- app.put("/admin/materia/add/:horariouuid", function (req, res) {
- console.log(1)
- //console.log(res.body)
- //materiajson=JSON.parse(res.body);
- if(materiajson===undefined){
- next({
- code:5,
- message:"Bad JSON"
- })
- }else{
- models.horario.find({
- where:{uuid: req.params.horariouuid}
- }).then(r =>{
- if(r.length>0){
- models.horario.create({
- cursouuid:req.params.horariouuid,
- nombre:materiajson.nombre
- })
- }
- })
- }
- })
- app.put("/admin/tipoclase/add/:horariouuid", function (req, res) {
- tipoclasejson=JSON.parse(res.body);
- if(materiajson===undefined){
- next({
- code:5,
- message:"Bad JSON"
- })
- }else{
- models.horario.find({
- where:{uuid: req.params.horariouuid}
- }).then(r =>{
- if(r.length>0){
- models.grupo_materia.create({
- horariouuid:req.params.horariouuid,
- nombre:tipoclasejson.nombre,
- abreviacion:tipoclasejson.abreviacion
- })
- }
- })
- }
- })
- app.put("/admin/clase/add/:horariouuid", function (req, res) {
- clasejson=JSON.parse(res.body);
- if(clasejson===undefined){
- next({
- code:5,
- message:"Bad JSON"
- })
- }else{
- console.log(new Validator.validate(clasejson,schemas.CREATE_clase))
- models.horario.find({
- where:{uuid: req.params.horariouuid}
- }).then(r =>{
- if(r.length>0){
- models.dia.create({
- nombre:clasejson.nombre,
- horariouuid:clasejson.horariouuid,
- materiumuuid:clasejson.materiumuuid,
- grupoMateriumUuid:clasejson.grupoMateriumUuid,
- horaInicio:clasejson.horaInicio,
- horaFinal:clasejson.horaFinal,
- })
- }
- })
- }
- })
- app.use(function (err, req, res, next) {
- res.code=500
- res.json({
- error:err.code,
- message:err.message
- })
- });
- app.listen(3000, function () {
- console.log('App listening on port 3000!');
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement