(苏维埃社会主义共和国)如何在服务器上获取 IntrospectionFragmentMatcher 的片段类型



是否可以直接从模式中获取fragmentType?

IntrospectionFragmentMatcher 的文档展示了如何获取这些内容并将其存储在 JSON 文件中 - 但它似乎只考虑客户端使用并假设您有一个正在运行的服务器。

由于我使用与 GraphQL API 相同的服务器以及渲染应用程序,因此这是一个先有鸡还是先有蛋的事情。我仍然可以按照文档所说的额外的构建步骤来做到这一点,但这基本上意味着:

  1. 从 src 构建
  2. 启动服务器
  3. 运行脚本以提取片段类型,并将其写入.json文件
  4. 重新启动服务器

我觉得一定有一种更简单的方法可以做到这一点。

渲染应用程序时,我正在创建一个带有SchemaLink的新 Apollo 客户端,因此我已经有一个完全准备好的架构。

现在我有这个:

import introspectionQueryResultData from './fragmentTypes.json'
const fragmentMatcher = new IntrospectionFragmentMatcher({
    introspectionQueryResultData,
})

const render = ({ schema, context }) => async (req, res, next) => {
    const client = new ApolloClient({
        ssrMode: true,
        link: new SchemaLink({ schema, context }),
        cache: new InMemoryCache({
            fragmentMatcher,
        }),
    })
    // ...

我希望能够像这样的事情:

const render = ({ schema, context }) => async (req, res, next) => {
    const client = new ApolloClient({
        ssrMode: true,
        link: new SchemaLink({ schema, context }),
        cache: new InMemoryCache({
            fragmentMatcher: fragmentMatcherFromSchema(schema)
        }),
    })
    // ...

这可能吗?

这很可能是可能的,但我还没有尝试在运行时完全这样做。但是,您可以避免必须运行启动服务器来提取片段。

如果您使用的是 GraphQL 代码生成器 (https://graphql-code-generator.com/docs/getting-started/(。

您可以为架构指定各种输入,而不是运行服务器的 url,请参阅:https://graphql-code-generator.com/docs/getting-started/schema-field#available-formats

您至少可以将步骤减少到

  1. 从 src 构建
  2. 运行脚本以提取片段类型,并将其写入 .json 文件
  3. 启动服务器

最新更新