How to use the graphql-mapping-template.set 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-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-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-relation-transformer / src / ModelRelationTransformer.ts View on Github external
}

    return new Resolver({
        ApiId: Fn.GetAtt(ResourceConstants.RESOURCES.GraphQLAPILogicalID, 'ApiId'),
        DataSourceName: ModelResourceIDs.ModelTableResourceID(relatedType.name.value),
        FieldName: field,
        TypeName: type,
        RequestMappingTemplate: print(
            compoundExpression([
                ...setup,
                DynamoDBMappingTemplate.query(queryArguments)
            ])
        ),
        ResponseMappingTemplate: print(
            compoundExpression([
                iff(raw('!$result'), set(ref('result'), ref('ctx.result'))),
                raw('$util.toJson($result)')
            ])
        )
    }).dependsOn([ResourceConstants.RESOURCES.GraphQLSchemaLogicalID, ModelResourceIDs.ModelTableResourceID(relatedType.name.value)])
}
github aws-amplify / amplify-cli / packages / graphql-dynamodb-transformer / lib / resources.js View on Github external
ResourceFactory.prototype.makeDeleteResolver = function (type, nameOverride) {
        var fieldName = nameOverride ? nameOverride : graphql_transformer_common_1.graphqlName('delete' + graphql_transformer_common_1.toUpper(type));
        return new appSync_1.default.Resolver({
            ApiId: cloudform_1.Fn.GetAtt(graphql_transformer_common_1.ResourceConstants.RESOURCES.GraphQLAPILogicalID, 'ApiId'),
            DataSourceName: cloudform_1.Fn.GetAtt(graphql_transformer_common_1.ModelResourceIDs.ModelTableDataSourceID(type), 'Name'),
            FieldName: fieldName,
            TypeName: 'Mutation',
            RequestMappingTemplate: graphql_mapping_template_1.print(graphql_mapping_template_1.compoundExpression([
                graphql_mapping_template_1.ifElse(graphql_mapping_template_1.ref(graphql_transformer_common_1.ResourceConstants.SNIPPETS.AuthCondition), graphql_mapping_template_1.compoundExpression([
                    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.DynamoDBMappingTemplate.deleteItem({
                    key: graphql_mapping_template_1.obj({
                        id: graphql_mapping_template_1.ref('util.dynamodb.toDynamoDBJson($ctx.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)'))
github aws-amplify / amplify-cli / packages / graphql-elasticsearch-transformer / src / resources.ts View on Github external
const fieldName = nameOverride ? nameOverride : graphqlName('search' + plurality(toUpper(type)));
    return new AppSync.Resolver({
      ApiId: Fn.GetAtt(ResourceConstants.RESOURCES.GraphQLAPILogicalID, 'ApiId'),
      DataSourceName: Fn.GetAtt(ResourceConstants.RESOURCES.ElasticsearchDataSourceLogicalID, 'Name'),
      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))\
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: 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"`),
                set(ref(`${requestVariable}.scanIndexForward`), bool(false)),
                set(ref(`${requestVariable}.scanIndexForward`), bool(true))
              ),
            ]),
github aws-amplify / amplify-cli / packages / graphql-relational-schema-transformer / src / RelationalDBResolverGenerator.ts View on Github external
type
      )}Input.${this.typePrimaryKeyMap.get(type)}`;
    }

    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,
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'), [
github aws-amplify / amplify-cli / packages / graphql-connection-transformer / src / resources.ts View on Github external
const queryObj = DynamoDBMappingTemplate.query(queryArguments);

        return new Resolver({
            ApiId: Fn.GetAtt(ResourceConstants.RESOURCES.GraphQLAPILogicalID, 'ApiId'),
            DataSourceName: Fn.GetAtt(ModelResourceIDs.ModelTableDataSourceID(relatedType.name.value), 'Name'),
            FieldName: field,
            TypeName: type,
            RequestMappingTemplate: print(
                compoundExpression([
                    ...setup,
                    queryObj
                ])
            ),
            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 / resources.ts View on Github external
public dynamicGroupAuthorizationExpressionForReadOperations(
        rules: AuthRule[],
        variableToCheck: string = 'ctx.result',
        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
            groupAuthorizationExpressions = groupAuthorizationExpressions.concat(
                comment(`Authorization rule: { allow: ${rule.allow}, groupsField: "${groupsAttribute}" }`),
                set(ref('allowedGroups'), ref(`util.defaultIfNull($${variableToCheck}.${groupsAttribute}, [])`)),
                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'))),
                    )
                ])
            )
        }