How to use the graphql-mapping-template.qref 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.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github aws-amplify / amplify-cli / packages / graphql-transformer-common / src / dynamodbUtils.ts View on Github external
iff(
      raw(`!$util.isNull($ctx.args.${sortKeyArgumentName}) && !$util.isNull($ctx.args.${sortKeyArgumentName}.le)`),
      compoundExpression([
        ...keyNames.map((keyName, idx) =>
          iff(
            raw(`!$util.isNull($ctx.args.${sortKeyArgumentName}.le.${keyName})`),
            idx === 0
              ? set(ref(accumulatorVar1), str(`$ctx.args.${sortKeyArgumentName}.le.${keyName}`))
              : set(ref(accumulatorVar1), str(`$${accumulatorVar1}${sep}$ctx.args.${sortKeyArgumentName}.le.${keyName}`)),
            true
          )
        ),
        set(ref(`${queryExprReference}.expression`), raw(`"$${queryExprReference}.expression AND #sortKey <= :sortKey"`)),
        qref(`$${queryExprReference}.expressionNames.put("#sortKey", "${sortKeyAttributeName}")`),
        // TODO: Handle N & B.
        qref(`$${queryExprReference}.expressionValues.put(":sortKey", { "S": "$${accumulatorVar1}" })`),
      ])
    ),
    iff(
      raw(`!$util.isNull($ctx.args.${sortKeyArgumentName}) && !$util.isNull($ctx.args.${sortKeyArgumentName}.gt)`),
      compoundExpression([
        ...keyNames.map((keyName, idx) =>
          iff(
            raw(`!$util.isNull($ctx.args.${sortKeyArgumentName}.gt.${keyName})`),
            idx === 0
              ? set(ref(accumulatorVar1), str(`$ctx.args.${sortKeyArgumentName}.gt.${keyName}`))
              : set(ref(accumulatorVar1), str(`$${accumulatorVar1}${sep}$ctx.args.${sortKeyArgumentName}.gt.${keyName}`)),
            true
          )
        ),
        set(ref(`${queryExprReference}.expression`), raw(`"$${queryExprReference}.expression AND #sortKey > :sortKey"`)),
        qref(`$${queryExprReference}.expressionNames.put("#sortKey", "${sortKeyAttributeName}")`),
github aws-amplify / amplify-cli / packages / graphql-dynamodb-transformer / src / resources.ts View on Github external
]),
              ]),
              set(
                ref('condition'),
                obj({
                  expression: str('attribute_exists(#id)'),
                  expressionNames: obj({
                    '#id': str('id'),
                  }),
                  expressionValues: obj({}),
                })
              )
            )
          ),
          comment('Automatically set the updatedAt timestamp.'),
          qref('$context.args.input.put("updatedAt", $util.defaultIfNull($ctx.args.input.updatedAt, $util.time.nowISO8601()))'),
          qref(`$context.args.input.put("__typename", "${type}")`),
          comment('Update condition if type is @versioned'),
          iff(
            ref(ResourceConstants.SNIPPETS.VersionedCondition),
            compoundExpression([
              // tslint:disable-next-line
              qref(
                `$condition.put("expression", "($condition.expression) AND $${ResourceConstants.SNIPPETS.VersionedCondition}.expression")`
              ),
              qref(`$condition.expressionNames.putAll($${ResourceConstants.SNIPPETS.VersionedCondition}.expressionNames)`),
              qref(`$condition.expressionValues.putAll($${ResourceConstants.SNIPPETS.VersionedCondition}.expressionValues)`),
            ])
          ),
          iff(
            ref('context.args.condition'),
            compoundExpression([
github aws-amplify / amplify-cli / packages / graphql-auth-transformer / src / resources.ts View on Github external
)
                )
            } else {
                // If the owner field is a list and the user does not
                // provide a list of values for the owner, set the list with
                // the owner as the sole member.
                ownershipAuthorizationExpressions.push(
                    // If the owner is not provided set it automatically.
                    // If the user explicitly provides null this will be false and we leave it null.
                    iff(
                        and([
                            raw(`$util.isNull($${allowedOwnersVariable})`),
                            parens(raw(`! $${variableToCheck}.containsKey("${ownerAttribute}")`)),
                        ]),
                        compoundExpression([
                            qref(`$${variableToCheck}.put("${ownerAttribute}", ["$identityValue"])`),
                            set(ref(variableToSet), raw('true'))
                        ])
                    )
                )
            }
            ruleNumber++
        }
        return compoundExpression([
            set(ref(variableToSet), raw(`false`)),
            ...ownershipAuthorizationExpressions,
        ]);
    }
