UNPKG

3.28 kBJavaScriptView Raw
1var Application = require('./application');
2
3var ModelsController = module.exports = function ModelsController(init) {
4 Application.call(this, init);
5
6 init.before(loadModel, {
7 only: ['show', 'edit', 'update', 'destroy']
8 });
9};
10
11require('util').inherits(ModelsController, Application);
12
13ModelsController.prototype['new'] = function (c) {
14 this.title = 'New model';
15 this.model = new (c.Model);
16 c.render();
17};
18
19ModelsController.prototype.create = function create(c) {
20 c.Model.create(c.body.Model, function (err, model) {
21 if (err) {
22 c.flash('error', 'Model can not be created');
23 c.render('new', {
24 model: model,
25 title: 'New model'
26 });
27 } else {
28 c.flash('info', 'Model created');
29 c.redirect(c.pathTo.models);
30 }
31 });
32};
33
34ModelsController.prototype.index = function index(c) {
35 this.title = 'Models index';
36 c.Model.all(function (err, models) {
37 c.respondTo(function (format) {
38 format.json(function () {
39 c.send(models);
40 });
41 format.html(function () {
42 c.render({
43 models: models
44 });
45 });
46 });
47 });
48};
49
50ModelsController.prototype.show = function show(c) {
51 this.title = 'Model show';
52 var model = this.model;
53 c.respondTo(function (format) {
54 format.json(function () {
55 c.send(model);
56 });
57 format.html(function () {
58 c.render();
59 });
60 });
61};
62
63ModelsController.prototype.edit = function edit(c) {
64 this.title = 'Model edit';
65 c.render();
66};
67
68ModelsController.prototype.update = function update(c) {
69 var model = this.model;
70 var self = this;
71
72 this.title = 'Model edit';
73
74 model.updateAttributes(c.body.Model, function (err) {
75 c.respondTo(function (format) {
76 format.json(function () {
77 if (err) {
78 c.send({
79 code: 500,
80 error: model && model.errors || err
81 });
82 } else {
83 c.send({
84 code: 200,
85 model: model.toObject()
86 });
87 }
88 });
89 format.html(function () {
90 if (!err) {
91 c.flash('info', 'Model updated');
92 c.redirect(c.pathTo.model(model));
93 } else {
94 c.flash('error', 'Model can not be updated');
95 c.render('edit');
96 }
97 });
98 });
99 });
100
101};
102
103ModelsController.prototype.destroy = function destroy(c) {
104 this.model.destroy(function (error) {
105 if (error) {
106 c.flash('error', 'Can not destroy model');
107 } else {
108 c.flash('info', 'Model successfully removed');
109 }
110 c.send("'" + c.pathTo.models + "'");
111 });
112};
113
114function loadModel(c) {
115 var self = this;
116 c.Model.find(c.params.id, function (err, model) {
117 if (err || !model) {
118 c.redirect(c.pathTo.models);
119 } else {
120 self.model = model;
121 c.next();
122 }
123 });
124}