Created
May 11, 2018 14:38
-
-
Save beshkenadze/450d5581bc0c553a6aa74124c604e0a4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Module Dependencies | |
*/ | |
const errors = require('restify-errors'); | |
/** | |
* Model Schema | |
*/ | |
const Message = require('../models/message'); | |
module.exports = function(server) { | |
/** | |
* POST | |
*/ | |
server.post('/api/messages', (req, res, next) => { | |
if (!req.is('application/json')) { | |
return next( | |
new errors.InvalidContentError("Expects 'application/json'"), | |
); | |
} | |
let data = req.body || {}; | |
let message = new Message(data); | |
message.expires = new Date(new Date().getTime() + data.minutesLimit * 60000) | |
message.save(function(err) { | |
if (err) { | |
console.error(err); | |
return next(new errors.InternalError(err.message)); | |
next(); | |
} | |
res.send(201, message); | |
}); | |
}); | |
/** | |
* GET | |
*/ | |
server.get('/api/messages/:message_id', (req, res, next) => { | |
Message.findOne({ id: req.params.message_id }, function(err, doc) { | |
if (err) { | |
return next(err.message); | |
} | |
if(!doc) { | |
return next(new errors.NotFoundError()); | |
} | |
if(doc.queriesLimit === 0) { // Need to remove it | |
doc.expires = Date.now(); | |
doc.save(function(err) { | |
if (err) { | |
return next(new errors.InternalError(err.message)); | |
} | |
console.log(doc.queriesLimit) | |
return next(new errors.NotFoundError()); | |
}); | |
} else if (doc.queriesLimit > 0) { | |
doc.queriesLimit--; | |
doc.save(function(err) { | |
if (err) { | |
return next(new errors.InternalError(err.message)); | |
} | |
res.send(doc); | |
return next(); | |
}); | |
} else { | |
res.send(doc); | |
return next(); | |
} | |
}); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment