How to use the graphql-mapping-template.compoundExpression 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.${argName}) && !$util.isNull($ctx.args.${argName}.lt)`),
      compoundExpression([
        set(ref(`${queryExprReference}.expression`), raw(`"$${queryExprReference}.expression AND #sortKey < :sortKey"`)),
        qref(`$${queryExprReference}.expressionNames.put("#sortKey", "${_sortKeyName}")`),
        // TODO: Handle N & B.
        qref(
          `$${queryExprReference}.expressionValues.put(":sortKey", { "${attributeType}": "${prefixValue(`$ctx.args.${argName}.lt`)}" })`
        ),
      ])
    ),
    iff(
      raw(`!$util.isNull($ctx.args.${argName}) && !$util.isNull($ctx.args.${argName}.le)`),
      compoundExpression([
        set(ref(`${queryExprReference}.expression`), raw(`"$${queryExprReference}.expression AND #sortKey <= :sortKey"`)),
        qref(`$${queryExprReference}.expressionNames.put("#sortKey", "${_sortKeyName}")`),
        // TODO: Handle N & B.
        qref(
          `$${queryExprReference}.expressionValues.put(":sortKey", { "${attributeType}": "${prefixValue(`$ctx.args.${argName}.le`)}" })`
        ),
      ])
    ),
    iff(
      raw(`!$util.isNull($ctx.args.${argName}) && !$util.isNull($ctx.args.${argName}.gt)`),
      compoundExpression([
        set(ref(`${queryExprReference}.expression`), raw(`"$${queryExprReference}.expression AND #sortKey > :sortKey"`)),
        qref(`$${queryExprReference}.expressionNames.put("#sortKey", "${_sortKeyName}")`),
        // TODO: Handle N & B.
        qref(
          `$${queryExprReference}.expressionValues.put(":sortKey", { "${attributeType}": "${prefixValue(`$ctx.args.${argName}.gt`)}" })`
github aws-amplify / amplify-cli / packages / graphql-auth-transformer / src / resources.ts View on Github external
// 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-versioned-transformer / src / VersionedModelTransformer.ts View on Github external
private augmentUpdateMutation(ctx: TransformerContext, typeName: string, versionField: string, versionInput: string) {
    const mutationResolverLogicalId = ResolverResourceIDs.DynamoDBUpdateResolverResourceID(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}`),
            }),
          })
        ),
        set(ref('newVersion'), raw(`$ctx.args.input.${versionInput} + 1`)),
        qref(`$ctx.args.input.put("${versionField}", $newVersion)`),
        qref(`$ctx.args.input.remove("${versionInput}")`),
      ])
github aws-amplify / amplify-cli / packages / graphql-http-transformer / src / resources.ts View on Github external
private makeNonNullChecks(nonNullArgs: string[]) {
    return compoundExpression([
      comment('START: Manually checking that all non-null arguments are provided either in the query or the body'),
      iff(
        or(nonNullArgs.map((arg: string) => parens(and([raw(`!$ctx.args.body.${arg}`), raw(`!$ctx.args.query.${arg}`)])))),
        ref('util.error("An argument you marked as Non-Null is not present ' + 'in the query nor the body of your request."))')
      ),
      comment('END: Manually checking that all non-null arguments are provided either in the query or the body'),
    ]);
  }
github aws-amplify / amplify-cli / packages / graphql-auth-transformer / src / resources.ts View on Github external
this.setUserGroups(rule.groupClaim),
        set(ref(variableToSet), raw(`$util.defaultIfNull($${variableToSet}, false)`)),
        forEach(ref('userGroup'), ref('userGroups'), [
          iff(
            raw(`$util.isList($ctx.args.input.${groupsAttribute})`),
            iff(ref(`${variableToCheck}.${groupsAttribute}.contains($userGroup)`), set(ref(variableToSet), raw('true')))
          ),
          iff(
            raw(`$util.isString($ctx.args.input.${groupsAttribute})`),
            iff(raw(`$ctx.args.input.${groupsAttribute} == $userGroup`), set(ref(variableToSet), raw('true')))
          ),
        ])
      );
    }

    return compoundExpression(groupAuthorizationExpressions);
  }
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)'),
              }),
            }),
          ])
        )
      ),
