GraphQL

Integrate Strapi with GraphQL.

开始使用 GraphQL

本集成指南遵循 快速入门指南,并假设您已完全完成“动手”路径。您应该能够通过浏览 URL http://localhost:1337/api/restaurants 来使用该 API。

如果您尚未阅读快速入门指南,使用 GraphQL 请求 Strapi API 的方式保持不变,只是您不会获取相同的内容。

安装 GraphQL 插件

在您的 Strapi 项目中安装 GraphQL 插件。

bash
yarn strapi install graphql
npm run strapi install graphql

获取您的餐厅集合类型

使用 GraphQL Playground 获取您的内容。

graphql
query Restaurants {
  restaurants {
    id
    name
    description
    categories {
      name
    }
  }
}
json
{
  "data": {
    "restaurants": [
      {
        "id": "1",
        "name": "Biscotte Restaurant",
        "description": "Welcome to Biscotte restaurant! Restaurant Biscotte offers a cuisine based on fresh, quality products, often local, organic when possible, and always produced by passionate producers.",
        "categories": [
          {
            "name": "French Food"
          }
        ]
      }
    ]
  }
}

示例

这些示例不包括使用 Apollo 为您的 GraphQL 端点 配置客户端。请遵循 ReactVue.js 的相关文档。

js
react
js
import { gql, useQuery } from '@apollo/client'

function Restaurants() {
  const { loading, error, data } = useQuery(gql`
    query Restaurants {
      restaurants {
        id
        name
        description
        categories {
          name
        }
      }
    }
  `)

  if (loading)
    return 'Loading...'
  if (error)
    return `Error! ${error.message}`

  return (
    <ul>
      {data.restaurants.map(restaurant => (
        <li key={restaurant.id}>{restaurant.name}</li>
      ))}
    </ul>
  )
}