forked from hapi-swagger/hapi-swagger
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathupload-file.js
139 lines (108 loc) · 3.19 KB
/
upload-file.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
133
134
135
136
137
138
139
'use strict';
// `upload-file.js` - how create documenation for a file upload
// the file `example/assets/test-upload.json` has data in the correct format for this example
const Hapi = require('hapi');
const Blipp = require('blipp');
const Inert = require('inert');
const Vision = require('vision');
const Boom = require('boom');
const Joi = require('joi');
const HapiSwagger = require('../');
let server = new Hapi.Server();
server.connection({
host: 'localhost',
port: 3000
});
const storeFile = function (request, reply) {
const payload = request.payload;
let data = '';
// check that required file is present
// the filepath property incorrectlty uses a string 'undefined'
if (payload.file) {
const file = payload.file;
const headers = file.hapi.headers;
// check the content-type is json
if (headers['content-type'] === 'application/json') {
// read the stream into memory
file.on('data', (chunk) => {
data += chunk;
});
// once we have all the data
file.on('end', () => {
// use Joi to validate file data format
const addSumSchema = Joi.object().keys({
a: Joi.number().required(),
b: Joi.number().required(),
operator: Joi.string().required(),
equals: Joi.number().required()
});
Joi.validate(data, addSumSchema, (err) => {
if (err) {
reply(Boom.badRequest('JSON file has incorrect format or properties. ' + err));
} else {
// do something with JSON.parse(data)
console.log('File uploaded correctly');
reply(data);
}
});
});
} else {
reply(Boom.unsupportedMediaType());
}
} else {
reply(Boom.badRequest('File is required'));
}
};
const swaggerOptions = {};
const routes = [{
method: 'POST',
path: '/store/file/',
config: {
handler: storeFile,
plugins: {
'hapi-swagger': {
payloadType: 'form'
}
},
tags: ['api'],
validate: {
payload: {
file: Joi.any()
.meta({ swaggerType: 'file' })
.description('json file')
}
},
payload: {
maxBytes: 1048576,
parse: true,
output: 'stream'
}
}
}];
server.register([
Inert,
Vision,
Blipp,
{
register: HapiSwagger,
options: swaggerOptions
}],
(err) => {
if (err) {
console.log(err);
}
server.route(routes);
server.start((startErr) => {
if (startErr) {
console.log(startErr);
} else {
console.log('Server running at:', server.info.uri);
}
});
});
// add templates only for testing custom.html
server.views({
path: 'bin',
engines: { html: require('handlebars') },
isCached: false
});