-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson.js
110 lines (96 loc) · 2.63 KB
/
json.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
var Village = require('./models/Village');
var User = require('./models/User');
var handleJsonError = function(e, res) {
console.log('[json request error] ', e && (e.stack || e));
res.json({error: (e && e.message) || e });
};
var execQuery = function(query, res, callback) {
try {
if (!query || !res || typeof callback !== 'function') throw 'query failed';
query.exec(function (err, ret) {
try {
if (err) throw err;
callback(ret);
}
catch (e) {
handleJsonError(e, res);
}
});
} catch (e) {
handleJsonError(e, res);
}
};
exports.request = function(req, res, type, option, page) {
var post = req.body || null;
var query;
try {
switch (type) {
case 'list':
switch (option) {
// ユーザーリストの処理
case 'users':
query = User.find().select('name lastAccess vid').lean();
execQuery(query, res, function (users) {
res.json({list: users});
});
break;
default:
break;
}
break;
case 'villist':
if (option === 'active') {
query = Village.find().lean();
execQuery(query, res, function (villages) {
res.json({villist: villages});
});
}
else {
res.end();
}
break;
// 新規JSON処理 (POST)
case 'new':
if (!req.isAuthenticated() || !post) return res.json({error:"unauthorized"});
switch (option) {
// 村を作る
case 'vil':
var newVil = post;
newVil.user = {
name: req.user.name
};
Village.create(newVil, function (err, vil){
try {
if (err) throw err;
res.json({success:true, vid:vil.vid});
}
catch (e) {
handleJsonError(e, res);
}
});
break;
default:
res.json({error: 'option undefined'});
break;
}
break;
// 入村処理 (POST)
case 'join':
if (!req.isAuthenticated() || !post) return res.json({error:"unauthorized"});
query = User.findById(req.user._id);
execQuery(query, res, function (user){
/* TODO: ここに入村できるか否かのバリデート */
user.vid = post.vid;
user.save(function(err){
res.json({success:true});
});
});
break;
default:
throw "undefined type";
}
}
catch (e) {
handleJsonError(e, res);
}
};