Advertisement
Guest User

Untitled

a guest
Feb 25th, 2019
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const Sequelize = require('sequelize');
  2. var Validator = require('jsonschema').Validator;
  3. const bodyParser = require('body-parser');
  4. var schemas = require('./schemas')
  5. const db = new Sequelize('','', '', {
  6.   host: 'localhost',
  7.   dialect: 'mysql',
  8.   operatorsAliases: false,
  9.  
  10.   pool: {
  11.     max: 5,
  12.     min: 0,
  13.     acquire: 30000,
  14.     idle: 10000
  15.   },
  16. });
  17.  
  18. db.authenticate().then(() => {
  19.   console.log('Connection has been established successfully.');
  20. }).catch(err => {
  21.   console.error('Unable to connect to the database');
  22. });
  23.  
  24.  
  25. //Model definition
  26.  
  27. const models = {
  28.   facultad: db.define('faculta', {
  29.     uuid: {
  30.       type: Sequelize.UUID,
  31.       defaultValue: Sequelize.UUIDV1,
  32.       primaryKey: true
  33.     },
  34.     nombre: Sequelize.STRING
  35.   }),
  36.  
  37.   grado: db.define('grado', {
  38.     uuid: {
  39.       type: Sequelize.UUID,
  40.       defaultValue: Sequelize.UUIDV1,
  41.       primaryKey: true
  42.     },
  43.     nombre: Sequelize.STRING
  44.   }),
  45.  
  46.   curso: db.define('curso', {
  47.     uuid: {
  48.       type: Sequelize.UUID,
  49.       defaultValue: Sequelize.UUIDV1,
  50.       primaryKey: true
  51.     },
  52.     nombre: Sequelize.STRING
  53.   }),
  54.  
  55.   materia: db.define('materia', {
  56.     uuid: {
  57.       type: Sequelize.UUID,
  58.       defaultValue: Sequelize.UUIDV1,
  59.       primaryKey: true
  60.     },
  61.     nombre: Sequelize.STRING,
  62.     abreviatura: Sequelize.STRING
  63.   }),
  64.  
  65.   grupo: db.define('grupo', {
  66.     uuid: {
  67.       type: Sequelize.UUID,
  68.       defaultValue: Sequelize.UUIDV1,
  69.       primaryKey: true
  70.     },
  71.     nombre: Sequelize.STRING
  72.   }),
  73.  
  74.   tipo_clase: db.define('tipo_clase', {
  75.     uuid: {
  76.       type: Sequelize.UUID,
  77.       defaultValue: Sequelize.UUIDV1,
  78.       primaryKey: true
  79.     },
  80.     nombre: Sequelize.STRING
  81.   }),
  82.  
  83.   horario: db.define('horario', {
  84.     uuid: {
  85.       type: Sequelize.UUID,
  86.       defaultValue: Sequelize.UUIDV1,
  87.       primaryKey: true
  88.     },
  89.     nombre: Sequelize.STRING
  90.   }),
  91.  
  92.   clase: db.define('clase', {
  93.     uuid: {
  94.       type: Sequelize.UUID,
  95.       defaultValue: Sequelize.UUIDV1,
  96.       primaryKey: true
  97.     },
  98.     nombre: Sequelize.STRING,
  99.     horaInicio: Sequelize.TIME,
  100.     horaFinal: Sequelize.TIME
  101.   }),
  102.  
  103. }
  104.  
  105. //Relation definition
  106. models.grado.belongsTo(models.facultad)
  107. models.curso.belongsTo(models.grado)
  108.  
  109. models.materia.belongsTo(models.horario)
  110.  
  111.  
  112. models.horario.belongsTo(models.curso)
  113. models.clase.belongsTo(models.horario)
  114. models.clase.belongsTo(models.materia)
  115.  
  116. models.tipo_clase.belongsTo(models.horario)
  117. models.grupo.belongsTo(models.tipo_clase)
  118.  
  119.  
  120. function data_test() {
  121.   console.log("ejecutando test de datos")
  122.   models.facultad.build({ nombre: 'Facultad de medicina' }).save().then((cat) => {
  123.     models.grado.build({ nombre: 'Grado en Enfermeria', facultumUuid: cat.dataValues.uuid, isCourse: false }).save().then((cat) => {
  124.       models.curso.build({ nombre: '1-Primer Curso', gradoUuid: cat.dataValues.uuid, isCourse: true }).save().then((curso)=>{
  125.         models.horario.build({cursoUuid: curso.dataValues.uuid}).save().then()
  126.       })
  127.       models.curso.build({ nombre: '2-Segundo Curso', gradoUuid: cat.dataValues.uuid, isCourse: true }).save()
  128.       models.curso.build({ nombre: '3-Tercer Curso', gradoUuid: cat.dataValues.uuid, isCourse: true }).save()
  129.       models.curso.build({ nombre: '4-Cuarto Curso', gradoUuid: cat.dataValues.uuid, isCourse: true }).save()
  130.     })
  131.     models.grado.build({ nombre: 'Grado en Medicina', facultumUuid: cat.dataValues.uuid, isCourse: false }).save().then((cat) => {
  132.       models.curso.build({ nombre: '1-Primer Curso', gradoUuid: cat.dataValues.uuid, isCourse: true }).save()
  133.       models.curso.build({ nombre: '2-Segundo Curso', gradoUuid: cat.dataValues.uuid, isCourse: true }).save()
  134.       models.curso.build({ nombre: '3-Tercer Curso', gradoUuid: cat.dataValues.uuid, isCourse: true }).save()
  135.       models.curso.build({ nombre: '4-Cuarto Curso', gradoUuid: cat.dataValues.uuid, isCourse: true }).save()
  136.       models.curso.build({ nombre: '5-Tercer Curso', gradoUuid: cat.dataValues.uuid, isCourse: true }).save()
  137.       models.curso.build({ nombre: '6-Cuarto Curso', gradoUuid: cat.dataValues.uuid, isCourse: true }).save()
  138.     })
  139.   })
  140. }
  141.  
  142. //Database rebooting
  143.  
  144. db.query("SET FOREIGN_KEY_CHECKS = 0")
  145. .then(function(result){
  146.    return db.sync({force: true});
  147. }).then(function(){
  148.    return db.query("SET FOREIGN_KEY_CHECKS = 1");
  149. }).catch(function(err){
  150.    console.log(err)
  151. });
  152.  
  153.  
  154. const express = require('express');
  155. const basicAuth = require('express-basic-auth')
  156. const app = express();
  157.  
  158. app.use(function(req,res,next){
  159.   res.setHeader("Access-Control-Allow-Origin","*")
  160.   res.setHeader("Access-Control-Allow-Methods","PUT,")
  161.   res.setHeader('Access-Control-Allow-Headers', 'Content-Type')
  162.   next()
  163. })
  164. app.use(bodyParser.json());
  165.  
  166. app.get('/', function (req, res) {
  167.   res.send('Uniovi UnOficial API');
  168. });
  169.  
  170. app.get('/facultad/lista', function (req, res) {
  171.   models.facultad.findAll(
  172.     {
  173.       attributes: ["uuid", "nombre"]
  174.     }
  175.   ).then((facultades) => {
  176.     res.send(JSON.stringify(facultades))
  177.   })
  178. });
  179.  
  180. app.get('/grado/lista/:facultumuuid', function (req, res) {
  181.   res.setHeader("content-type", "application/json")
  182.   models.grado.findAll({
  183.     where: {facultumUuid: req.params.facultumuuid}
  184.   }).then((grados) => {
  185.     if (grados.length == 0) {
  186.       res.send({
  187.         error: "Not grades found"
  188.       })
  189.     } else {
  190.       res.send(JSON.stringify(grados))
  191.     }
  192.     console.log()
  193.   })
  194. });
  195.  
  196. app.get('/curso/lista/:gradouuid', function (req, res,next) {
  197.   res.setHeader("content-type", "application/json")
  198.   models.curso.findAll(
  199.     {
  200.       where: { gradouuid: req.params.gradouuid }
  201.     }
  202.   ).then((cursos) => {
  203.     if (cursos.length == 0) {
  204.       error=new Error();
  205.       error.code=4
  206.       error.message="curso no encontrado"
  207.       next(error)
  208.     } else {
  209.       res.json(cursos)
  210.     }
  211.   })
  212. });
  213.  
  214. app.get('/horario/lista/:cursouuid',function(req,res,next) {
  215.   models.horario.findAll({
  216.     where:{cursoUuid: req.params.cursouuid},
  217.     order:[
  218.       ['createdAt', 'ASC']
  219.     ]
  220.   }).then((horarios) => {
  221.     if (horarios.length == 0) {
  222.       error=new Error();
  223.       error.code=4
  224.       error.message="horario no encontrado"
  225.       next(error)
  226.     } else {
  227.       res.json(horarios)
  228.     }
  229.   })
  230. })
  231.  
  232. app.get('/materias/lista/:horariouuid',function(req,res,next) {
  233.   models.materia.findAll({
  234.     where:{horariouuid: req.params.horariouuid}
  235.   }).then((tipoclases) => {
  236.     if (tipoclases.length == 0) {
  237.       error=new Error();
  238.       error.code=4
  239.       error.message="horario no encontrado"
  240.       next(error)
  241.     } else {
  242.       res.json(tipoclases)
  243.     }
  244.   })
  245. })
  246.  
  247. app.get('/tipoclases/lista/:horariouuid',function(req,res,next) {
  248.   models.grupo_materia.findAll({
  249.     where:{horariouuid: req.params.horariouuid}
  250.   }).then((tipoclases) => {
  251.     if (tipoclases.length == 0) {
  252.       error=new Error();
  253.       error.code=4
  254.       error.message="horario no encontrado"
  255.       next(error)
  256.     } else {
  257.       res.json(tipoclases)
  258.     }
  259.   })
  260. })
  261.  
  262. app.get('/clase/lista/:horariouuid',function(req,res,next) {
  263.   models.dia.findAll({
  264.     where:{horariouuid: req.params.horariouuid},
  265.     include: [{
  266.       model: models.materia,
  267.       where: {
  268.         state: Sequelize.col('project.state'),
  269.         include: [{
  270.           model: Task,
  271.           where: { state: Sequelize.col('project.state') }
  272.         }]
  273.       }
  274.   }]
  275.   }).then((tipoclases) => {
  276.     if (tipoclases.length == 0) {
  277.       error=new Error();
  278.       error.code=4
  279.       error.message="horario no encontrado"
  280.       next(error)
  281.     } else {
  282.       res.json(tipoclases)
  283.     }
  284.   })
  285. })
  286.  
  287.  
  288.  
  289. const requireadmin=false
  290. if(requireadmin){
  291.   app.use('/admin', basicAuth({
  292.     users: {
  293.       'admin': 'supersecret',
  294.       'adam': 'password1234',
  295.       'eve': 'asdfghjkl',
  296.     },
  297.    
  298.     unauthorizedResponse: (req) => {
  299.       return req.auth
  300.         ? ('Credentials ' + req.auth.user + ':' + req.auth.password + ' rejected')
  301.         : 'No credentials provided'
  302.     }
  303.   }))
  304. }
  305.  
  306.  
  307.  
  308. app.put("/admin/horario/add/:cursouuid", function (req, res, next) {
  309.   horariojson=req.body
  310.   if(horariojson===undefined){
  311.     next({
  312.       code:5,
  313.       message:"Bad JSON"
  314.     })
  315.   }else{
  316.     models.curso.findAll({
  317.       where:{uuid: req.params.cursouuid}
  318.     }).then(r =>{
  319.       if(r.length>0){
  320.         models.horario.create({
  321.           cursoUuid:req.params.cursouuid,
  322.           nombre:horariojson.nombre
  323.         })
  324.         res.json({status:"ok"})
  325.       }else{
  326.         next({
  327.           code:4,
  328.           message:"Not found curso"
  329.         })
  330.       }
  331.     })
  332.   }
  333. })
  334.  
  335. app.put("/admin/materia/add/:horariouuid", function (req, res) {
  336.   console.log(1)
  337.   //console.log(res.body)
  338.   //materiajson=JSON.parse(res.body);
  339.   if(materiajson===undefined){
  340.     next({
  341.       code:5,
  342.       message:"Bad JSON"
  343.     })
  344.   }else{
  345.     models.horario.find({
  346.       where:{uuid: req.params.horariouuid}
  347.     }).then(r =>{
  348.       if(r.length>0){
  349.         models.horario.create({
  350.           cursouuid:req.params.horariouuid,
  351.           nombre:materiajson.nombre
  352.         })
  353.       }
  354.     })
  355.   }
  356. })
  357.  
  358. app.put("/admin/tipoclase/add/:horariouuid", function (req, res) {
  359.   tipoclasejson=JSON.parse(res.body);
  360.   if(materiajson===undefined){
  361.     next({
  362.       code:5,
  363.       message:"Bad JSON"
  364.     })
  365.   }else{
  366.     models.horario.find({
  367.       where:{uuid: req.params.horariouuid}
  368.     }).then(r =>{
  369.       if(r.length>0){
  370.         models.grupo_materia.create({
  371.           horariouuid:req.params.horariouuid,
  372.           nombre:tipoclasejson.nombre,
  373.           abreviacion:tipoclasejson.abreviacion
  374.         })
  375.       }
  376.     })
  377.   }
  378. })
  379.  
  380. app.put("/admin/clase/add/:horariouuid", function (req, res) {
  381.   clasejson=JSON.parse(res.body);
  382.   if(clasejson===undefined){
  383.     next({
  384.       code:5,
  385.       message:"Bad JSON"
  386.     })
  387.   }else{
  388.     console.log(new Validator.validate(clasejson,schemas.CREATE_clase))
  389.     models.horario.find({
  390.       where:{uuid: req.params.horariouuid}
  391.     }).then(r =>{
  392.       if(r.length>0){
  393.         models.dia.create({
  394.           nombre:clasejson.nombre,
  395.           horariouuid:clasejson.horariouuid,
  396.           materiumuuid:clasejson.materiumuuid,
  397.           grupoMateriumUuid:clasejson.grupoMateriumUuid,
  398.           horaInicio:clasejson.horaInicio,
  399.           horaFinal:clasejson.horaFinal,
  400.         })
  401.       }
  402.     })
  403.   }
  404. })
  405.  
  406.  
  407.  
  408.  
  409. app.use(function (err, req, res, next) {
  410.   res.code=500
  411.   res.json({
  412.     error:err.code,
  413.     message:err.message
  414.   })
  415. });
  416.  
  417.  
  418. app.listen(3000, function () {
  419.   console.log('App listening on port 3000!');
  420. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement