【发布时间】:2016-08-30 21:44:29
【问题描述】:
我有以下有效的 GraphQL 操作:
GraphQL 突变:
mutation CreateUserMutation ($input: CreateUserInput!) {
createUser(input: $input) {
clientMutationId
userEdge {
node {
email
username
}
},
validationErrors {
id
email
}
}
}
GraphQL 突变响应:
{
"data": {
"createUser": {
"clientMutationId": "112",
"userEdge": {
"node": {
"email": "prasath112@example.com",
"username": "soosap112"
}
},
"validationErrors": {
"id": "create-user-validation-errors",
"email": [
"Email looks not so good."
]
}
}
}
}
到目前为止一切顺利,我的 GraphQL 响应的 validationErrors 是键值对的对象,其中 value 始终是来自服务器的输入验证错误消息数组特定的输入字段(即{'email': ['email is taken', 'email is on blacklist']})。
下一步(这是我需要帮助的地方)-如何在 Relay 客户端存储中使用该数据?换句话说,要如何让我的组件中的 validationErrors 成为this.props.validationErrors?
CreateUserMutation.js
import Relay from 'react-relay';
export class CreateUserMutation extends Relay.Mutation {
getMutation() {
return Relay.QL`
mutation {
createUser
}
`;
}
getVariables() {
return {
email: this.props.email,
username: this.props.username,
password: this.props.password,
};
}
getFatQuery() {
return Relay.QL`
fragment on CreateUserPayload @relay(pattern: true) {
userEdge,
validationErrors,
viewer { userConnection }
}
`;
}
getConfigs() {
return [
{
type: 'FIELDS_CHANGE',
fieldIDs: {
validationErrors: 'create-user-validation-errors',
},
},
{
type: 'RANGE_ADD',
parentName: 'viewer',
parentID: this.props.viewer.id,
connectionName: 'userConnection',
edgeName: 'userEdge',
rangeBehaviors: {
// When the ships connection is not under the influence
// of any call, append the ship to the end of the connection
'': 'append',
// Prepend the ship, wherever the connection is sorted by age
// 'orderby(newest)': 'prepend',
},
},
];
}
}
这是我的尝试:首先,我可以使用 getConfigs RANGE_ADD 将 user edge 消耗到我的 Relay 客户端存储中。由于我的validationErrors 对象没有实现连接模型,所以FIELDS_CHANGE 在我的例子中似乎是唯一合理的类型。我正在尝试模拟 Relay 似乎需要使用“create-user-validation-errors”作为唯一 ID 填充客户端存储的 dataID。
这是我的 React 组件中的一个 sn-p,用于使示例完整。
class App extends React.Component {
static propTypes = {
limit: React.PropTypes.number,
viewer: React.PropTypes.object,
validationErrors: React.PropTypes.object,
};
static defaultProps = {
limit: 5,
validationErrors: {
id: 'create-user-validation-errors',
},
};
handleUserSubmit = (e) => {
e.preventDefault();
Relay.Store.commitUpdate(
new CreateUserMutation({
email: this.refs.newEmail.value,
username: this.refs.newUsername.value,
password: this.refs.newPassword.value,
viewer: this.props.viewer,
})
);
};
如何使用 Relay 从 React 组件中的 GraphQL 响应中使用基于非连接模型的信息片段?最小的工作示例会很棒。
您知道使用 GraphQL 和 Relay 进行服务器端输入验证的更好方法吗?
【问题讨论】:
标签: relayjs