如何使用GraphQL

快速开始

通过下面的代码,我们可以快速使用GraphQL实现查询。
import { graphql, buildSchema } from 'graphql';

const schema = buildSchema(/* GraphQL */ `
  type Query {
    hello: String
  }
`);
const root = { hello: () => 'Hello world!' };

const response = await graphql({
  schema,
  source: /* GraphQL */ `
    {
      hello
    }
  `,
  rootValue: root
});

console.log(response);

使用graphql-tools

我们可以使用graphql-tools来使用GraphQL。
首先我们先创建两个GraphQL文件。

query.graphql

#import './human.graphql'

type Query {
    hello: String
    human(age: Int): Human
}

human.graphql

type Human {
    name: String
    age: Int
}
创建一个方法,用于加载GraphQL文件。
import { URL } from 'node:url';
import { loadSchema } from '@graphql-tools/load';
import { GraphQLFileLoader } from '@graphql-tools/graphql-file-loader';

export async function getSchema(file, importMetaUrl) {
  const urlResult = decodeURIComponent(new URL(file, importMetaUrl).pathname);

  return loadSchema(urlResult, {
    loaders: [new GraphQLFileLoader()]
  });
}
实现查询。
import { graphql } from 'graphql';
import { addResolversToSchema } from '@graphql-tools/schema'
import { getSchema } from './utils.js';

const resolvers = {
  Query: {
    hello(obj, args, context, info) {
      return '你好';
    },
    human(obj, args, context, info) {
      return {
        name: '小明',
        age: args.age + obj.$add()
      };
    }
  }
};
const schema = await getSchema('./query.graphql', import.meta.url);
const schemaWithResolvers = addResolversToSchema({ schema, resolvers });

const response = await graphql({
  schema: schemaWithResolvers,
  source: /* GraphQL */ `
    {
      hello
      human(age: 56) {
        name
        age
      }
    }
  `,
  rootValue: {
    $add() {
      return 32;
    }
  }
});

console.log(response.data);

webpack配置

如果要通过webpack来配置使用,首先要配置loader。
export default {
  mode: 'development',
  module: {
    rules: [
      {
        test: /^.*\.(gql|graphql)$/,
        loader: '@graphql-tools/webpack-loader',
        options: {
          importHelpers: true
        }
      }
    ]
  }
};
然后在项目中使用。
import { graphql, buildASTSchema } from 'graphql';
import query from './query.graphql';

const root = {
  hello() {
    return '你好';
  },
  human() {
    return {
      name: '小明',
      age: 14
    };
  }
}

graphql({
  schema: buildASTSchema(query),
  source: /* GraphQL */ `
    {
        hello
        human {
            name
            age
        }
    }
  `,
  rootValue: root
}).then((response) => {
  console.log(response);
});