如何拆分很长的 GraphQL 模式

Sca*_*ama 15 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
}
`);
Run Code Online (Sandbox Code Playgroud)

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

Lir*_*von 14

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

  1. 你可以看看 Apollo 的博客——他们展示了一种模块化架构的方法:模块化你的 GraphQL 架构代码 如果你想要一个例子,你可以看看这个github 存储库

  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);
Run Code Online (Sandbox Code Playgroud)
  1. 另一种方法是使用代码优先方法并用 javascript 而不是 graphql 模式语言编写模式。

  • 所以我可以创建多个文件并将它们嵌入到索引中,正确吗?我将来会研究 Apollo,因为我宁愿先学会在不使用任何其他库的情况下做到这一点。我需要先了解整个过程,谢谢您的帮助! (2认同)