forked from ec-europa/eubfr-data-lake
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
86 lines (69 loc) · 2.38 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
78
79
80
81
82
83
84
85
86
const AWS = require('aws-sdk');
const awscred = require('awscred');
const connectionClass = require('http-aws-es');
const elasticsearch = require('elasticsearch');
const isEqual = require('lodash.isequal');
const { promisify } = require('util');
const getExportValueByName = require('./lib/getExportValueByName');
const getUserCredentials = promisify(awscred.load);
class CreateElasticIndexDeploy {
constructor(serverless, options) {
this.serverless = serverless;
this.options = options;
this.hooks = {
'after:deploy:deploy': this.afterDeployment.bind(this),
};
}
afterDeployment() {
const indices = this.serverless.service.custom.slsEsIndices;
return Promise.all(
indices.map(async indexConfig => {
try {
const credentials = await getUserCredentials();
const { accessKeyId, secretAccessKey } = credentials.credentials;
const { index, mapping, region, endpointName } = indexConfig;
const domain = await getExportValueByName({
name: endpointName,
region,
});
// elasticsearch client configuration
const esOptions = {
index,
connectionClass,
apiVersion: '6.5',
host: `https://${domain}`,
// this is required when out of a lambda function
awsConfig: new AWS.Config({
accessKeyId,
secretAccessKey,
region,
}),
};
const client = elasticsearch.Client(esOptions);
const exists = await client.indices.exists({ index });
if (!exists) {
return client.indices.create({ index, body: mapping });
}
const existingMappping = await client.indices.getMapping({ index });
if (!isEqual(existingMappping[index], mapping)) {
const types = Object.keys(mapping.mappings);
return Promise.all(
types.map(type =>
// Update mapping (if possible)
client.indices.putMapping({
index,
type,
body: mapping.mappings[type],
})
)
);
}
return console.log('Finished updates on ES indices.');
} catch (error) {
throw error;
}
})
);
}
}
module.exports = CreateElasticIndexDeploy;