forked from jeremydaly/lambda-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdownload.js
More file actions
313 lines (261 loc) · 11.7 KB
/
Copy pathdownload.js
File metadata and controls
313 lines (261 loc) · 11.7 KB
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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
'use strict';
const Promise = require('bluebird') // Promise library
const expect = require('chai').expect // Assertion library
const fs = require('fs') // Require Node.js file system
// Require Sinon.js library
const sinon = require('sinon')
const AWS = require('aws-sdk') // AWS SDK (automatically available in Lambda)
const S3 = require('../lib/s3-service') // Init S3 Service
// Init API instance
const api = require('../index')({ version: 'v1.0', mimeTypes: { test: 'text/test' } })
let event = {
httpMethod: 'get',
path: '/',
body: {},
multiValueHeaders: {
'content-type': ['application/json']
}
}
/******************************************************************************/
/*** DEFINE TEST ROUTES ***/
/******************************************************************************/
api.get('/download/badpath', function(req,res) {
res.download()
})
api.get('/download', function(req,res) {
res.download('./test-missing.txt')
})
api.get('/download/err', function(req,res) {
res.download('./test-missing.txt', err => {
if (err) {
res.error(404,'There was an error accessing the requested file')
}
})
})
api.get('/download/test', function(req,res) {
res.download('test/test.txt' + (req.query.test ? req.query.test : ''), err => {
// Return a promise
return Promise.delay(100).then((x) => {
if (err) {
// set custom error code and message on error
res.error(501,'Custom File Error')
} else {
// else set custom response code
res.status(201)
}
})
})
})
api.get('/download/buffer', function(req,res) {
res.download(fs.readFileSync('test/test.txt'), req.query.filename ? req.query.filename : undefined)
})
api.get('/download/headers', function(req,res) {
res.download('test/test.txt', {
headers: { 'x-test': 'test', 'x-timestamp': 1 }
})
})
api.get('/download/headers-private', function(req,res) {
res.download('test/test.txt', {
headers: { 'x-test': 'test', 'x-timestamp': 1 },
private: true
})
})
api.get('/download/all', function(req,res) {
res.download('test/test.txt', 'test-file.txt', { private: true, maxAge: 3600000 }, err => { res.header('x-callback','true') })
})
api.get('/download/no-options', function(req,res) {
res.download('test/test.txt', 'test-file.txt', err => { res.header('x-callback','true') })
})
// S3 file
api.get('/download/s3', function(req,res) {
stub.withArgs({Bucket: 'my-test-bucket', Key: 'test.txt'}).returns({
promise: () => { return {
AcceptRanges: 'bytes',
LastModified: new Date('2018-04-01T13:32:58.000Z'),
ContentLength: 23,
ETag: '"ae771fbbba6a74eeeb77754355831713"',
ContentType: 'text/plain',
Metadata: {},
Body: Buffer.from('Test file for sendFile\n')
}}
})
res.download('s3://my-test-bucket/test.txt')
})
api.get('/download/s3path', function(req,res) {
stub.withArgs({Bucket: 'my-test-bucket', Key: 'test/test.txt'}).returns({
promise: () => { return {
AcceptRanges: 'bytes',
LastModified: new Date('2018-04-01T13:32:58.000Z'),
ContentLength: 23,
ETag: '"ae771fbbba6a74eeeb77754355831713"',
ContentType: 'text/plain',
Metadata: {},
Body: Buffer.from('Test file for sendFile\n')
}}
})
res.download('s3://my-test-bucket/test/test.txt')
})
api.get('/download/s3missing', function(req,res) {
stub.withArgs({Bucket: 'my-test-bucket', Key: 'file-does-not-exist.txt'})
.throws(new Error("NoSuchKey: The specified key does not exist."))
res.download('s3://my-test-bucket/file-does-not-exist.txt')
})
// Error Middleware
api.use(function(err,req,res,next) {
res.header('x-error','true')
next()
})
/******************************************************************************/
/*** BEGIN TESTS ***/
/******************************************************************************/
let stub
describe('Download Tests:', function() {
before(function() {
// Stub getObjectAsync
stub = sinon.stub(S3,'getObject')
})
it('Bad path', async function() {
let _event = Object.assign({},event,{ path: '/download/badpath' })
let result = await new Promise(r => api.run(_event,{},(e,res) => { r(res) }))
expect(result).to.deep.equal({ multiValueHeaders: { 'content-type': ['application/json'], 'x-error': ['true'] }, statusCode: 500, body: '{"error":"Invalid file"}', isBase64Encoded: false })
}) // end it
it('Missing file', async function() {
let _event = Object.assign({},event,{ path: '/download' })
let result = await new Promise(r => api.run(_event,{},(e,res) => { r(res) }))
expect(result).to.deep.equal({ multiValueHeaders: { 'content-type': ['application/json'], 'x-error': ['true'] }, statusCode: 500, body: '{"error":"No such file"}', isBase64Encoded: false })
}) // end it
it('Missing file with custom catch', async function() {
let _event = Object.assign({},event,{ path: '/download/err' })
let result = await new Promise(r => api.run(_event,{},(e,res) => { r(res) }))
expect(result).to.deep.equal({ multiValueHeaders: { 'content-type': ['application/json'], 'x-error': ['true'] }, statusCode: 404, body: '{"error":"There was an error accessing the requested file"}', isBase64Encoded: false })
}) // end it
it('Text file w/ callback override (promise)', async function() {
let _event = Object.assign({},event,{ path: '/download/test' })
let result = await new Promise(r => api.run(_event,{},(e,res) => { r(res) }))
expect(result).to.deep.equal({
multiValueHeaders: {
'content-type': ['text/plain'],
'cache-control': ['max-age=0'],
'expires': result.multiValueHeaders.expires,
'last-modified': result.multiValueHeaders['last-modified'],
'content-disposition': ['attachment; filename="test.txt"']
},
statusCode: 201, body: 'VGVzdCBmaWxlIGZvciBzZW5kRmlsZQo=', isBase64Encoded: true
})
}) // end it
it('Text file error w/ callback override (promise)', async function() {
let _event = Object.assign({},event,{ path: '/download/test', queryStringParameters: { test: 'x' } })
let result = await new Promise(r => api.run(_event,{},(e,res) => { r(res) }))
expect(result).to.deep.equal({ multiValueHeaders: { 'content-type': ['application/json'], 'x-error': ['true'] }, statusCode: 501, body: '{"error":"Custom File Error"}', isBase64Encoded: false })
}) // end it
it('Buffer Input (no filename)', async function() {
let _event = Object.assign({},event,{ path: '/download/buffer' })
let result = await new Promise(r => api.run(_event,{},(e,res) => { r(res) }))
expect(result).to.deep.equal({
multiValueHeaders: {
'content-type': ['application/json'],
'cache-control': ['max-age=0'],
'expires': result.multiValueHeaders.expires,
'last-modified': result.multiValueHeaders['last-modified'],
'content-disposition': ['attachment']
}, statusCode: 200, body: 'VGVzdCBmaWxlIGZvciBzZW5kRmlsZQo=', isBase64Encoded: true
})
}) // end it
it('Buffer Input (w/ filename)', async function() {
let _event = Object.assign({},event,{ path: '/download/buffer', queryStringParameters: { filename: 'test.txt' } })
let result = await new Promise(r => api.run(_event,{},(e,res) => { r(res) }))
expect(result).to.deep.equal({
multiValueHeaders: {
'content-type': ['text/plain'],
'cache-control': ['max-age=0'],
'expires': result.multiValueHeaders.expires,
'last-modified': result.multiValueHeaders['last-modified'],
'content-disposition': ['attachment; filename="test.txt"']
}, statusCode: 200, body: 'VGVzdCBmaWxlIGZvciBzZW5kRmlsZQo=', isBase64Encoded: true
})
}) // end it
it('Text file w/ headers', async function() {
let _event = Object.assign({},event,{ path: '/download/headers' })
let result = await new Promise(r => api.run(_event,{},(e,res) => { r(res) }))
expect(result).to.deep.equal({
multiValueHeaders: {
'content-type': ['text/plain'],
'x-test': ['test'],
'x-timestamp': [1],
'cache-control': ['max-age=0'],
'expires': result.multiValueHeaders.expires,
'last-modified': result.multiValueHeaders['last-modified'],
'content-disposition': ['attachment; filename="test.txt"']
}, statusCode: 200, body: 'VGVzdCBmaWxlIGZvciBzZW5kRmlsZQo=', isBase64Encoded: true
})
}) // end it
it('Text file w/ filename, options, and callback', async function() {
let _event = Object.assign({},event,{ path: '/download/all' })
let result = await new Promise(r => api.run(_event,{},(e,res) => { r(res) }))
expect(result).to.deep.equal({
multiValueHeaders: {
'content-type': ['text/plain'],
'x-callback': ['true'],
'cache-control': ['private, max-age=3600'],
'expires': result.multiValueHeaders.expires,
'last-modified': result.multiValueHeaders['last-modified'],
'content-disposition': ['attachment; filename="test-file.txt"']
}, statusCode: 200, body: 'VGVzdCBmaWxlIGZvciBzZW5kRmlsZQo=', isBase64Encoded: true
})
}) // end it
it('Text file w/ filename and callback (no options)', async function() {
let _event = Object.assign({},event,{ path: '/download/no-options' })
let result = await new Promise(r => api.run(_event,{},(e,res) => { r(res) }))
expect(result).to.deep.equal({
multiValueHeaders: {
'content-type': ['text/plain'],
'x-callback': ['true'],
'cache-control': ['max-age=0'],
'expires': result.multiValueHeaders.expires,
'last-modified': result.multiValueHeaders['last-modified'],
'content-disposition': ['attachment; filename="test-file.txt"']
}, statusCode: 200, body: 'VGVzdCBmaWxlIGZvciBzZW5kRmlsZQo=', isBase64Encoded: true
})
}) // end it
it('S3 file', async function() {
let _event = Object.assign({},event,{ path: '/download/s3' })
let result = await new Promise(r => api.run(_event,{},(e,res) => { r(res) }))
expect(result).to.deep.equal({
multiValueHeaders: {
'content-type': ['text/plain'],
'cache-control': ['max-age=0'],
'content-disposition': ['attachment; filename="test.txt"'],
'expires': result.multiValueHeaders['expires'],
'etag': ['"ae771fbbba6a74eeeb77754355831713"'],
'last-modified': result.multiValueHeaders['last-modified']
}, statusCode: 200, body: 'VGVzdCBmaWxlIGZvciBzZW5kRmlsZQo=', isBase64Encoded: true
})
}) // end it
it('S3 file w/ nested path', async function() {
let _event = Object.assign({},event,{ path: '/download/s3path' })
let result = await new Promise(r => api.run(_event,{},(e,res) => { r(res) }))
expect(result).to.deep.equal({
multiValueHeaders: {
'content-type': ['text/plain'],
'cache-control': ['max-age=0'],
'content-disposition': ['attachment; filename="test.txt"'],
'expires': result.multiValueHeaders['expires'],
'etag': ['"ae771fbbba6a74eeeb77754355831713"'],
'last-modified': result.multiValueHeaders['last-modified']
}, statusCode: 200, body: 'VGVzdCBmaWxlIGZvciBzZW5kRmlsZQo=', isBase64Encoded: true
})
}) // end it
it('S3 file error', async function() {
let _event = Object.assign({},event,{ path: '/download/s3missing' })
let result = await new Promise(r => api.run(_event,{},(e,res) => { r(res) }))
expect(result).to.deep.equal({
multiValueHeaders: {
'content-type': ['application/json'],
'x-error': ['true']
}, statusCode: 500, body: '{"error":"NoSuchKey: The specified key does not exist."}', isBase64Encoded: false
})
}) // end it
after(function() {
stub.restore()
})
}) // end download tests