asksuite-core
Version:
78 lines (60 loc) • 2.08 kB
JavaScript
const _ = require('lodash');
const AWSLambdaCaller = require('../services/AWSLambdaCaller');
const CodeSnippetsAccessor = require('../services/CodeSnippetsAccessor');
const CodeSnippetsCache = require('../singletons/CodeSnippetsCache');
const LAMBDA_NAME = 'asksuite-lambda-function-dev-executor';
const DEFAULT_MEMORY_SIZE = 1024;
module.exports = class MetaDialogCaller {
constructor(snippetId, parameters, resources, config) {
this.snippetId = snippetId;
// Parses if it comes as an array
this.parameters = this.parseParameters(parameters);
this.resources = resources;
this.config = config;
this.accessor = new CodeSnippetsAccessor(this.config);
}
parseParameters(parameters) {
if (Array.isArray(parameters)) {
return _.chain(parameters)
.keyBy('id')
.mapValues('value')
.value();
}
return parameters;
}
async mountLambdaRequest() {
let snippet;
try {
const res = await this.accessor.find(this.snippetId);
snippet = res.toJSON().body;
} catch (e) {
// Control off
snippet = CodeSnippetsCache.get(this.snippetId);
}
if (!snippet) {
throw new Error('Snippet not found');
} else if (typeof snippet === 'string') {
snippet = JSON.parse(snippet);
}
CodeSnippetsCache.set(snippet.id, snippet);
const selectedResources = _.pick(this.resources, snippet.resources);
const mergedParameters = _.assign(this.parseParameters(snippet.parameters), this.parameters);
const parameters = _.assign(mergedParameters, selectedResources);
return {
parameters,
functionCode: snippet.snippet,
memorySize: snippet.memorySize,
};
}
mountLambdaName(memorySize) {
return `${LAMBDA_NAME}_${memorySize}`;
}
async call() {
const awsLambdaCaller = new AWSLambdaCaller(this.config.CORE_LAMBDA_AWS);
const requestObj = await this.mountLambdaRequest();
return awsLambdaCaller.call(
requestObj,
this.mountLambdaName(requestObj.memorySize || DEFAULT_MEMORY_SIZE),
);
}
};