-
Notifications
You must be signed in to change notification settings - Fork 0
/
actions.js
104 lines (92 loc) · 2.5 KB
/
actions.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
'use strict';
var fs = require('fs');
var multiparty = require('multiparty');
var PROJECT_CONFIG = require('./project.conf.json');
var gcloud = require('gcloud')(PROJECT_CONFIG);
var dataset = gcloud.datastore.dataset();
var bucket = gcloud.storage.bucket();
function getUsers(req, res) {
var query = dataset.createQuery(['Users']);
dataset.runQuery(query, _handleResponse(res));
}
module.exports.getUsers = getUsers;
function getUser(req, res) {
var id = req.url.split('/').pop();
dataset.get(dataset.key('Users', id), _handleResponse(res));
}
module.exports.getUser = getUser;
function saveUser(req, res) {
var id = req.url.split('/').pop();
_saveUserFromKey(dataset.key('Users', id), req, res);
}
module.exports.saveUser = saveUser;
function createUser(req, res) {
_saveUserFromKey(dataset.key('Users', null), req, res);
}
module.exports.createUser = createUser;
function uploadFile(req, res) {
var form = new multiparty.Form();
form.parse(req, function(err, fields, files) {
var file = files.file[0];
fs.createReadStream(file.path)
.pipe(bucket.createWriteStream(fields.name[0], {
contentType: file.headers['content-type']
}))
.on('error', function(err) {
res.writeHead(err.code);
res.end(JSON.stringify(err));
})
.on('complete', function() {
res.writeHead(200);
res.end();
});
});
}
module.exports.uploadFile = uploadFile;
function getFiles(req, res) {
bucket.list(function(err, files) {
if (err) {
res.writeHead(err.code);
res.end(err.message);
return;
}
files = files.map(function(file) {
return {
name: file.name,
contentType: file.contentType
};
});
res.end(JSON.stringify(files, null, 2));
});
}
module.exports.getFiles = getFiles;
function getFile(req, res) {
var filename = req.url.split('/').pop();
bucket.createReadStream(filename)
.on('error', function(err) {
res.end(JSON.stringify(err));
})
.pipe(res);
}
module.exports.getFile = getFile;
function _handleResponse(res) {
return function(err, result) {
if (err) {
res.writeHead(err.code);
res.end(JSON.stringify(err));
return;
}
res.end(JSON.stringify(result, null, 2));
};
}
function _saveUserFromKey(key, req, res) {
var data = '';
req
.on('data', function(chunk) {
data += chunk;
})
.on('end', function(chunk) {
data += (chunk || '');
dataset.save({ key: key, data: JSON.parse(data) }, _handleResponse(res));
});
}