reactjs 放大GraphQL从ID以外的其他字段获取项

f45qwnt8  于 2023-06-22  发布在  React
关注(0)|答案(2)|浏览(87)

我正在使用React和AWS Amplify实现一个网页。
我在schema.graphql文件中有以下定义:

type Calendar @model {
  id: ID!
  name: String
  description: String
  url: String!
  intervals: [Interval] @connection(keyName: "byCalendar", fields: ["id"])
}

我想从它的URL字符串获取日历。不幸的是,下面的代码抛出一个错误:

import { API, graphqlOperation } from "aws-amplify";
import * as queries from "../../graphql/queries";

await API.graphql(graphqlOperation(queries.getCalendar, { url: "some-url"}));

Variable "$id" of required type "ID!" was not provided.
根据错误,必须提供ID。但是,我希望能够从URL中获取对象。
我该怎么做?
我使用的是由amplify的cli自动生成的查询。

/* eslint-disable */
// this is an auto generated file. This will be overwritten

export const getCalendar = /* GraphQL */ `
  query GetCalendar($id: ID!) {
    getCalendar(id: $id) {
      id
      name
      description
      url
      intervals {
        nextToken
      }
      createdAt
      updatedAt
    }
  }
`;
export const listCalendars = /* GraphQL */ `
  query ListCalendars(
    $filter: ModelCalendarFilterInput
    $limit: Int
    $nextToken: String
  ) {
    listCalendars(filter: $filter, limit: $limit, nextToken: $nextToken) {
      items {
        id
        name
        description
        url
        createdAt
        updatedAt
      }
      nextToken
    }
  }
`;
k97glaaz

k97glaaz1#

找到解决办法了。我不得不在模型中添加一个“byURL”键,如下所示:

type Calendar @model @key(name: "byURL", fields: ["url", "id"], queryField: "calendarByURL") {
    id: ID!
    name: String
    description: String
    url: String
    intervals: [Interval] @connection(keyName: "byCalendar", fields: ["id"])
}

然后使用新键编写一个自定义查询(或者使用amplify根据更新的schema.graphql文件重新生成查询):

export const getCalendarByURL = /* GraphQL */ `
    query calendarByURL($url: String!) {
        calendarByURL(url: $url) {
            items {
                id
                name
                description
                url
                intervals {
                    nextToken
                }
                createdAt
                updatedAt
            }
        }
    }
`;

这会让我做:

await API.graphql(graphqlOperation(customQueries.getCalendarByURL, { url: "some-url"}));
qyswt5oh

qyswt5oh2#

在较新的版本中,您现在必须以以下方式替换@key指令(参见GraphQL Transformer v2):

type Calendar @model {
    id: ID!
    name: String
    description: String
    url: String @index(name: "byUrl", queryField: "calendarByUrl")
    intervals: [Interval] @connection(keyName: "byCalendar", fields: ["id"])
}

相关问题