github aws-amplify / amplify-cli / packages / graphql-dynamodb-transformer / src / resources.ts View on Github external
return new AppSync.Resolver({
      ApiId: Fn.GetAtt(ResourceConstants.RESOURCES.GraphQLAPILogicalID, 'ApiId'),
      DataSourceName: Fn.GetAtt(ModelResourceIDs.ModelTableDataSourceID(type), 'Name'),
      FieldName: fieldName,
      TypeName: mutationTypeName,
      RequestMappingTemplate: print(
        compoundExpression([
          ifElse(
            raw(`$${ResourceConstants.SNIPPETS.AuthCondition} && $${ResourceConstants.SNIPPETS.AuthCondition}.expression != ""`),
            compoundExpression([
              set(ref('condition'), ref(ResourceConstants.SNIPPETS.AuthCondition)),
              ifElse(
                ref(ResourceConstants.SNIPPETS.ModelObjectKey),
                forEach(ref('entry'), ref(`${ResourceConstants.SNIPPETS.ModelObjectKey}.entrySet()`), [
                  qref('$condition.put("expression", "$condition.expression AND attribute_exists(#keyCondition$velocityCount)")'),
                  qref('$condition.expressionNames.put("#keyCondition$velocityCount", "$entry.key")'),
                ]),
                compoundExpression([
                  qref('$condition.put("expression", "$condition.expression AND attribute_exists(#id)")'),
                  qref('$condition.expressionNames.put("#id", "id")'),
                ])
              ),
            ]),
            ifElse(
              ref(ResourceConstants.SNIPPETS.ModelObjectKey),
              compoundExpression([
                set(
                  ref('condition'),
                  obj({
                    expression: str(''),
                    expressionNames: obj({}),
                    expressionValues: obj({}),
github aws-amplify / amplify-cli / packages / graphql-http-transformer / src / resources.ts View on Github external
public makePatchResolver(baseURL: string, path: string, type: string, field: string, nonNullArgs: string[], headers: HttpHeader[]) {
    const parsedHeaders = headers.map(header => qref(`$headers.put("${header.key}", "${header.value}")`));

    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'),
github aws-amplify / amplify-cli / packages / graphql-versioned-transformer / src / VersionedModelTransformer.ts View on Github external
private augmentCreateMutation(ctx: TransformerContext, typeName: string, versionField: string, versionInput: string) {
    const snippet = printBlock(`Setting "${versionField}" to 1`)(qref(`$ctx.args.input.put("${versionField}", 1)`));
    const mutationResolverLogicalId = ResolverResourceIDs.DynamoDBCreateResolverResourceID(typeName);
    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-dynamodb-transformer / src / resources.ts View on Github external
public makeCreateResolver({ type, nameOverride, syncConfig, mutationTypeName = 'Mutation' }: MutationResolverInput) {
    const fieldName = nameOverride ? nameOverride : graphqlName('create' + toUpper(type));
    return new AppSync.Resolver({
      ApiId: Fn.GetAtt(ResourceConstants.RESOURCES.GraphQLAPILogicalID, 'ApiId'),
      DataSourceName: Fn.GetAtt(ModelResourceIDs.ModelTableDataSourceID(type), 'Name'),
      FieldName: fieldName,
      TypeName: mutationTypeName,
      RequestMappingTemplate: printBlock('Prepare DynamoDB PutItem Request')(
        compoundExpression([
          qref('$context.args.input.put("createdAt", $util.defaultIfNull($ctx.args.input.createdAt, $util.time.nowISO8601()))'),
          qref('$context.args.input.put("updatedAt", $util.defaultIfNull($ctx.args.input.updatedAt, $util.time.nowISO8601()))'),
          qref(`$context.args.input.put("__typename", "${type}")`),
          set(
            ref('condition'),
            obj({
              expression: str('attribute_not_exists(#id)'),
              expressionNames: obj({
                '#id': str('id'),
              }),
            })
          ),
          iff(
            ref('context.args.condition'),
            compoundExpression([
              set(ref('condition.expressionValues'), obj({})),
              set(
github aws-amplify / amplify-cli / packages / graphql-dynamodb-transformer / src / resources.ts View on Github external
ifElse(
              ref(ResourceConstants.SNIPPETS.ModelObjectKey),
              compoundExpression([
                set(
                  ref('condition'),
                  obj({
                    expression: str(''),
                    expressionNames: obj({}),
                    expressionValues: obj({}),
                  })
                ),
                forEach(ref('entry'), ref(`${ResourceConstants.SNIPPETS.ModelObjectKey}.entrySet()`), [
                  ifElse(
                    raw('$velocityCount == 1'),
                    qref('$condition.put("expression", "attribute_exists(#keyCondition$velocityCount)")'),
                    qref('$condition.put(\
"expression", "$condition.expression AND attribute_exists(#keyCondition$velocityCount)")')
                  ),
                  qref('$condition.expressionNames.put("#keyCondition$velocityCount", "$entry.key")'),
                ]),
              ]),
              set(
                ref('condition'),
                obj({
                  expression: str('attribute_exists(#id)'),
                  expressionNames: obj({
                    '#id': str('id'),
                  }),
                  expressionValues: obj({}),
                })
              )
            )
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-dynamodb-transformer / src / resources.ts View on Github external
public makeCreateResolver({ type, nameOverride, syncConfig, mutationTypeName = 'Mutation' }: MutationResolverInput) {
    const fieldName = nameOverride ? nameOverride : graphqlName('create' + toUpper(type));
    return new AppSync.Resolver({
      ApiId: Fn.GetAtt(ResourceConstants.RESOURCES.GraphQLAPILogicalID, 'ApiId'),
      DataSourceName: Fn.GetAtt(ModelResourceIDs.ModelTableDataSourceID(type), 'Name'),
      FieldName: fieldName,
      TypeName: mutationTypeName,
      RequestMappingTemplate: printBlock('Prepare DynamoDB PutItem Request')(
        compoundExpression([
          qref('$context.args.input.put("createdAt", $util.defaultIfNull($ctx.args.input.createdAt, $util.time.nowISO8601()))'),
          qref('$context.args.input.put("updatedAt", $util.defaultIfNull($ctx.args.input.updatedAt, $util.time.nowISO8601()))'),
          qref(`$context.args.input.put("__typename", "${type}")`),
          set(
            ref('condition'),
            obj({
              expression: str('attribute_not_exists(#id)'),
              expressionNames: obj({
                '#id': str('id'),
              }),
            })
          ),
          iff(
            ref('context.args.condition'),
            compoundExpression([
              set(ref('condition.expressionValues'), obj({})),
              set(
                ref('conditionFilterExpressions'),
                raw('$util.parseJson($util.transform.toDynamoDBConditionExpression($context.args.condition))')