This repository has been archived by the owner on May 7, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
tableAPI.js
83 lines (76 loc) · 2.02 KB
/
tableAPI.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
"use strict";
var fs = require('fs');
function setup(Model, sequelize) {
return {
model: Model,
list: function (req, res) {
var search = { $or: { }};
if (req.query) {
if ((req.query.search) && (req.query.search.length > 0)) {
for (var attr in Model.attributes) {
if (attr === 'id') continue;
search.$or[attr] = sequelize.where(sequelize.cast(sequelize.col(attr), 'text'), { $ilike: '%' + req.query.search + '%' });
}
}
}
return Model.findAll({ where: search }).then(function(entries) {
res.json(entries);
});
},
create: function (req, res) {
var neItem = req.body;
return Model.create(neItem).then(function(entry) {
res.json(entry);
});
},
read: function (req, res) {
var id = ~~req.params.id;
return Model.findOne({ where: {id: id} }).then(function(entry) {
res.json(entry);
});
},
update: function (req, res) {
var id = ~~req.params.id;
var updateData = req.body;
return Model.update(updateData, {
where: {
id: id
}
}).then(function(entry) {
res.json(updateData);
});
},
delete: function (req, res) {
var id = ~~req.params.id
return Model.destroy({
where: {
id: id
}
}).then(function() {
res.json({});
});
},
upload: function (req, res) {
var oldPath = req.files.file.path;
var dir = './uploaded/';
var newPath = dir + req.files.file.name;
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
}
fs.readFile(oldPath, function(err, data) {
fs.writeFile(newPath, data, function(err) {
fs.unlink(oldPath, function(){
if (err) { res.json({ status: 'err' }); return; };
res.send({
status: 'err',
msg: 'File uploaded to: ' + newPath
});
});
});
});
}
};
}
module.exports = {
setup: setup
};