const Sequelize = require('sequelize'); const Model = Sequelize.Model; const express = require('express'); const server= express(); const bd = require('body-parser'); server.use(bd.json()); server.use(function (err, req, res, next) { console.error(err.stack); res.status(500).send(err.stack); }); const personCtrl = { get_all(res) { Person.findAll().then(persons => { res.send(JSON.stringify(persons, null, 4)); }) }, create(req, res, next) { if (req.query.firstname == undefined || req.query.lastname == undefined) { throw "Un des éléments est vide"; } Person.create({lastname: req.query.firstname, firstname: req.query.lastname}).then(p => { res.send("ok"); }) .catch(function (error) { next(error); }) }, get_by_id(req, res, next) { Person.findByPk(req.params.person_id).then(persons => { if (!persons) { throw "Pas bonne id" } res.send(JSON.stringify(persons, null, 4)) }) .catch(function (error) { next(error); }) }, update_by_id(req, res, next) { Person.findByPk(req.params.person_id).then(persons => { if (!persons) { throw "Pas bonne id"; } else { Person.update(req.body, { where: { id: req.params.person_id } }) .then( res.send("ok") ) } }) .catch(function (error) { next(error); }) }, delete_by_id(req, res, next) { Person.destroy({ where: { id: req.params.person_id } }) .then(data => { if (!data) { throw "Pas bonne id" } res.send("fait")}) .catch(function (error) { next(error); }) } } const pCtrl = Object.create(personCtrl); const sequelize = new Sequelize('w4aclem', 'clement.krebs', 'n4or2bgm', { host: 'mysql.iutrs.unistra.fr', dialect: 'mysql' }); class Person extends Model {} Person.init({ lastname: Sequelize.STRING, firstname: Sequelize.STRING }, {sequelize, modelName: 'Person'}); /*sequelize.sync() .then(() => Person.create({ lastname: 'moi', firstname: 'toi' })) .then(moi => { console.log(moi.toJSON()); });*/ server.get('/person', function (req, res) { pCtrl.get_all(res); }); server.post('/person', function (req, res, next) { pCtrl.create(req, res, next); }); server.get('/person/:person_id', function (req, res, next) { pCtrl.get_by_id(req, res, next); }); server.put('/person/:person_id', function (req, res, next) { pCtrl.update_by_id(req, res, next); }); server.delete('/person/:person_id', function (req, res, next) { pCtrl.delete_by_id(req, res, next); }); server.listen(8000, function () { console.log('ouais ouais ouais !!!'); });