How to use graphql-mapping-template - 10 common examples

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-auth-transformer / src / resources.ts View on Github external
const groupsAttributeName = `groupsAttribute${ruleNumber}`
            const groupName = `group${ruleNumber}`
            groupAuthorizationExpressions = groupAuthorizationExpressions.concat(
                comment(`Authorization rule${fieldMention}: { allow: ${rule.allow}, groupsField: "${groupsAttribute}" }`),
                // Add the new auth expression and values
                forEach(ref('userGroup'), ref('userGroups'), [
                    raw(`$util.qr($groupAuthExpressions.add("contains(#${groupsAttributeName}, :${groupName}$foreach.count)"))`),
                    raw(`$util.qr($groupAuthExpressionValues.put(":${groupName}$foreach.count", { "S": $userGroup }))`),
                ]),
                iff(raw('$userGroups.size() > 0'), raw(`$util.qr($groupAuthExpressionNames.put("#${groupsAttributeName}", "${groupsAttribute}"))`)),
            )
            ruleNumber++
        }
        return block('Dynamic group authorization checks', [
            this.setUserGroups(),
            set(ref('groupAuthExpressions'), list([])),
            set(ref('groupAuthExpressionValues'), obj({})),
            set(ref('groupAuthExpressionNames'), obj({})),
            ...groupAuthorizationExpressions,
        ])
    }
