How to use the graphql-mapping-template.obj 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-auth-transformer / src / resources.ts View on Github external
public collectAuthCondition(): Expression {
    return block('Collect Auth Condition', [
      set(
        ref(ResourceConstants.SNIPPETS.AuthCondition),
        raw(
          `$util.defaultIfNull($authCondition, ${print(
            obj({
              expression: str(''),
              expressionNames: obj({}),
              expressionValues: obj({}),
            })
          )})`
        )
      ),
      set(ref('totalAuthExpression'), str('')),
      comment('Add dynamic group auth conditions if they exist'),
      iff(
        ref('groupAuthExpressions'),
        forEach(ref('authExpr'), ref('groupAuthExpressions'), [
          set(ref('totalAuthExpression'), str(`$totalAuthExpression $authExpr`)),
          iff(ref('foreach.hasNext'), set(ref('totalAuthExpression'), str(`$totalAuthExpression OR`))),
        ])
      ),
      iff(
        ref('groupAuthExpressionNames'),
        raw(`$util.qr($${ResourceConstants.SNIPPETS.AuthCondition}.expressionNames.putAll($groupAuthExpressionNames))`)
github aws-amplify / amplify-cli / packages / graphql-versioned-transformer / src / VersionedModelTransformer.ts View on Github external
private augmentDeleteMutation(ctx: TransformerContext, typeName: string, versionField: string, versionInput: string) {
    const mutationResolverLogicalId = ResolverResourceIDs.DynamoDBDeleteResolverResourceID(typeName);
    const snippet = printBlock(`Inject @versioned condition.`)(
      compoundExpression([
        set(
          ref(ResourceConstants.SNIPPETS.VersionedCondition),
          obj({
            expression: str(`#${versionField} = :${versionInput}`),
            expressionValues: obj({
              [`:${versionInput}`]: raw(`$util.dynamodb.toDynamoDB($ctx.args.input.${versionInput})`),
            }),
            expressionNames: obj({
              [`#${versionField}`]: str(`${versionField}`),
            }),
          })
        ),
        qref(`$ctx.args.input.remove("${versionInput}")`),
      ])
    );
    const resolver = ctx.getResource(mutationResolverLogicalId);
    if (resolver) {
      resolver.Properties.RequestMappingTemplate = snippet + '\n\n' + resolver.Properties.RequestMappingTemplate;
      ctx.setResource(mutationResolverLogicalId, resolver);
github aws-amplify / amplify-cli / packages / graphql-key-transformer / src / KeyTransformer.ts View on Github external
const queryTypeName = ctx.getQueryTypeName();
    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(
github aws-amplify / amplify-cli / packages / graphql-auth-transformer / src / resources.ts View on Github external
public collectAuthCondition(): Expression {
        return block('Collect Auth Condition', [
            set(
                ref(ResourceConstants.SNIPPETS.AuthCondition),
                obj({
                    expression: str(""),
                    expressionNames: obj({}),
                    expressionValues: obj({})
                })
            ),
            set(ref('totalAuthExpression'), str('')),
            comment('Add dynamic group auth conditions if they exist'),
            iff(
                ref('groupAuthExpressions'),
                forEach(ref('authExpr'), ref('groupAuthExpressions'), [
                    set(ref('totalAuthExpression'), str(`$totalAuthExpression $authExpr`)),
                    iff(ref('foreach.hasNext'), set(ref('totalAuthExpression'), str(`$totalAuthExpression OR`)))
                ])
            ),
            iff(
                ref('groupAuthExpressionNames'),
                raw(`$util.qr($${ResourceConstants.SNIPPETS.AuthCondition}.expressionNames.putAll($groupAuthExpressionNames))`)),
            iff(
github aws-amplify / amplify-cli / packages / graphql-key-transformer / src / KeyTransformer.ts View on Github external
function setQuerySnippet(definition: ObjectTypeDefinitionNode, directive: DirectiveNode, ctx: TransformerContext) {
    const args: KeyArguments = getDirectiveArguments(directive);
    const keys = args.fields;
    const keyTypes = keys.map(k => {
        const field = definition.fields.find(f => f.name.value === k);
        return attributeTypeFromType(field.type, ctx);
    })
    return block(`Set query expression for @key`, [
        set(ref(ResourceConstants.SNIPPETS.ModelQueryExpression), obj({})),
        applyKeyExpressionForCompositeKey(keys, keyTypes, ResourceConstants.SNIPPETS.ModelQueryExpression)
    ])
}
github aws-amplify / amplify-cli / packages / graphql-http-transformer / src / resources.ts View on Github external
return new AppSync.Resolver({
      ApiId: Fn.GetAtt(ResourceConstants.RESOURCES.GraphQLAPILogicalID, 'ApiId'),
      DataSourceName: Fn.GetAtt(HttpResourceIDs.HttpDataSourceID(baseURL), 'Name'),
      FieldName: field,
      TypeName: type,
      RequestMappingTemplate: this.replaceEnv(
        print(
          compoundExpression([
            nonNullArgs.length > 0 ? this.makeNonNullChecks(nonNullArgs) : null,
            set(ref('headers'), ref('utils.http.copyHeaders($ctx.request.headers)')),
            qref('$headers.put("Content-Type", "application/json")'),
            qref('$headers.put("accept-encoding", "application/json")'),
            ...parsedHeaders,
            HttpMappingTemplate.patchRequest({
              resourcePath: path,
              params: obj({
                body: ref('util.toJson($ctx.args.body)'),
                query: ref('util.toJson($ctx.args.query)'),
                headers: ref('util.toJson($headers)'),
              }),
            }),
          ])
        )
      ),
      ResponseMappingTemplate: print(
        ifElse(
          raw('$ctx.result.statusCode == 200 || $ctx.result.statusCode == 201'),
          ifElse(
            ref('ctx.result.headers.get("Content-Type").toLowerCase().contains("xml")'),
            ref('utils.xml.toJsonString($ctx.result.body)'),
            ref('ctx.result.body')
          ),
github aws-amplify / amplify-cli / packages / graphql-auth-transformer / src / resources.ts View on Github external
public makeESToGQLExpression() {
    return compoundExpression([
      set(
        ref('es_response'),
        obj({
          items: ref('es_items'),
        })
      ),
      iff(
        raw('$es_items.size() > 0'),
        compoundExpression([qref('$es_response.put("nextToken", $nextToken)'), qref('$es_response.put("total", $es_items.size())')])
      ),
      toJson(ref('es_response')),
    ]);
  }
}
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)
        }),
        'expressionValues': obj({
github aws-amplify / amplify-cli / packages / graphql-relation-transformer / src / ModelRelationTransformer.ts View on Github external
':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]}`)
            })
        })
    })
}