首页 > 解决方案 > Javascript 中的 GraphQL 查询

问题描述

我目前正在尝试将我的 Postman 查询转移到生产中。我在这里有这个查询。 邮差

我想将此添加到作为 GH Action 运行的节点包中。

const core = require("@actions/core");
const github = require("@actions/github");
const { graphql, buildSchema } = require('graphql');

const run = async () => {
  /** The token used to access Gatsby Cloud */
  const gatsbyToken = core.getInput("gatsby-token");
  /** The ID of the site to modify */
  const siteID = core.getInput("gatsby-site-id");
  /** The GraphQL schema used to query the existing ENV */
  const schema = buildSchema(`
    query AllEnvironmentVariablesForSite($id: UUID!) {
      buildEnvironmentVariablesForSite: environmentVariablesForSite(
        id: $id
        runnerType: BUILDS
      ) {
        key
        value
        truncatedValue
      }
      previewEnvironmentVariablesForSite: environmentVariablesForSite(
        id: $id
        runnerType: PREVIEW
      ) {
        key
        value
        truncatedValue
      }
    }
  `);
  /** The variables associated to the GraphQL schema above */
  const variables = {
    id: siteID
  }
  console.log( { variables } )
  try {
    /** The existing ENV in Gatsby Cloud */
    const existing = await fetch( 'https://api.gatsbyjs.com/graphql', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Authorization': `Bearer ${gatsbyToken}`
      },
      body: JSON.stringify( { query, variables } )
    } )
  } catch ( error ) {
    core.setFailed( error.message )
  }
}

run()

当我在本地运行它时,我收到 UUID is an unknown type: 的错误Unknown type "UUID".

我该如何解决这个问题?

标签: graphqlgithub-actions

解决方案


这样做的问题是查询应该格式化为字符串。该问题的查询格式与 Express 服务器中的格式相同。

...
  /** The GraphQL schema used to query the existing ENV */
  const query = `
    query AllEnvironmentVariablesForSite($id: UUID!) {
      buildEnvironmentVariablesForSite: environmentVariablesForSite(
        id: $id
        runnerType: BUILDS
      ) {
        key
        value
        truncatedValue
      }
      previewEnvironmentVariablesForSite: environmentVariablesForSite(
        id: $id
        runnerType: PREVIEW
      ) {
        key
        value
        truncatedValue
      }
    }`
...
try {
    /** The existing ENV in Gatsby Cloud */
    const existing = await fetch( 'https://api.gatsbyjs.com/graphql', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Authorization': `Bearer ${gatsbyToken}`
      },
      body: JSON.stringify( { query, variables } )
    } )
    const existingJSON  = await existing.json()
    console.log( existingJSON.data )
  } catch ( error ) {
    core.setFailed( error.message )
  }
}

推荐阅读