はじめに
これは、DB操作に不慣れな弱々フロントエンドエンジニアのつまづき記録です〜〜〜
環境
- aws-amplify
- next.js
queryやmutationはamplify mock apiコマンドを使用したmockを叩いています!
状況
下記記事を参考に 多対多のリレーション作成のためにgraphql schemaを下記に変更
変更前
type Resource @model {
id: ID!
categoryId: ID!
userId: ID!
title: String!
url: String!
category: Category @connection(fields: ["categoryId"])
}
type User @model {
id: ID!
name: String!
email: String!
profileImagePath: String!
progressRate: Int!
resourcesCount: Int!
posts: [Post] @connection(keyName: "postsByUserId", fields: ["id"])
}
変更後
type Resource @model {
id: ID!
categoryId: ID!
userId: ID!
title: String!
url: String!
category: Category @connection(fields: ["categoryId"])
users: [ResourceUser] @connection(keyName: "byResource", fields: ["id"])
}
type ResourceUser
@model(queries: null)
@key(name: "byResource", fields: ["resourceId", "userId"])
@key(name: "byUser", fields: ["userId", "resourceId"]) {
id: ID!
resourceId: ID!
userId: ID!
resource: Resource! @connection(fields: ["resourceId"])
user: User! @connection(fields: ["userId"])
}
type User @model {
id: ID!
name: String!
email: String!
profileImagePath: String!
progressRate: Int!
resourcesCount: Int!
posts: [Post] @connection(keyName: "postsByUserId", fields: ["id"])
resources: [ResourceUser] @connection(keyName: "byUser", fields: ["id"])
}
```
https://docs.amplify.aws/cli-legacy/graphql-transformer/connection/
これで、多対多のリレーション行ける〜〜と舞い上がってたら、
```javascript
const fetchCurrentUser = async (userId: string) => {
try {
return (await API.graphql({
query: getUser,
variables: {
id: userId,
},
})) as { data: GetUserQuery }
} catch (error) {
console.error(error)
}
}
```
って感じでクエリ叩いてるところで、`Query condition missed key schema element `でめっちゃ怒られました。
## 結論
理由わからず奮闘しましたが、
mock-dataが古いから新しいスキーマと型合ってないけど大丈夫か?と怒られてるだけでした。
なので、amplifyディレクトリ内のmock-dataを削除して、`amplify mock api`
を叩き直せば解決しました。
## 終わりに
リレーションとかDBがらみの設定変更したら、DBリセットするの忘れんように要注意じゃ~~
## 参考文献
https://github.com/aws-amplify/amplify-cli/issues/2210