AWS Amplify API/React:如何过滤LIST查询获取指定关联公司的项目数据
实现方案
完全可以通过传入关联公司ID过滤ListProjects查询实现需求,具体操作步骤如下:
前置检查
首先确认你的Amplify GraphQL Schema中,Projects模型和Companies模型的关联定义是否符合规范,如果你使用了Amplify官方的@belongsTo/@hasOne指令定义一对一关联,Projects模型会自动生成关联外键字段(通常命名为companyID,可根据你自己的定义调整),该字段默认支持作为过滤条件使用。
方案1:前端传过滤条件(快速实现)
步骤1:获取当前登录用户的自定义CompanyID属性
调用Amplify Auth接口拿到当前用户的自定义属性,注意Cognito的自定义属性默认会带custom:前缀:
import { Auth, API, graphqlOperation } from 'aws-amplify'; import { listProjects } from './graphql/queries';
步骤2:带过滤条件调用ListProjects查询
const fetchMyCompanyProjects = async () => { try { // 取当前登录用户信息 const user = await Auth.currentAuthenticatedUser(); const targetCompanyId = user.attributes['custom:CompanyID']; // 传入filter参数过滤关联公司ID const queryResult = await API.graphql(graphqlOperation(listProjects, { filter: { companyID: { eq: targetCompanyId } } })); return queryResult.data.listProjects.items; } catch (error) { console.error('查询项目列表失败:', error); } }
如果你的外键字段名不是companyID,替换为你Schema中定义的对应字段名即可。
方案2:后端权限控制(更安全,推荐)
如果不希望依赖前端传参过滤,避免参数被篡改导致越权访问,可以直接在Schema中通过@auth配置权限规则,实现自动过滤:
type Projects @model @auth(rules: [ # 直接从Cognito身份声明中取custom:CompanyID和项目的companyID字段匹配 { allow: owner, ownerField: "companyID", identityClaim: "custom:CompanyID" } ]) { id: ID! projectName: String! companyID: ID! belongCompany: Companies @belongsTo(fields: ["companyID"]) # 其他字段... }
配置完成后重新发布Amplify后端,后续前端调用listProjects时不需要传任何过滤参数,Amplify后端会自动根据当前登录用户的CompanyID返回对应项目,安全性更高。
内容的提问来源于stack exchange,提问作者Jacob Nolley
相关产品推荐
相关产品推荐

