forked from mickymots/aws-lambda-xml-json
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
77 lines (55 loc) · 2 KB
/
index.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
// dependencies
const AWS = require('aws-sdk');
const util = require('util');
const moment = require('moment')
const parser = require('xml2json');
// get reference to S3 client
const s3 = new AWS.S3();
exports.handler = async (event, context, callback) => {
// Read options from the event parameter.
console.log("Reading options from event:\n", util.inspect(event, {depth: 5}));
const srcBucket = event.Records[0].s3.bucket.name;
// Object key may have spaces or unicode non-ASCII characters.
const srcKey = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, " "));
const dstBucket = srcBucket + "-target";
console.log("source bucket - " + srcBucket)
console.log("destination bucket - " + dstBucket)
// Download the xml from the S3 source bucket.
try {
const params = {
Bucket: srcBucket,
Key: srcKey
};
var metadata_xml = await s3.getObject(params).promise();
} catch (error) {
console.log(error);
return;
}
// create outfile_name with date string
let dt_str = moment().format('YYYYDDMM');
// const basename = 'Metadata'
const output_ext = '.json'
const output_file_name = "".concat(srcKey.slice(0, -4), "_" , dt_str, output_ext)
// Use the xml2json module to convert the file.
try {
var buffer = parser.toJson(metadata_xml.Body);
} catch (error) {
console.log(error);
return;
}
// Upload the json to the destination bucket
try {
const destparams = {
Bucket: dstBucket,
Key: output_file_name,
Body: buffer,
ContentType: "json"
};
const putResult = await s3.putObject(destparams).promise();
} catch (error) {
console.log(error);
return;
}
console.log('Successfully converted to json ' + srcBucket + '/' + srcKey +
' and uploaded to ' + dstBucket + '/' + output_file_name);
}