forked from matthisk/es6console
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexamples.js
More file actions
76 lines (62 loc) · 1.79 KB
/
examples.js
File metadata and controls
76 lines (62 loc) · 1.79 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
'use strict';
const aws = require('aws-sdk');
const project = require('../config/project.config.js');
const options = {
region: 'eu-west-1',
};
function listObjects(s3, params) {
return new Promise((resolve, reject) => {
s3.listObjects(params, (err, data) => {
if (err) return reject(err);
return resolve(data);
});
});
}
function trimPrefix(prefix) {
const pattern = /examples\/(\w+)\//;
return prefix.match(pattern)[1];
}
function trimItem(key) {
const pattern = /examples\/\w+\/(.*)/;
return key.match(pattern)[1];
}
function makeBody(data) {
const result = {};
data.forEach((set) => {
result[trimPrefix(set.Prefix)] = set.Contents.map((item) => trimItem(item.Key));
});
return {
examples: result,
};
}
module.exports.handler = (event, context, callback) => {
const s3 = new aws.S3(options);
const params = {
Bucket: project.bucket_name,
Delimiter: '/',
Prefix: 'examples/',
};
s3.listObjects(params, (err, data) => {
if (err) return callback(err);
const prefixes = data.CommonPrefixes.map((item) => item.Prefix);
Promise.all(prefixes.map((prefix) =>
listObjects(s3, {
Bucket: project.bucket_name,
Delimiter: '/',
Prefix: prefix,
})
)).then((data) => {
const content = makeBody(data);
const response = {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': '*',
},
body: JSON.stringify(content),
};
return callback(null, response);
}).catch((err) => {
return callback(err);
});
});
};