javascript - 如何拆分长 GraphQL 模式

标签 javascript graphql

我正在尝试创建一个架构,但是会变得太长和困惑,拆分不同查询、突变和输入的最佳实践是什么,这样我就可以只需要它们并组织它们以使其易于阅读.

我试图在网上查找信息,但没有任何明确的信息,我尽量不使用 Apollo。

const { buildSchema } = require('graphql');

module.exports = buildSchema(`
type Region {
  _id: ID!
  name: String!
  countries: [Country!]
}

type Country {
  _id: ID!
  name: String!
  region: [Region!]!
}

type City {
  _id: ID!
  name: String!
  country: [Country!]!
}

type Attraction {
  _id: ID!
  name: String!
  price: Float!
  description: String!
  city: [City!]!
}

type Eatery {
  _id: ID!
  name: String!
  cuisine: String!
  priceRange: String!
  location: [Location!]!
  typeOfEatery: String!
  city: [City!]!
}

type Location {
  _id: ID!
  latitude: String!
  longitude: String!
  address: Float
}

type User {
  _id: ID!
  email: String!
  password: String!
}

type AuthData {
  userId: ID!
  token: String!
  tokenExpiration: String!
}

type RegionInput {
  name: String!
}

type CountryInput {
  name: String!
}

type CityInput {
  name: String!
}

type RootQuery {
  regions: [Region!]!
  countries: [Country!]!
  login(email: String!, password: String!): AuthData!
}

type RootMutation {
  createRegion(regionInput: RegionInput): Region
  createCountry(countryInput: CountryInput): Country
  createCity(cityInput: CityInput): City
}

schema {
  query: RootQuery
  mutation: RootMutation
}
`);

我需要一些非常有条理的东西,让我把所有的东西都整理得井井有条,将所有文件合并到一个索引中是最好的解决方案。

最佳答案

有多个选项,这里是其中三个:

  1. 您可以查看 Apollo 的博客 - 他们展示了一种模块化模式的方法:Modularizing your GraphQL schema code 如果你想要一个例子,你可以看看这个 github repository

  2. 当然,您始终可以只使用模板文字将模式的一部分作为字符串嵌入:

const countryType = `
type Country {
  _id: ID!
  name: String!
  region: [Region!]!
}
`

const regionType = `
type Region {
  _id: ID!
  name: String!
  countries: [Country!]
}
`

const schema = `
${countryType}
${regionType}

# ... more stuff ...
`

module.exports = buildSchema(schema);
  1. 另一种方法是使用代码优先方法并使用 javascript 而不是 graphql 模式语言编写模式。

关于javascript - 如何拆分长 GraphQL 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57040429/

相关文章:

amazon-dynamodb - AWS AppSync - 为缺少自定义类型和枚举的架构创建资源

javascript - 如何在javascript中通过两个对象创建新对象

javascript - 谁知道如何将 "Ulkit 3"(https ://getuikit. com/) 连接到“Vue.js 2

javascript - 如何合并这些数组/json 对象?

reactjs - <Query> 与 graphql Hoc 这是在 React apollo 中将 graphql 查询与组件 Hook 的最佳方式

GraphQL:突变运行时订阅不会触发

reactjs - Apollo 缓存 - 缺少为查询字段名称返回的类型 undefined object 的选择集

javascript - 使用 React.JS 向容器填充内容

javascript - onclick 在表单中显示 &lt;input&gt; 文本字段

amazon-web-services - DynamoDB : Best hash/sort keys for my use case [confusion with AppSync/GraphQL]