|
| 1 | +"use strict"; |
| 2 | +Object.defineProperty(exports, "__esModule", { value: true }); |
| 3 | +exports.ModelRouter = void 0; |
| 4 | +const router_1 = require("./router"); |
| 5 | +const mongoose = require("mongoose"); |
| 6 | +const restify_errors_1 = require("restify-errors"); |
| 7 | +class ModelRouter extends router_1.Router { |
| 8 | + constructor(model) { |
| 9 | + super(); |
| 10 | + this.model = model; |
| 11 | + this.validateId = (req, res, next) => { |
| 12 | + if (!mongoose.Types.ObjectId.isValid(req.params.id)) { |
| 13 | + next(new restify_errors_1.NotFoundError('Document not found')); |
| 14 | + } |
| 15 | + else { |
| 16 | + next(); |
| 17 | + } |
| 18 | + }; |
| 19 | + this.findAll = (req, resp, next) => { |
| 20 | + this.model.find().then(this.renderAll(resp, next)) |
| 21 | + .catch(next); |
| 22 | + }; |
| 23 | + this.findById = (req, resp, next) => { |
| 24 | + this.model.findById(req.params.id) |
| 25 | + .then(this.render(resp, next)) |
| 26 | + .catch(next); |
| 27 | + }; |
| 28 | + this.save = (req, resp, next) => { |
| 29 | + let document = new this.model(req.body); |
| 30 | + document.save().then(this.render(resp, next)) |
| 31 | + .catch(next); |
| 32 | + }; |
| 33 | + this.replace = (req, resp, next) => { |
| 34 | + const options = { runValidators: true, overwrite: true }; |
| 35 | + this.model.update({ _id: req.params.id }, req.body, options) |
| 36 | + .exec().then((result) => { |
| 37 | + console.log(result); |
| 38 | + if (result.n) { |
| 39 | + resp.send(204); |
| 40 | + } |
| 41 | + else { |
| 42 | + throw new restify_errors_1.NotFoundError('Documento não encontrado'); |
| 43 | + } |
| 44 | + }).then(this.render(resp, next)) |
| 45 | + .catch(next); |
| 46 | + }; |
| 47 | + this.update = (req, resp, next) => { |
| 48 | + const options = { runValidators: true, new: true }; |
| 49 | + this.model.findByIdAndUpdate(req.params.id, req.body, options) |
| 50 | + .then(this.render(resp, next)) |
| 51 | + .catch(next); |
| 52 | + }; |
| 53 | + this.delete = (req, resp, next) => { |
| 54 | + this.model.remove({ _id: req.params.id }) |
| 55 | + .exec().then((cmdResult) => { |
| 56 | + if (cmdResult.result.n) { |
| 57 | + resp.send(204); |
| 58 | + } |
| 59 | + else { |
| 60 | + throw new restify_errors_1.NotFoundError('Documento não encontrado'); |
| 61 | + } |
| 62 | + return next(); |
| 63 | + }) |
| 64 | + .catch(next); |
| 65 | + }; |
| 66 | + } |
| 67 | +} |
| 68 | +exports.ModelRouter = ModelRouter; |
0 commit comments