-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
132 lines (121 loc) · 2.88 KB
/
server.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
const fs = require('fs');
const bunyan = require('bunyan');
const Hapi = require('hapi');
const Good = require('good');
const Promise = require('bluebird');
const rp = require('request-promise');
// Enable smart logger
const log = bunyan.createLogger({
name: 'app',
streams: [{
path: 'log.json'
}]
});
// Spin up Hapi server
const server = new Hapi.Server();
server.connection({
port: 8080
});
// Routes
server.route({
method: 'POST',
path: '/submit',
config: {
payload: {
output: 'stream',
parse: true,
allow: 'multipart/form-data'
},
handler: (req, reply) => {
function processFile(incomingStream, url) {
// TODO: figure out how to use this incoming stream directly,
// instead of writing it to the filesystem
return new Promise((resolve, reject) => {
const name = incomingStream.hapi.filename;
const path = `${__dirname}/uploads/${name}`;
const newFile = fs.createWriteStream(path);
incomingStream.on('error', err => {
log.warn(err);
});
incomingStream.pipe(newFile);
incomingStream.on('end', err => {
const formData = {
f: 'json',
attachment: fs.createReadStream(path)
};
rp({
method: 'POST',
uri: `${url}/addAttachment`,
formData
})
.then((response) => {
fs.unlink(path);
resolve({ name, response });
})
.catch(error => {
log.warn(error);
reject(error);
});
});
});
}
const fileOps = [];
const featureUrl = req.payload.featureUrl;
const data = req.payload;
if (data.uploads) {
if (data.uploads.length) {
data.uploads.forEach(upload => {
fileOps.push(processFile(upload, featureUrl));
});
} else {
fileOps.push(processFile(data.uploads, featureUrl));
}
Promise.all(fileOps).then(response => {
reply(JSON.stringify(response));
}, error => {
reply(JSON.stringify(error));
});
}
}
}
});
// Static Routes
server.register(require('inert'), (err) => {
if (err) {
throw err;
}
// Test Page
server.route({
method: 'GET',
path: '/test',
handler: (req, reply) => {
log.info(req);
reply.file('./public/form.html');
}
});
});
/* Plugins */
// Hapi process monitoring
server.register({
register: Good,
options: {
reporters: [{
reporter: require('good-console'),
events: {
response: '*',
log: '*'
}
}]
}
}, (err) => {
if (err) {
throw err;
}
});
// Start the Hapi server
server.start((err) => {
if (err) {
throw err;
}
server.log('info', `Server running at ${server.info.uri}`);
});