对 Contentful 的 GraphQL 查询仅返回 imagesCollection 中的一张图像,尽管存在多个图像

问题描述 投票:0回答:1

我正在开发一个 Next.js 项目,使用 Contentful 作为我的 CMS。我正在通过 GraphQL 查询获取房间详细信息,包括图像集合。在 Contentful UI 中,房间条目包含 imagesCollection 中的多个图像。但是,当我在代码中运行 GraphQL 查询时,

imagesCollection.items
数组仅返回一个图像对象,即使多个图像与房间关联也是如此。

{
  roomsCollection(where: { id: "ROOM_ID" }, order: id_ASC) {
    items {
      id
      roomType
      hotelSlug
      included
      imagesCollection {
        items {
          title
          description
          url
          fileName
        }
      }
    }
  }
}

响应中的

imagesCollection.items
数组仅包含一个对象,而在 Contentful 中,多个图像链接到房间。

其他字段(如

roomType
hotelSlug
included
)已正确获取。

我采取的步骤:

  1. 检查了内容丰富的条目:所有图像均已正确上传和发布。
  2. 在 Contentful GraphQL Playground 中测试查询:它正确返回所有图像。
  3. 确认其余数据(例如,
    roomType
    included
    )正在顺利获取。

我的抓取功能:

export async function getRoomDetailsById(
  id: string
): Promise<{ RoomCollectionItem: RoomCollectionType[] }> {
  const response = await fetch(ApiUrl, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.NEXT_PUBLIC_CONTENTFUL_ACCESS_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      query: `
        {
          roomsCollection(where: { id: "${id}" }, order: id_ASC) {
            items {
              id
              roomType
              hotelSlug
              included
              imagesCollection {
                items {
                  title
                  description
                  url
                  fileName
                }
              }
            }
          }
        }
      `,
    }),
  });

  const json: ApiResponse = await response.json();
  console.log(json.data.roomsCollection.items[0].imagesCollection.items);
  
  return {
    RoomCollectionItem: json.data.roomsCollection.items,
  };
}
next.js graphql contentful
1个回答
0
投票

您是否尝试过将 limit 参数传递给 imagesCollection?但不确定为什么游乐场结果与您的实际查询之间存在差异。

© www.soinside.com 2019 - 2024. All rights reserved.