-
Notifications
You must be signed in to change notification settings - Fork 3
/
organisation-resource.js
71 lines (61 loc) · 1.58 KB
/
organisation-resource.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
var mongojs = require("mongojs");
var connection_string = process.env.MONGOLAB_URI || '127.0.0.1:27017/roisalen';
var db = mongojs(connection_string, ['organisations']);
function compare(orgA, orgB) {
return orgA.name.localeCompare(orgB.name);
}
function validShortName(shortName) {
return shortName && shortName.length > 2 && shortName.length < 12;
}
function validOrgName(orgName) {
return orgName && orgName.length > 0;
}
function getOrganisations(req, res, next) {
db.organisations.find(function(err, success) {
if (success) {
success.sort(compare);
res.status(200).send(success);
return next();
} else {
console.log("failed")
console.log(err)
res.status(500).send();
return next(err);
}
});
}
function addOrganisation(req, res, next) {
if (!validShortName(req.body.shortName) || !validOrgName(req.body.name)) {
res.status(400).send();
return next();
}
req.body._id = req.body.shortName;
db.organisations.save(req.body, function(err, success) {
if (!err && success) {
res.status(201).send(success);
return next();
} else {
console.log(err);
res.status(500).send();
return next(err);
}
});
}
function deleteOrganisation(req, res, next) {
var id = req.params.id;
if (id.length > 12) {
id = db.ObjectId(id);
}
db.organisations.remove({_id: id}, function (err, success) {
if (success) {
console.log("deleted all");
res.status(200).send();
} else {
res.status(500).send();
}
return next(err);
});
}
module.exports.get = getOrganisations;
module.exports.add = addOrganisation;
module.exports.delete = deleteOrganisation;