var Piece = require('../db/index.js').Piece;

module.exports = {

  getAllPieces: function(req, res) {
    Piece.findAll().then(function(pieces) {
      res.status(200).send({ pieces: pieces });
    }).catch(function(error) {
      console.log(error);
      res.sendStatus(500);
    });
  },

  addPiece: function(req, res) {
    Piece.create(req.body.piece).then(function(piece) {
      res.status(201).send({ piece: piece });
    }).catch(function(error) {
      console.log(error);
      if (error.errors[0].message === 'item must be unique') {
        res.sendStatus(409);
      } else {
        res.sendStatus(500);
      }
    });
  },

  modifyPiece: function(req, res) {
    Piece.findOne({ where: { item: req.params.item } }).then(function(piece) {
      if (piece === null) {
        res.sendStatus(404);
      } else {
        piece.update(req.body).then(function(updatedPiece) {
          res.status(200).send({ piece: updatedPiece });
        });
      }
    }).catch(function(error) {
      console.log(error);
      res.sendStatus(500);
    });
  },

  removePiece: function(req, res) {
    Piece.findOne({ where: {item: req.params.item } }).then(function(piece) {
      if (piece === null) {
        res.sendStatus(404);
      } else {
        return piece.destroy();
      }
    }).then(function() {
      res.sendStatus(204);
    }).catch(function(error) {
      console.log(error);
      res.sendStatus(500);
    });
  }

};

@@ -1,17 +1,18 @@
 var 
-Piece
+models
  = requi
@@ -35,13 +35,67 @@
 js')
-.Piec
+;%0Avar Piece = models.Piece;%0Avar PieceType = models.PieceTyp
 e;%0A%0A
@@ -382,105 +382,581 @@
     
-Piece.create(req.body.piece).then(function(piece) %7B%0A      res.status(201).send(%7B piece: piece %7D);
+// save type to associate later%0A    if (req.body.piece.hasOwnProperty('type')) %7B%0A      var type = req.body.piece.type;%0A      delete req.body.piece.type;%0A    %7D%0A%0A    Piece.create(req.body.piece).then(function(piece) %7B%0A      // associate type if given%0A      if (type) %7B%0A        PieceType.findOne(%7B where: %7B name: type %7D%7D).then(function(matchedType) %7B%0A          if (matchedType !== null) %7B%0A            piece.typeId = matchedType.id;%0A          %7D%0A          res.status(201).send(%7B piece: piece %7D);%0A        %7D);%0A      %7D else %7B%0A        res.status(201).send(%7B piece: piece %7D);%0A      %7D
 %0A   

Modify addPiece to associate piece with a type