github aws-amplify / amplify-cli / packages / graphql-dynamodb-transformer / src / resources.ts View on Github external
expressionNames: obj({
                    '#id': str('id'),
                  }),
                })
              )
            )
          ),
          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)`),
              set(ref('expressionValues'), raw('$util.defaultIfNull($condition.expressionValues, {})')),
              qref(`$expressionValues.putAll($${ResourceConstants.SNIPPETS.VersionedCondition}.expressionValues)`),
              set(ref('condition.expressionValues'), ref('expressionValues')),
            ])
          ),
          iff(
            ref('context.args.condition'),
            compoundExpression([
              set(
                ref('conditionFilterExpressions'),
                raw('$util.parseJson($util.transform.toDynamoDBConditionExpression($context.args.condition))')
              ),
              // tslint:disable-next-line
              qref(`$condition.put("expression", "($condition.expression) AND $conditionFilterExpressions.expression")`),
              qref(`$condition.expressionNames.putAll($conditionFilterExpressions.expressionNames)`),
              set(ref('conditionExpressionValues'), raw('$util.defaultIfNull($condition.expressionValues, {})')),
              qref(`$conditionExpressionValues.putAll($conditionFilterExpressions.expressionValues)`),
github aws-amplify / amplify-cli / packages / graphql-auth-transformer / src / resources.ts View on Github external
if (groups) {
        groupAuthorizationExpressions = groupAuthorizationExpressions.concat(
          comment(`Authorization rule: { allow: groups, groups: ${JSON.stringify(groups)}, groupClaim: "${groupClaimAttribute}" }`),
          this.setUserGroups(rule.groupClaim),
          set(ref('allowedGroups'), list(groups.map(s => str(s)))),
          forEach(ref('userGroup'), ref('userGroups'), [
            iff(raw(`$allowedGroups.contains($userGroup)`), compoundExpression([set(ref(variableToSet), raw('true')), raw('#break')])),
          ])
        );
      }
    }
    const staticGroupAuthorizedVariable = this.getStaticAuthorizationVariable(field);

    // tslint:disable-next-line
    return block('Static Group Authorization Checks', [
      raw(`#set($${staticGroupAuthorizedVariable} = $util.defaultIfNull(
            $${staticGroupAuthorizedVariable}, false))`),
      ...groupAuthorizationExpressions,
    ]);
  }
github aws-amplify / amplify-cli / packages / graphql-transformer-common / src / dynamodbUtils.ts View on Github external
? set(ref(accumulatorVar1), str(`$ctx.args.${sortKeyArgumentName}.beginsWith.${keyName}`))
              : set(ref(accumulatorVar1), str(`$${accumulatorVar1}${sep}$ctx.args.${sortKeyArgumentName}.beginsWith.${keyName}`)),
            true
          )
        ),
        set(ref(`${queryExprReference}.expression`), raw(`"$${queryExprReference}.expression AND begins_with(#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}.between)`),
      compoundExpression([
        iff(
          raw(`$ctx.args.${sortKeyArgumentName}.between.size() != 2`),
          raw(`$util.error("Argument ${sortKeyArgumentName}.between expects exactly 2 elements.")`)
        ),
        ...keyNames.map((keyName, idx) =>
          iff(
            raw(`!$util.isNull($ctx.args.${sortKeyArgumentName}.between[0].${keyName})`),
            idx === 0
              ? set(ref(accumulatorVar1), str(`$ctx.args.${sortKeyArgumentName}.between[0].${keyName}`))
              : set(ref(accumulatorVar1), str(`$${accumulatorVar1}${sep}$ctx.args.${sortKeyArgumentName}.between[0].${keyName}`)),
            true
          )
        ),
        ...keyNames.map((keyName, idx) =>
          iff(
            raw(`!$util.isNull($ctx.args.${sortKeyArgumentName}.between[1].${keyName})`),
            idx === 0
              ? set(ref(accumulatorVar2), str(`$ctx.args.${sortKeyArgumentName}.between[1].${keyName}`))
github aws-amplify / amplify-cli / packages / graphql-auth-transformer / src / resources.ts View on Github external
) {
    let groupAuthorizationExpressions = [];
    for (const rule of rules) {
      // for loop do check of rules here
      const groupsAttribute = rule.groupsField || DEFAULT_GROUPS_FIELD;
      const groupClaimAttribute = rule.groupClaim || DEFAULT_GROUP_CLAIM;
      groupAuthorizationExpressions = groupAuthorizationExpressions.concat(
        formatComment
          ? comment(formatComment(rule))
          : comment(`Authorization rule: { allow: ${rule.allow}, groupsField: "${groupsAttribute}", groupClaim: "${groupClaimAttribute}"`),
        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-auth-transformer / src / resources.ts View on Github external
variableToSet: string = ResourceConstants.SNIPPETS.IsDynamicGroupAuthorizedVariable,
    defaultValue: Expression = raw(`$util.defaultIfNull($${variableToSet}, false)`)
  ): Expression {
    if (!rules || rules.length === 0) {
      return comment(`No Dynamic Group Authorization Rules`);
    }
    let groupAuthorizationExpressions = [];
    for (const rule of rules) {
      const groupsAttribute = rule.groupsField || DEFAULT_GROUPS_FIELD;
      const groupClaimAttribute = rule.groupClaim || DEFAULT_GROUP_CLAIM;
      groupAuthorizationExpressions = groupAuthorizationExpressions.concat(
        comment(`Authorization rule: { allow: ${rule.allow}, groupsField: "${groupsAttribute}", groupClaim: "${groupClaimAttribute}" }`),
        set(ref('allowedGroups'), ref(`util.defaultIfNull($${variableToCheck}.${groupsAttribute}, [])`)),
        this.setUserGroups(rule.groupClaim),
        forEach(ref('userGroup'), ref('userGroups'), [
          iff(raw('$util.isList($allowedGroups)'), iff(raw(`$allowedGroups.contains($userGroup)`), set(ref(variableToSet), raw('true')))),
          iff(raw(`$util.isString($allowedGroups)`), iff(raw(`$allowedGroups == $userGroup`), set(ref(variableToSet), raw('true')))),
        ])
      );
    }
    // check for group claim here
    return block('Dynamic Group Authorization Checks', [set(ref(variableToSet), defaultValue), ...groupAuthorizationExpressions]);
  }
github aws-amplify / amplify-cli / packages / graphql-http-transformer / src / resources.ts View on Github external
qref('$headers.put("accept-encoding", "application/json")'),
            ...parsedHeaders,
            HttpMappingTemplate.putRequest({
              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')
          ),
          ref('util.qr($util.appendError($ctx.result.body, $ctx.result.statusCode))')
        )
      ),
    }); // .dependsOn(ResourceConstants.RESOURCES.GraphQLSchemaLogicalID)
  }
github aws-amplify / amplify-cli / packages / graphql-auth-transformer / src / resources.ts View on Github external
// tslint:disable-next-line
                    set(ref('identityValue'), raw(`$util.defaultIfNull($ctx.identity.claims.get("${rawUsername}"), $util.defaultIfNull($ctx.identity.claims.get("${identityAttribute}"), "${NONE_VALUE}"))`)) :
                    set(ref('identityValue'), raw(`$util.defaultIfNull($ctx.identity.claims.get("${identityAttribute}"), "${NONE_VALUE}")`)),
                iff(
                    raw(`$util.isList($${allowedOwnersVariable})`),
                    forEach(ref('allowedOwner'), ref(allowedOwnersVariable), [
                        iff(
                            raw(`$allowedOwner == $identityValue`),
                            set(ref(variableToSet), raw('true'))),
                    ])
                ),
                iff(
                    raw(`$util.isString($${allowedOwnersVariable})`),
                    iff(
                        raw(`$${allowedOwnersVariable} == $identityValue`),
                        set(ref(variableToSet), raw('true'))),
                )
            )
            ruleNumber++
        }
        return block('Owner Authorization Checks', [
            set(ref(variableToSet), defaultValue),
            ...ownerAuthorizationExpressions
        ])
    }
