1 | const _ = require('lodash');
|
2 |
|
3 | const AWSLambdaCaller = require('../services/AWSLambdaCaller');
|
4 | const CodeSnippetsAccessor = require('../services/CodeSnippetsAccessor');
|
5 | const CodeSnippetsCache = require('../singletons/CodeSnippetsCache');
|
6 |
|
7 | const LAMBDA_NAME = 'asksuite-lambda-function-dev-executor';
|
8 | const DEFAULT_MEMORY_SIZE = 1024;
|
9 |
|
10 | module.exports = class MetaDialogCaller {
|
11 | constructor(snippetId, parameters, resources, config) {
|
12 | this.snippetId = snippetId;
|
13 |
|
14 |
|
15 | this.parameters = this.parseParameters(parameters);
|
16 |
|
17 | this.resources = resources;
|
18 |
|
19 | this.config = config;
|
20 |
|
21 | this.accessor = new CodeSnippetsAccessor(this.config);
|
22 | }
|
23 |
|
24 | parseParameters(parameters) {
|
25 | if (Array.isArray(parameters)) {
|
26 | return _.chain(parameters)
|
27 | .keyBy('id')
|
28 | .mapValues('value')
|
29 | .value();
|
30 | }
|
31 | return parameters;
|
32 | }
|
33 |
|
34 | async mountLambdaRequest() {
|
35 | let snippet;
|
36 | try {
|
37 | const res = await this.accessor.find(this.snippetId);
|
38 | snippet = res.toJSON().body;
|
39 | } catch (e) {
|
40 |
|
41 | snippet = CodeSnippetsCache.get(this.snippetId);
|
42 | }
|
43 |
|
44 | if (!snippet) {
|
45 | throw new Error('Snippet not found');
|
46 | } else if (typeof snippet === 'string') {
|
47 | snippet = JSON.parse(snippet);
|
48 | }
|
49 |
|
50 | CodeSnippetsCache.set(snippet.id, snippet);
|
51 |
|
52 | const selectedResources = _.pick(this.resources, snippet.resources);
|
53 | const mergedParameters = _.assign(this.parseParameters(snippet.parameters), this.parameters);
|
54 | const parameters = _.assign(mergedParameters, selectedResources);
|
55 |
|
56 | return {
|
57 | parameters,
|
58 | functionCode: snippet.snippet,
|
59 | memorySize: snippet.memorySize,
|
60 | };
|
61 | }
|
62 |
|
63 | mountLambdaName(memorySize) {
|
64 | return `${LAMBDA_NAME}_${memorySize}`;
|
65 | }
|
66 |
|
67 | async call() {
|
68 | const awsLambdaCaller = new AWSLambdaCaller(this.config.CORE_LAMBDA_AWS);
|
69 |
|
70 | const requestObj = await this.mountLambdaRequest();
|
71 |
|
72 | return awsLambdaCaller.call(
|
73 | requestObj,
|
74 | this.mountLambdaName(requestObj.memorySize || DEFAULT_MEMORY_SIZE),
|
75 | );
|
76 | }
|
77 | };
|