How to use the graphql-mapping-template.str function in graphql-mapping-template

To help you get started, we’ve selected a few graphql-mapping-template examples, based on popular ways it is used in public projects.

github aws-amplify / amplify-cli / packages / graphql-relation-transformer / src / ModelRelationTransformer.ts View on Github external
'#partitionKey': str(keySchema[0].AttributeName),
                '#sortKey': str(keySchema[1].AttributeName),
            }),
            'expressionValues': obj({
                ':partitionKey': obj({
                    'S': str(`$context.source.${connectionAttributes[0]}`)
                }),
                ':sortKey': obj({
                    'S': str(`$context.source.${connectionAttributes[1]}`)
                }),
            })
        })
    }

    return obj({
        'expression': str('#partitionKey = :partitionKey'),
        'expressionNames': obj({
            '#partitionKey': str(keySchema[0].AttributeName)
        }),
        'expressionValues': obj({
            ':partitionKey': obj({
                'S': str(`$context.source.${connectionAttributes[0]}`)
            })
        })
    })
}
github aws-amplify / amplify-cli / packages / graphql-auth-transformer / src / resources.ts View on Github external
public blankResolver(type: string, field: string) {
    return new AppSync.Resolver({
      ApiId: Fn.GetAtt(ResourceConstants.RESOURCES.GraphQLAPILogicalID, 'ApiId'),
      DataSourceName: 'NONE',
      FieldName: field,
      TypeName: type,
      RequestMappingTemplate: print(
        obj({
          version: str('2017-02-28'),
          payload: obj({}),
        })
      ),
      ResponseMappingTemplate: print(ref(`util.toJson($context.source.${field})`)),
    });
  }