github aws-amplify / amplify-cli / packages / graphql-auth-transformer / src / resources.ts View on Github external
ownerAuthorizationExpressions = ownerAuthorizationExpressions.concat(
        comment(`Authorization rule: { allow: ${rule.allow}, ownerField: "${ownerAttribute}", identityClaim: "${identityAttribute}" }`),
        set(ref(allowedOwnersVariable), ref(`${variableToCheck}.${ownerAttribute}`)),
        isUser
          ? // tslint:disable-next-line
            set(
              ref('identityValue'),
              raw(
                `$util.defaultIfNull($ctx.identity.claims.get("${rawUsername}"), $util.defaultIfNull($ctx.identity.claims.get("${identityAttribute}"), "${NONE_VALUE}"))`
              )
            )
          : set(ref('identityValue'), raw(`$util.defaultIfNull($ctx.identity.claims.get("${identityAttribute}"), "${NONE_VALUE}")`)),
        iff(
          raw(`$util.isList($${allowedOwnersVariable})`),
          forEach(ref('allowedOwner'), ref(allowedOwnersVariable), [
            iff(raw(`$allowedOwner == $identityValue`), set(ref(variableToSet), raw('true'))),
          ])
        ),
        iff(
          raw(`$util.isString($${allowedOwnersVariable})`),
          iff(raw(`$${allowedOwnersVariable} == $identityValue`), set(ref(variableToSet), raw('true')))
        )
      );
      ruleNumber++;
    }
    return block('Owner Authorization Checks', [set(ref(variableToSet), defaultValue), ...ownerAuthorizationExpressions]);
  }
github aws-amplify / amplify-cli / packages / graphql-auth-transformer / src / resources.ts View on Github external
set(ref(allowedOwnersVariable), raw(`$util.defaultIfNull($${variableToCheck}.${ownerAttribute}, null)`)),
                isUsern ?
                    // tslint:disable-next-line
                    set(ref('identityValue'), raw(`$util.defaultIfNull($ctx.identity.claims.get("${rawUsername}"), $util.defaultIfNull($ctx.identity.claims.get("${identityAttribute}"), "${NONE_VALUE}"))`)) :
                    set(ref('identityValue'), raw(`$util.defaultIfNull($ctx.identity.claims.get("${identityAttribute}"), "${NONE_VALUE}")`)),
                // If a list of owners check for at least one.
                iff(
                    raw(`$util.isList($${allowedOwnersVariable})`),
                    forEach(ref('allowedOwner'), ref(allowedOwnersVariable), [
                        iff(
                            raw(`$allowedOwner == $identityValue`),
                            set(ref(variableToSet), raw('true'))),
                    ])
                ),
                // If a single owner check for at least one.
                iff(
                    raw(`$util.isString($${allowedOwnersVariable})`),
                    iff(
                        raw(`$${allowedOwnersVariable} == $identityValue`),
                        set(ref(variableToSet), raw('true'))),
                )
            )
            // If the owner field is not a list and the user does not
            // provide a value for the owner, set the owner automatically.
            if (!ownerFieldIsList) {
                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}")`)),