@aws-amplify/graphql-predictions-transformer
Version:
Amplify GraphQL @predictions transformer
487 lines • 31.6 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PredictionsTransformer = void 0;
const path = __importStar(require("path"));
const graphql_transformer_core_1 = require("@aws-amplify/graphql-transformer-core");
const graphql_directives_1 = require("@aws-amplify/graphql-directives");
const cdk = __importStar(require("aws-cdk-lib"));
const iam = __importStar(require("aws-cdk-lib/aws-iam"));
const lambda = __importStar(require("aws-cdk-lib/aws-lambda"));
const graphql_transformer_common_1 = require("graphql-transformer-common");
const graphql_1 = require("graphql");
const graphql_mapping_template_1 = require("graphql-mapping-template");
const action_maps_1 = require("./utils/action-maps");
const constants_1 = require("./utils/constants");
class PredictionsTransformer extends graphql_transformer_core_1.TransformerPluginBase {
constructor(predictionsConfig) {
var _a;
super('amplify-predictions-transformer', graphql_directives_1.PredictionsDirective.definition);
this.directiveList = [];
this.field = (parent, definition, directive, context) => {
if (!this.bucketName) {
throw new graphql_transformer_core_1.InvalidDirectiveError('Please configure storage in your project in order to use the @predictions directive');
}
if (parent.name.value !== context.output.getQueryTypeName()) {
throw new graphql_transformer_core_1.InvalidDirectiveError('@predictions directive only works under Query operations.');
}
const directiveWrapped = new graphql_transformer_core_1.DirectiveWrapper(directive);
const args = directiveWrapped.getArguments({
resolverTypeName: parent.name.value,
resolverFieldName: definition.name.value,
}, (0, graphql_transformer_core_1.generateGetArgumentsInput)(context.transformParameters));
if (!Array.isArray(args.actions)) {
args.actions = [args.actions];
}
validateActions(args.actions);
this.directiveList.push(args);
};
this.transformSchema = (context) => {
this.directiveList.forEach((directive) => {
var _a, _b;
const actionInputObjectFields = [];
let isList = false;
directive.actions.forEach((action, index) => {
isList = needsList(action, isList);
actionInputObjectFields.push(createInputValueAction(action, directive.resolverFieldName));
if (!context.output.hasType(getActionInputName(action, directive.resolverFieldName))) {
const actionInput = getActionInputType(action, directive.resolverFieldName, index === 0);
context.output.addInput(actionInput);
}
});
context.output.addInput(makeActionInputObject(directive.resolverFieldName, actionInputObjectFields));
const queryTypeName = (_a = context.output.getQueryTypeName()) !== null && _a !== void 0 ? _a : '';
const type = context.output.getType(queryTypeName);
if (queryTypeName && type) {
const fields = (_b = type.fields) !== null && _b !== void 0 ? _b : [];
const field = fields.find((f) => f.name.value === directive.resolverFieldName);
if (field) {
const newFields = [
...fields.filter((f) => f.name.value !== field.name.value),
addInputArgument(field, directive.resolverFieldName, isList),
];
const newMutation = {
...type,
fields: newFields,
};
context.output.putType(newMutation);
}
}
});
};
this.generateResolvers = (context) => {
if (this.directiveList.length === 0) {
return;
}
if (!context.transformParameters.allowGen1Patterns) {
cdk.Annotations.of(context.api).addWarning(`@${graphql_directives_1.PredictionsDirective.name} is deprecated. This functionality will be removed in the next major release.`);
}
const stack = context.stackManager.createStack(constants_1.PREDICTIONS_DIRECTIVE_STACK);
const env = context.synthParameters.amplifyEnvironmentName;
const createdResources = new Map();
const seenActions = new Set();
const role = new iam.Role(stack, graphql_transformer_common_1.PredictionsResourceIDs.iamRole, {
roleName: joinWithEnv(context, '-', [graphql_transformer_common_1.PredictionsResourceIDs.iamRole, context.api.apiId]),
assumedBy: new iam.ServicePrincipal('appsync.amazonaws.com'),
});
(0, graphql_transformer_core_1.setResourceName)(role, { name: graphql_transformer_common_1.PredictionsResourceIDs.iamRole, setOnDefaultChild: true });
role.attachInlinePolicy(new iam.Policy(stack, 'PredictionsStorageAccess', {
statements: [
new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: ['s3:GetObject'],
resources: [getStorageArn(context, this.bucketName)],
}),
],
}));
new cdk.CfnCondition(stack, graphql_transformer_common_1.ResourceConstants.CONDITIONS.HasEnvironmentParameter, {
expression: cdk.Fn.conditionNot(cdk.Fn.conditionEquals(env, graphql_transformer_common_1.ResourceConstants.NONE)),
});
this.directiveList.forEach((directive) => {
const predictionFunctions = [];
directive.actions.forEach((action) => {
const datasourceName = action_maps_1.actionToDataSourceMap.get(action);
const functionName = graphql_transformer_common_1.PredictionsResourceIDs.getPredictionFunctionName(action);
const roleAction = action_maps_1.actionToRoleAction.get(action);
let datasource = context.api.host.getDataSource(datasourceName);
if (roleAction && !seenActions.has(action)) {
role.attachInlinePolicy(new iam.Policy(stack, `${action}Access`, {
statements: [
new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: [roleAction],
resources: ['*'],
}),
],
}));
}
seenActions.add(action);
if (!datasource) {
let predictionLambda;
if (action === constants_1.convertTextToSpeech) {
predictionLambda = createPredictionsLambda(context, stack);
role.attachInlinePolicy(new iam.Policy(stack, 'PredictionsLambdaAccess', {
statements: [
new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: ['lambda:InvokeFunction'],
resources: [predictionLambda.functionArn],
}),
],
}));
}
datasource = createPredictionsDataSource(context, stack, action, role, predictionLambda);
}
let actionFunction = createdResources.get(functionName);
if (!actionFunction) {
actionFunction = createActionFunction(context, stack, action, datasource.name);
createdResources.set(functionName, actionFunction);
}
predictionFunctions.push(actionFunction.functionId);
});
createResolver(context, stack, directive, predictionFunctions, this.bucketName);
});
};
this.bucketName = (_a = predictionsConfig === null || predictionsConfig === void 0 ? void 0 : predictionsConfig.bucketName) !== null && _a !== void 0 ? _a : '';
}
}
exports.PredictionsTransformer = PredictionsTransformer;
function validateActions(actions) {
if (actions.length === 0) {
throw new graphql_transformer_core_1.InvalidDirectiveError('@predictions directive requires at least one action.');
}
let allowed = [];
actions.forEach((action, index) => {
if (index !== 0 && Array.isArray(allowed) && !allowed.includes(action)) {
throw new graphql_transformer_core_1.InvalidDirectiveError(`${action} is not supported in this context!`);
}
allowed = action_maps_1.allowedActions.get(action);
});
}
function createPredictionsDataSource(context, stack, action, role, lambdaFn) {
let datasource;
switch (action) {
case constants_1.identifyEntities:
case constants_1.identifyText:
case constants_1.identifyLabels:
datasource = context.api.host.addHttpDataSource('RekognitionDataSource', cdk.Fn.sub('https://rekognition.${AWS::Region}.amazonaws.com'), {
authorizationConfig: {
signingRegion: cdk.Fn.sub('${AWS::Region}'),
signingServiceName: 'rekognition',
},
}, stack);
break;
case constants_1.translateText:
datasource = context.api.host.addHttpDataSource('TranslateDataSource', cdk.Fn.sub('https://translate.${AWS::Region}.amazonaws.com'), {
authorizationConfig: {
signingRegion: cdk.Fn.sub('${AWS::Region}'),
signingServiceName: 'translate',
},
}, stack);
break;
case constants_1.convertTextToSpeech:
default:
datasource = context.api.host.addLambdaDataSource('LambdaDataSource', lambda.Function.fromFunctionAttributes(stack, 'LambdaDataSourceFunction', {
functionArn: lambdaFn === null || lambdaFn === void 0 ? void 0 : lambdaFn.functionArn,
}), {}, stack);
break;
}
datasource.ds.serviceRoleArn = role.roleArn;
return datasource;
}
function createResolver(context, stack, config, resolvers, bucketName) {
const substitutions = {
hash: cdk.Fn.select(3, cdk.Fn.split('-', cdk.Fn.ref('AWS::StackName'))),
};
if (referencesEnv(bucketName)) {
substitutions.env = context.synthParameters.amplifyEnvironmentName;
}
const setBucketLine = cdk.Token.isUnresolved(bucketName)
? `$util.qr($ctx.stash.put("s3Bucket", "${bucketName}"))`
: cdk.Fn.conditionIf(graphql_transformer_common_1.ResourceConstants.CONDITIONS.HasEnvironmentParameter, cdk.Fn.sub(`$util.qr($ctx.stash.put("s3Bucket", "${bucketName}"))`, substitutions), cdk.Fn.sub(`$util.qr($ctx.stash.put("s3Bucket", "${removeEnvReference(bucketName)}"))`, {
hash: cdk.Fn.select(3, cdk.Fn.split('-', cdk.Fn.ref('AWS::StackName'))),
}));
return context.api.host.addVtlRuntimeResolver(config.resolverTypeName, config.resolverFieldName, graphql_transformer_core_1.MappingTemplate.inlineTemplateFromString(cdk.Fn.join('\n', [
setBucketLine,
(0, graphql_mapping_template_1.print)((0, graphql_mapping_template_1.compoundExpression)([(0, graphql_mapping_template_1.qref)('$ctx.stash.put("isList", false)'), (0, graphql_mapping_template_1.obj)({})])),
])), graphql_transformer_core_1.MappingTemplate.inlineTemplateFromString((0, graphql_mapping_template_1.print)((0, graphql_mapping_template_1.compoundExpression)([
(0, graphql_mapping_template_1.comment)('If the result is a list return the result as a list'),
(0, graphql_mapping_template_1.ifElse)((0, graphql_mapping_template_1.ref)('ctx.stash.get("isList")'), (0, graphql_mapping_template_1.compoundExpression)([(0, graphql_mapping_template_1.set)((0, graphql_mapping_template_1.ref)('result'), (0, graphql_mapping_template_1.ref)('ctx.result.split("[ ,]+")')), (0, graphql_mapping_template_1.toJson)((0, graphql_mapping_template_1.ref)('result'))]), (0, graphql_mapping_template_1.toJson)((0, graphql_mapping_template_1.ref)('ctx.result'))),
]))), undefined, undefined, resolvers, stack);
}
function createPredictionsLambda(context, stack) {
const functionId = graphql_transformer_common_1.PredictionsResourceIDs.lambdaID;
const role = new iam.Role(stack, graphql_transformer_common_1.PredictionsResourceIDs.lambdaIAMRole, {
roleName: joinWithEnv(context, '-', [graphql_transformer_common_1.PredictionsResourceIDs.lambdaIAMRole, context.api.apiId]),
assumedBy: new iam.ServicePrincipal('lambda.amazonaws.com'),
inlinePolicies: {
PollyAccess: new iam.PolicyDocument({
statements: [
new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: ['polly:SynthesizeSpeech'],
resources: ['*'],
}),
],
}),
},
});
(0, graphql_transformer_core_1.setResourceName)(role, { name: graphql_transformer_common_1.PredictionsResourceIDs.lambdaIAMRole, setOnDefaultChild: true });
return context.api.host.addLambdaFunction(graphql_transformer_common_1.PredictionsResourceIDs.lambdaName, `functions/${functionId}.zip`, graphql_transformer_common_1.PredictionsResourceIDs.lambdaHandlerName, path.join(__dirname, '..', 'lib', 'predictionsLambdaFunction.zip'), lambda.Runtime.NODEJS_24_X, [], role, {}, cdk.Duration.seconds(graphql_transformer_common_1.PredictionsResourceIDs.lambdaTimeout), stack);
}
function referencesEnv(value) {
return value.includes('${env}');
}
function removeEnvReference(value) {
return value.replace(/(-\${env})/, '');
}
function joinWithEnv(context, separator, listToJoin) {
const env = context.synthParameters.amplifyEnvironmentName;
return cdk.Fn.conditionIf(graphql_transformer_common_1.ResourceConstants.CONDITIONS.HasEnvironmentParameter, cdk.Fn.join(separator, [...listToJoin, env]), cdk.Fn.join(separator, listToJoin));
}
function needsList(action, isCurrentlyList) {
switch (action) {
case constants_1.identifyLabels:
return true;
case constants_1.convertTextToSpeech:
return false;
default:
return isCurrentlyList;
}
}
function capitalizeFirstLetter(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
function getActionInputName(action, fieldName) {
return `${capitalizeFirstLetter(fieldName)}${capitalizeFirstLetter(action)}Input`;
}
function makeActionInputObject(fieldName, fields) {
return {
kind: graphql_1.Kind.INPUT_OBJECT_TYPE_DEFINITION,
name: { kind: 'Name', value: `${capitalizeFirstLetter(fieldName)}Input` },
fields,
directives: [],
};
}
function createInputValueAction(action, fieldName) {
return {
kind: graphql_1.Kind.INPUT_VALUE_DEFINITION,
name: { kind: 'Name', value: action },
type: (0, graphql_transformer_common_1.makeNonNullType)((0, graphql_transformer_common_1.makeNamedType)(getActionInputName(action, fieldName))),
directives: [],
};
}
function inputValueDefinition(inputValue, namedType, isNonNull = false) {
return {
kind: graphql_1.Kind.INPUT_VALUE_DEFINITION,
name: { kind: 'Name', value: inputValue },
type: isNonNull ? (0, graphql_transformer_common_1.makeNonNullType)((0, graphql_transformer_common_1.makeNamedType)(namedType)) : (0, graphql_transformer_common_1.makeNamedType)(namedType),
directives: [],
};
}
function getActionInputType(action, fieldName, isFirst) {
const actionInputFields = {
identifyText: [inputValueDefinition('key', 'String', true)],
identifyLabels: [inputValueDefinition('key', 'String', true)],
translateText: [
inputValueDefinition('sourceLanguage', 'String', true),
inputValueDefinition('targetLanguage', 'String', true),
...(isFirst ? [inputValueDefinition('text', 'String', true)] : []),
],
convertTextToSpeech: [
inputValueDefinition('voiceID', 'String', true),
...(isFirst ? [inputValueDefinition('text', 'String', true)] : []),
],
};
return {
kind: graphql_1.Kind.INPUT_OBJECT_TYPE_DEFINITION,
name: { kind: 'Name', value: getActionInputName(action, fieldName) },
fields: actionInputFields[action],
directives: [],
};
}
function addInputArgument(field, fieldName, isList) {
return {
...field,
arguments: [
{
kind: graphql_1.Kind.INPUT_VALUE_DEFINITION,
name: { kind: 'Name', value: 'input' },
type: (0, graphql_transformer_common_1.makeNonNullType)((0, graphql_transformer_common_1.makeNamedType)(`${capitalizeFirstLetter(fieldName)}Input`)),
directives: [],
},
],
type: isList ? (0, graphql_transformer_common_1.makeListType)((0, graphql_transformer_common_1.makeNamedType)('String')) : (0, graphql_transformer_common_1.makeNamedType)('String'),
};
}
function s3ArnKey(name) {
return `arn:aws:s3:::${name}/public/*`;
}
function getStorageArn(context, bucketName) {
const substitutions = {
hash: cdk.Fn.select(3, cdk.Fn.split('-', cdk.Fn.ref('AWS::StackName'))),
};
if (referencesEnv(bucketName)) {
const env = context.synthParameters.amplifyEnvironmentName;
substitutions.env = env;
}
return cdk.Token.isUnresolved(bucketName)
? s3ArnKey(bucketName)
: cdk.Fn.conditionIf(graphql_transformer_common_1.ResourceConstants.CONDITIONS.HasEnvironmentParameter, cdk.Fn.sub(s3ArnKey(bucketName), substitutions), cdk.Fn.sub(s3ArnKey(removeEnvReference(bucketName)), { hash: cdk.Fn.select(3, cdk.Fn.split('-', cdk.Fn.ref('AWS::StackName'))) }));
}
function createActionFunction(context, stack, action, datasourceName) {
const httpPayload = `${action}Payload`;
let actionFunctionResolver;
switch (action) {
case constants_1.identifyText:
actionFunctionResolver = {
request: (0, graphql_mapping_template_1.compoundExpression)([
(0, graphql_mapping_template_1.set)((0, graphql_mapping_template_1.ref)('bucketName'), (0, graphql_mapping_template_1.ref)('ctx.stash.get("s3Bucket")')),
(0, graphql_mapping_template_1.set)((0, graphql_mapping_template_1.ref)('identityTextKey'), (0, graphql_mapping_template_1.ref)('ctx.args.input.identifyText.key')),
(0, graphql_mapping_template_1.set)((0, graphql_mapping_template_1.ref)(httpPayload), graphql_mapping_template_1.HttpMappingTemplate.postRequest({
resourcePath: '/',
params: (0, graphql_mapping_template_1.obj)({
body: (0, graphql_mapping_template_1.obj)({
Image: (0, graphql_mapping_template_1.obj)({
S3Object: (0, graphql_mapping_template_1.obj)({
Bucket: (0, graphql_mapping_template_1.str)('$bucketName'),
Name: (0, graphql_mapping_template_1.str)('public/$identityTextKey'),
}),
}),
}),
headers: (0, graphql_mapping_template_1.obj)({
'Content-Type': (0, graphql_mapping_template_1.str)(constants_1.amzJsonContentType),
'X-Amz-Target': (0, graphql_mapping_template_1.str)(constants_1.identifyTextAmzTarget),
}),
}),
})),
(0, graphql_mapping_template_1.toJson)((0, graphql_mapping_template_1.ref)(httpPayload)),
]),
response: (0, graphql_mapping_template_1.compoundExpression)([
(0, graphql_mapping_template_1.iff)((0, graphql_mapping_template_1.ref)('ctx.error'), (0, graphql_mapping_template_1.ref)('util.error($ctx.error.message)')),
(0, graphql_mapping_template_1.ifElse)((0, graphql_mapping_template_1.raw)('$ctx.result.statusCode == 200'), (0, graphql_mapping_template_1.compoundExpression)([
(0, graphql_mapping_template_1.set)((0, graphql_mapping_template_1.ref)('results'), (0, graphql_mapping_template_1.ref)('util.parseJson($ctx.result.body)')),
(0, graphql_mapping_template_1.set)((0, graphql_mapping_template_1.ref)('finalResult'), (0, graphql_mapping_template_1.str)('')),
(0, graphql_mapping_template_1.forEach)((0, graphql_mapping_template_1.ref)('item'), (0, graphql_mapping_template_1.ref)('results.TextDetections'), [
(0, graphql_mapping_template_1.iff)((0, graphql_mapping_template_1.raw)('$item.Type == "LINE"'), (0, graphql_mapping_template_1.set)((0, graphql_mapping_template_1.ref)('finalResult'), (0, graphql_mapping_template_1.str)('$finalResult$item.DetectedText '))),
]),
(0, graphql_mapping_template_1.ref)('util.toJson($finalResult.trim())'),
]), (0, graphql_mapping_template_1.ref)('utils.error($ctx.result.body)')),
]),
};
break;
case constants_1.identifyLabels:
actionFunctionResolver = {
request: (0, graphql_mapping_template_1.compoundExpression)([
(0, graphql_mapping_template_1.set)((0, graphql_mapping_template_1.ref)('bucketName'), (0, graphql_mapping_template_1.ref)('ctx.stash.get("s3Bucket")')),
(0, graphql_mapping_template_1.set)((0, graphql_mapping_template_1.ref)('identifyLabelKey'), (0, graphql_mapping_template_1.ref)('ctx.args.input.identifyLabels.key')),
(0, graphql_mapping_template_1.qref)('$ctx.stash.put("isList", true)'),
(0, graphql_mapping_template_1.set)((0, graphql_mapping_template_1.ref)(httpPayload), graphql_mapping_template_1.HttpMappingTemplate.postRequest({
resourcePath: '/',
params: (0, graphql_mapping_template_1.obj)({
body: (0, graphql_mapping_template_1.obj)({
Image: (0, graphql_mapping_template_1.obj)({
S3Object: (0, graphql_mapping_template_1.obj)({
Bucket: (0, graphql_mapping_template_1.str)('$bucketName'),
Name: (0, graphql_mapping_template_1.str)('public/$identifyLabelKey'),
}),
}),
MaxLabels: (0, graphql_mapping_template_1.int)(10),
MinConfidence: (0, graphql_mapping_template_1.int)(55),
}),
headers: (0, graphql_mapping_template_1.obj)({
'Content-Type': (0, graphql_mapping_template_1.str)(constants_1.amzJsonContentType),
'X-Amz-Target': (0, graphql_mapping_template_1.str)(constants_1.identifyLabelsAmzTarget),
}),
}),
})),
(0, graphql_mapping_template_1.toJson)((0, graphql_mapping_template_1.ref)(httpPayload)),
]),
response: (0, graphql_mapping_template_1.compoundExpression)([
(0, graphql_mapping_template_1.iff)((0, graphql_mapping_template_1.ref)('ctx.error'), (0, graphql_mapping_template_1.ref)('util.error($ctx.error.message)')),
(0, graphql_mapping_template_1.ifElse)((0, graphql_mapping_template_1.raw)('$ctx.result.statusCode == 200'), (0, graphql_mapping_template_1.compoundExpression)([
(0, graphql_mapping_template_1.set)((0, graphql_mapping_template_1.ref)('labels'), (0, graphql_mapping_template_1.str)('')),
(0, graphql_mapping_template_1.set)((0, graphql_mapping_template_1.ref)('result'), (0, graphql_mapping_template_1.ref)('util.parseJson($ctx.result.body)')),
(0, graphql_mapping_template_1.forEach)((0, graphql_mapping_template_1.ref)('label'), (0, graphql_mapping_template_1.ref)('result.Labels'), [(0, graphql_mapping_template_1.set)((0, graphql_mapping_template_1.ref)('labels'), (0, graphql_mapping_template_1.str)('$labels$label.Name, '))]),
(0, graphql_mapping_template_1.toJson)((0, graphql_mapping_template_1.ref)('labels.replaceAll(", $", "")')),
]), (0, graphql_mapping_template_1.ref)('util.error($ctx.result.body)')),
]),
};
break;
case constants_1.translateText:
actionFunctionResolver = {
request: (0, graphql_mapping_template_1.compoundExpression)([
(0, graphql_mapping_template_1.set)((0, graphql_mapping_template_1.ref)('text'), (0, graphql_mapping_template_1.ref)('util.defaultIfNull($ctx.args.input.translateText.text, $ctx.prev.result)')),
(0, graphql_mapping_template_1.set)((0, graphql_mapping_template_1.ref)(httpPayload), graphql_mapping_template_1.HttpMappingTemplate.postRequest({
resourcePath: '/',
params: (0, graphql_mapping_template_1.obj)({
body: (0, graphql_mapping_template_1.obj)({
SourceLanguageCode: (0, graphql_mapping_template_1.ref)('ctx.args.input.translateText.sourceLanguage'),
TargetLanguageCode: (0, graphql_mapping_template_1.ref)('ctx.args.input.translateText.targetLanguage'),
Text: (0, graphql_mapping_template_1.ref)('text'),
}),
headers: (0, graphql_mapping_template_1.obj)({
'Content-Type': (0, graphql_mapping_template_1.str)(constants_1.amzJsonContentType),
'X-Amz-Target': (0, graphql_mapping_template_1.str)(constants_1.translateTextAmzTarget),
}),
}),
})),
(0, graphql_mapping_template_1.toJson)((0, graphql_mapping_template_1.ref)(httpPayload)),
]),
response: (0, graphql_mapping_template_1.compoundExpression)([
(0, graphql_mapping_template_1.iff)((0, graphql_mapping_template_1.ref)('ctx.error'), (0, graphql_mapping_template_1.ref)('util.error($ctx.error.message)')),
(0, graphql_mapping_template_1.ifElse)((0, graphql_mapping_template_1.raw)('$ctx.result.statusCode == 200'), (0, graphql_mapping_template_1.compoundExpression)([(0, graphql_mapping_template_1.set)((0, graphql_mapping_template_1.ref)('result'), (0, graphql_mapping_template_1.ref)('util.parseJson($ctx.result.body)')), (0, graphql_mapping_template_1.ref)('util.toJson($result.TranslatedText)')]), (0, graphql_mapping_template_1.ref)('util.error($ctx.result.body)')),
]),
};
break;
case constants_1.convertTextToSpeech:
default:
actionFunctionResolver = {
request: (0, graphql_mapping_template_1.compoundExpression)([
(0, graphql_mapping_template_1.set)((0, graphql_mapping_template_1.ref)('bucketName'), (0, graphql_mapping_template_1.ref)('ctx.stash.get("s3Bucket")')),
(0, graphql_mapping_template_1.qref)('$ctx.stash.put("isList", false)'),
(0, graphql_mapping_template_1.set)((0, graphql_mapping_template_1.ref)('text'), (0, graphql_mapping_template_1.ref)('util.defaultIfNull($ctx.args.input.convertTextToSpeech.text, $ctx.prev.result)')),
(0, graphql_mapping_template_1.obj)({
version: (0, graphql_mapping_template_1.str)('2018-05-29'),
operation: (0, graphql_mapping_template_1.str)('Invoke'),
payload: (0, graphql_mapping_template_1.toJson)((0, graphql_mapping_template_1.obj)({
uuid: (0, graphql_mapping_template_1.str)('$util.autoId()'),
action: (0, graphql_mapping_template_1.str)(constants_1.convertTextToSpeech),
voiceID: (0, graphql_mapping_template_1.ref)('ctx.args.input.convertTextToSpeech.voiceID'),
text: (0, graphql_mapping_template_1.ref)('text'),
})),
}),
]),
response: (0, graphql_mapping_template_1.compoundExpression)([
(0, graphql_mapping_template_1.iff)((0, graphql_mapping_template_1.ref)('ctx.error'), (0, graphql_mapping_template_1.ref)('util.error($ctx.error.message, $ctx.error.type)')),
(0, graphql_mapping_template_1.set)((0, graphql_mapping_template_1.ref)('response'), (0, graphql_mapping_template_1.ref)('util.parseJson($ctx.result)')),
(0, graphql_mapping_template_1.ref)('util.toJson($ctx.result.url)'),
]),
};
break;
}
return context.api.host.addAppSyncVtlRuntimeFunction(`${action}Function`, graphql_transformer_core_1.MappingTemplate.inlineTemplateFromString((0, graphql_mapping_template_1.print)(actionFunctionResolver.request)), graphql_transformer_core_1.MappingTemplate.inlineTemplateFromString((0, graphql_mapping_template_1.print)(actionFunctionResolver.response)), datasourceName, stack);
}
//# sourceMappingURL=graphql-predictions-transformer.js.map