github aws-amplify / amplify-cli / packages / graphql-key-transformer / src / KeyTransformer.ts View on Github external
const requestVariable = 'QueryRequest';
    return new AppSync.Resolver({
        ApiId: Fn.GetAtt(ResourceConstants.RESOURCES.GraphQLAPILogicalID, 'ApiId'),
        DataSourceName: Fn.GetAtt(ModelResourceIDs.ModelTableDataSourceID(type), 'Name'),
        FieldName: fieldName,
        TypeName: queryTypeName,
        RequestMappingTemplate: print(
            compoundExpression([
                setQuerySnippet(definition, directive, ctx),
                set(ref('limit'),
                ref(`util.defaultIfNull($context.args.limit, ${defaultPageLimit})`)),
                set(
                    ref(requestVariable),
                    obj({
                        version: str('2017-02-28'),
                        operation: str('Query'),
                        limit: ref('limit'),
                        query: ref(ResourceConstants.SNIPPETS.ModelQueryExpression),
                        index: str(index)
                    })
                ),
                ifElse(
                    raw(`!$util.isNull($ctx.args.sortDirection)
                    && $ctx.args.sortDirection == "DESC"`),
                    set(ref(`${requestVariable}.scanIndexForward`), bool(false)),
                    set(ref(`${requestVariable}.scanIndexForward`), bool(true)),
                ),
                iff(
                    ref('context.args.nextToken'),
                    set(
                        ref(`${requestVariable}.nextToken`),
                        str('$context.args.nextToken')
github aws-amplify / amplify-cli / packages / graphql-key-transformer / src / KeyTransformer.ts View on Github external
const defaultPageLimit = 10
    const requestVariable = 'QueryRequest';
    return new AppSync.Resolver({
        ApiId: Fn.GetAtt(ResourceConstants.RESOURCES.GraphQLAPILogicalID, 'ApiId'),
        DataSourceName: Fn.GetAtt(ModelResourceIDs.ModelTableDataSourceID(type), 'Name'),
        FieldName: fieldName,
        TypeName: queryTypeName,
        RequestMappingTemplate: print(
            compoundExpression([
                setQuerySnippet(definition, directive, ctx),
                set(ref('limit'),
                ref(`util.defaultIfNull($context.args.limit, ${defaultPageLimit})`)),
                set(
                    ref(requestVariable),
                    obj({
                        version: str('2017-02-28'),
                        operation: str('Query'),
                        limit: ref('limit'),
                        query: ref(ResourceConstants.SNIPPETS.ModelQueryExpression),
                        index: str(index)
                    })
                ),
                ifElse(
                    raw(`!$util.isNull($ctx.args.sortDirection)
                    && $ctx.args.sortDirection == "DESC"`),
                    set(ref(`${requestVariable}.scanIndexForward`), bool(false)),
                    set(ref(`${requestVariable}.scanIndexForward`), bool(true)),
                ),
                iff(
                    ref('context.args.nextToken'),
                    set(
                        ref(`${requestVariable}.nextToken`),
github aws-amplify / amplify-cli / packages / graphql-elasticsearch-transformer / src / resources.ts View on Github external
FieldName: fieldName,
      TypeName: queryTypeName,
      RequestMappingTemplate: print(
        compoundExpression([
          set(ref('indexPath'), str(`/${type.toLowerCase()}/doc/_search`)),
          set(ref('nonKeywordFields'), list(nonKeywordFields)),
          ifElse(
            ref('util.isNullOrEmpty($context.args.sort)'),
            compoundExpression([set(ref('sortDirection'), str('desc')), set(ref('sortField'), str(primaryKey))]),
            compoundExpression([
              set(ref('sortDirection'), raw('$util.defaultIfNull($context.args.sort.direction, "desc")')),
              set(ref('sortField'), raw(`$util.defaultIfNull($context.args.sort.field, "${primaryKey}")`)),
            ])
          ),
          ElasticsearchMappingTemplate.searchItem({
            path: str('$indexPath'),
            size: ifElse(ref('context.args.limit'), ref('context.args.limit'), int(10), true),
            search_after: list([str('$context.args.nextToken')]),
            query: ifElse(
              ref('context.args.filter'),
              ref('util.transform.toElasticsearchQueryDSL($ctx.args.filter)'),
              obj({
                match_all: obj({}),
              })
            ),
            sort: list([
              raw(
                '{ #if($nonKeywordFields.contains($sortField))\
    "$sortField" #else "${sortField}.keyword" #end : {\
    "order" : "$sortDirection"\
} }'
              ),
github aws-amplify / amplify-cli / packages / graphql-dynamodb-transformer / src / resources.ts View on Github external
public makeListResolver(type: string, nameOverride?: string, isSyncEnabled: boolean = false, queryTypeName: string = 'Query') {
    const fieldName = nameOverride ? nameOverride : graphqlName('list' + plurality(toUpper(type)));
    const defaultPageLimit = 10;
    const requestVariable = 'ListRequest';
    return new AppSync.Resolver({
      ApiId: Fn.GetAtt(ResourceConstants.RESOURCES.GraphQLAPILogicalID, 'ApiId'),
      DataSourceName: Fn.GetAtt(ModelResourceIDs.ModelTableDataSourceID(type), 'Name'),
      FieldName: fieldName,
      TypeName: queryTypeName,
      RequestMappingTemplate: print(
        compoundExpression([
          set(ref('limit'), ref(`util.defaultIfNull($context.args.limit, ${defaultPageLimit})`)),
          set(
            ref(requestVariable),
            obj({
              version: isSyncEnabled ? str('2018-05-29') : str('2017-02-28'),
              limit: ref('limit'),
            })
          ),
          iff(ref('context.args.nextToken'), set(ref(`${requestVariable}.nextToken`), str('$context.args.nextToken'))),
          iff(
            ref('context.args.filter'),
            set(ref(`${requestVariable}.filter`), ref('util.parseJson("$util.transform.toDynamoDBFilterExpression($ctx.args.filter)")'))
          ),
          ifElse(
            raw(`!$util.isNull($${ResourceConstants.SNIPPETS.ModelQueryExpression})
                        && !$util.isNullOrEmpty($${ResourceConstants.SNIPPETS.ModelQueryExpression}.expression)`),
            compoundExpression([
              qref(`$${requestVariable}.put("operation", "Query")`),
              qref(`$${requestVariable}.put("query", $${ResourceConstants.SNIPPETS.ModelQueryExpression})`),
              ifElse(
                raw(`!$util.isNull($ctx.args.sortDirection) && $ctx.args.sortDirection == "DESC"`),
github aws-amplify / amplify-cli / packages / graphql-relational-schema-transformer / src / RelationalDBResolverGenerator.ts View on Github external
const reqFileName = `${mutationTypeName}.${fieldName}.req.vtl`;
    const resFileName = `${mutationTypeName}.${fieldName}.res.vtl`;

    const reqTemplate = print(
      compoundExpression([
        set(ref('cols'), list([])),
        set(ref('vals'), list([])),
        forEach(ref('entry'), ref(`ctx.args.create${toUpper(type)}Input.keySet()`), [
          set(ref('discard'), ref(`cols.add($entry)`)),
          set(ref('discard'), ref(`vals.add("'$ctx.args.create${toUpper(type)}Input[$entry]'")`)),
        ]),
        set(ref('valStr'), ref('vals.toString().replace("[","(").replace("]",")")')),
        set(ref('colStr'), ref('cols.toString().replace("[","(").replace("]",")")')),
        RelationalDBMappingTemplate.rdsQuery({
          statements: list([str(createSql), str(selectSql)]),
        }),
      ])
    );

    const resTemplate = print(ref('utils.toJson($utils.parseJson($utils.rds.toJsonString($ctx.result))[1][0])'));

    fs.writeFileSync(`${this.resolverFilePath}/${reqFileName}`, reqTemplate, 'utf8');
    fs.writeFileSync(`${this.resolverFilePath}/${resFileName}`, resTemplate, 'utf8');

    let resolver = new AppSync.Resolver({
      ApiId: Fn.Ref(ResourceConstants.PARAMETERS.AppSyncApiId),
      DataSourceName: Fn.GetAtt(ResourceConstants.RESOURCES.RelationalDatabaseDataSource, 'Name'),
      TypeName: mutationTypeName,
      FieldName: fieldName,
      RequestMappingTemplateS3Location: Fn.Sub(s3BaseUrl, {
        [ResourceConstants.PARAMETERS.S3DeploymentBucket]: Fn.Ref(ResourceConstants.PARAMETERS.S3DeploymentBucket),
github aws-amplify / amplify-cli / packages / graphql-dynamodb-transformer / lib / resources.js View on Github external
graphql_mapping_template_1.set(graphql_mapping_template_1.ref('condition'), graphql_mapping_template_1.ref(graphql_transformer_common_1.ResourceConstants.SNIPPETS.AuthCondition)),
                    graphql_mapping_template_1.qref('$condition.put("expression", "$condition.expression AND attribute_exists(#id)")'),
                    graphql_mapping_template_1.qref('$condition.expressionNames.put("#id", "id")')
                ]), graphql_mapping_template_1.set(graphql_mapping_template_1.ref('condition'), graphql_mapping_template_1.obj({
                    expression: graphql_mapping_template_1.str("attribute_exists(#id)"),
                    expressionNames: graphql_mapping_template_1.obj({
                        "#id": graphql_mapping_template_1.str("id")
                    })
                }))),
                graphql_mapping_template_1.iff(graphql_mapping_template_1.raw('!$input'), graphql_mapping_template_1.set(graphql_mapping_template_1.ref('input'), graphql_mapping_template_1.ref('util.map.copyAndRemoveAllKeys($context.args.input, [])'))),
                graphql_mapping_template_1.comment('Automatically set the updatedAt timestamp.'),
                graphql_mapping_template_1.qref('$input.put("updatedAt", $util.time.nowISO8601())'),
                graphql_mapping_template_1.qref("$input.put(\"__typename\", \"" + type + "\")"),
                graphql_mapping_template_1.DynamoDBMappingTemplate.updateItem({
                    key: graphql_mapping_template_1.obj({
                        id: graphql_mapping_template_1.obj({ S: graphql_mapping_template_1.str('$context.args.input.id') })
                    }),
                    condition: graphql_mapping_template_1.ref('util.toJson($condition)')
                })
            ])),
            ResponseMappingTemplate: graphql_mapping_template_1.print(graphql_mapping_template_1.ref('util.toJson($context.result)'))
        }).dependsOn(graphql_transformer_common_1.ResourceConstants.RESOURCES.GraphQLSchemaLogicalID);
    };
    /**
github aws-amplify / amplify-cli / packages / graphql-relation-transformer / src / ModelRelationTransformer.ts View on Github external
function makeExpression(keySchema: KeySchema[], connectionAttributes: string[]) : ObjectNode {
    if (keySchema[1]) {
        return obj({
            'expression': str('#partitionKey = :partitionKey AND #sortKey = :sortKey'),
            'expressionNames': obj({
                '#partitionKey': str(keySchema[0].AttributeName),
                '#sortKey': str(keySchema[1].AttributeName),
            }),
            'expressionValues': obj({
                ':partitionKey': obj({
                    'S': str(`$context.source.${connectionAttributes[0]}`)
                }),
                ':sortKey': obj({
                    'S': str(`$context.source.${connectionAttributes[1]}`)
                }),
            })
        })
    }

    return obj({
        'expression': str('#partitionKey = :partitionKey'),
        'expressionNames': obj({
            '#partitionKey': str(keySchema[0].AttributeName)
github aws-amplify / amplify-cli / packages / graphql-function-transformer / src / FunctionTransformer.ts View on Github external
function = (name: string, region: string): any => {
    return new AppSync.FunctionConfiguration({
      ApiId: Fn.Ref(ResourceConstants.PARAMETERS.AppSyncApiId),
      Name: FunctionResourceIDs.FunctionAppSyncFunctionConfigurationID(name, region),
      DataSourceName: FunctionResourceIDs.FunctionDataSourceID(name, region),
      FunctionVersion: '2018-05-29',
      RequestMappingTemplate: printBlock(`Invoke AWS Lambda data source: ${FunctionResourceIDs.FunctionDataSourceID(name, region)}`)(
        obj({
          version: str('2018-05-29'),
          operation: str('Invoke'),
          payload: obj({
            typeName: str('$ctx.stash.get("typeName")'),
            fieldName: str('$ctx.stash.get("fieldName")'),
            arguments: ref('util.toJson($ctx.arguments)'),
            identity: ref('util.toJson($ctx.identity)'),
            source: ref('util.toJson($ctx.source)'),
            request: ref('util.toJson($ctx.request)'),
            prev: ref('util.toJson($ctx.prev)'),
          }),
        })
      ),
      ResponseMappingTemplate: printBlock('Handle error or return result')(
        compoundExpression([
          iff(ref('ctx.error'), raw('$util.error($ctx.error.message, $ctx.error.type)')),
          raw('$util.toJson($ctx.result)'),
        ])