github aws-amplify / amplify-cli / packages / graphql-connection-transformer / src / resources.ts View on Github external
ref('context.args.filter'),
                            ref('util.transform.toDynamoDBFilterExpression($ctx.args.filter)'),
                            nul()
                        ),
                        limit: ref('limit'),
                        nextToken: ifElse(
                            ref('context.args.nextToken'),
                            str('$context.args.nextToken'),
                            nul()
                        ),
                        index: str(`gsi-${connectionName}`)
                    })
                ])
            ),
            ResponseMappingTemplate: print(
                compoundExpression([
                    iff(raw('!$result'), set(ref('result'), ref('ctx.result'))),
                    raw('$util.toJson($result)')
                ])
            )
        }).dependsOn(ResourceConstants.RESOURCES.GraphQLSchemaLogicalID)
    }
github aws-amplify / amplify-cli / packages / graphql-auth-transformer / src / ModelAuthTransformer.ts View on Github external
set(ref('items'), list([])),
                forEach(
                    ref('item'),
                    ref('ctx.result.items'),
                    [
                        dynamicGroupAuthorizationExpression,
                        newline(),
                        ownerAuthorizationExpression,
                        newline(),
                        appendIfLocallyAuthorized
                    ]
                ),
                set(ref('ctx.result.items'), ref('items'))
            ])
        )
        return compoundExpression([
            staticGroupAuthorizationExpression,
            newline(),
            comment('[Start] If not static group authorized, filter items'),
            ifNotStaticallyAuthedFilterObjects,
            comment('[End] If not static group authorized, filter items')
        ])
    }
github aws-amplify / amplify-cli / packages / graphql-relational-schema-transformer / src / RelationalDBResolverGenerator.ts View on Github external
)}Input.${this.typePrimaryKeyMap.get(type)}`;
    let selectSql;
    if (this.typePrimaryKeyTypeMap.get(type).includes('String')) {
      selectSql = `SELECT * FROM ${type} WHERE ${this.typePrimaryKeyMap.get(type)}=\'$ctx.args.update${toUpper(
        type
      )}Input.${this.typePrimaryKeyMap.get(type)}\'`;
    } else {
      selectSql = `SELECT * FROM ${type} WHERE ${this.typePrimaryKeyMap.get(type)}=$ctx.args.update${toUpper(
        type
      )}Input.${this.typePrimaryKeyMap.get(type)}`;
    }
    const reqFileName = `${mutationTypeName}.${fieldName}.req.vtl`;
    const resFileName = `${mutationTypeName}.${fieldName}.res.vtl`;

    const reqTemplate = print(
      compoundExpression([
        set(ref('updateList'), obj({})),
        forEach(ref('entry'), ref(`ctx.args.update${toUpper(type)}Input.keySet()`), [
          set(ref('discard'), ref(`updateList.put($entry, "'$ctx.args.update${toUpper(type)}Input[$entry]'")`)),
        ]),
        set(ref('update'), ref(`updateList.toString().replace("{","").replace("}","")`)),
        RelationalDBMappingTemplate.rdsQuery({
          statements: list([str(updateSql), 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');
github aws-amplify / amplify-cli / packages / graphql-auth-transformer / src / ModelAuthTransformer.ts View on Github external
return isListType(field.type);
                }
                return false;
            }
            const ownerAuthorizationExpression = this.resources.ownerAuthorizationExpressionForCreateOperationsByField(
                ownerAuthorizationRules,
                field.name.value,
                fieldIsList
            )

            const throwIfUnauthorizedExpression = this.resources.throwIfUnauthorized()
            const templateParts = [
                print(
                    iff(
                        raw(`$ctx.args.input.containsKey("${field.name.value}")`),
                        compoundExpression([
                            staticGroupAuthorizationExpression,
                            newline(),
                            dynamicGroupAuthorizationExpression,
                            newline(),
                            ownerAuthorizationExpression,
                            newline(),
                            throwIfUnauthorizedExpression
                        ])
                    )
                ),
                createResolverResource.Properties.RequestMappingTemplate
            ]
            createResolverResource.Properties.RequestMappingTemplate = templateParts.join('\n\n')
            ctx.setResource(resolverResourceId, createResolverResource)
        }
    }