教你使用GraphQL Yoga构建强大的GraphQL服务器

编程语言译者 2021-09-11 ⋅ 34 阅读

GraphQL Yoga 是一个基于 Express.js 构建的 GraphQL 服务器库,它提供了一种简单快捷的方式来构建和运行强大的 GraphQL 服务器。本博客将教你如何使用 GraphQL Yoga 来构建一个完整的 GraphQL 服务器。

什么是 GraphQL?

GraphQL 是一种用于 API 的查询语言和运行时环境。它允许客户端向服务器发送一个描述所需数据的查询,而服务器会根据这个查询来提供对应的响应。与传统的 RESTful API 不同,GraphQL 允许客户端精确地指定需要的数据,并减少了过多或不必要的数据传输。GraphQL 的一大特点就是它的强大灵活性和可组合性,使得客户端可以根据需求自由地组合和获取数据。

GraphQL Yoga 简介

GraphQL Yoga 是一个基于 Express.js 的库,它结合了 GraphQL 和 Node.js 的优势,提供了一个快速搭建 GraphQL 服务器的框架。它内置了 Apollo Server,Apollo Client 和 Prisma,使得我们可以非常方便地构建和扩展 GraphQL 服务器。

安装和设置项目

首先,我们需要在项目中安装 GraphQL Yoga。打开命令行终端,进入你的项目目录,运行以下命令来安装依赖:

npm install graphql-yoga

完成后,你可以创建一个新的文件 index.js,并引入 GraphQL Yoga:

const { GraphQLServer } = require('graphql-yoga');

// 定义 schema 和 resolvers
const typeDefs = `
  type Query {
    hello: String!
  }
`;

const resolvers = {
  Query: {
    hello: () => 'Hello, GraphQL Yoga!'
  }
};

const server = new GraphQLServer({ typeDefs, resolvers });

// 启动服务器
server.start(() => console.log('Server is running on localhost:4000'));

在上面的代码中,我们定义了一个简单的 schema 和 resolvers,其中 hello 是我们一个查询字段,返回一个固定的字符串。然后,我们通过 GraphQLServer 类创建了一个服务器实例,并传入了 schema 和 resolvers。最后,我们启动了服务器并打印出服务的运行地址。

现在你可以运行以下命令来启动你的 GraphQL 服务器:

node index.js

访问 http://localhost:4000,你将看到 GraphQL Playground 的界面。在左侧的查询编辑器中输入以下查询语句:

query {
  hello
}

点击执行按钮,你将在右侧的结果窗口中看到返回的结果:

{
  "data": {
    "hello": "Hello, GraphQL Yoga!"
  }
}

恭喜!你已经成功创建了你的第一个 GraphQL 服务器。

构建更复杂的 GraphQL 服务器

现在我们将创建一个更复杂的 GraphQL 服务器,包含更多的查询和数据类型。

首先,我们需要安装一些额外的依赖来辅助我们构建服务器:

npm install graphql
npm install -D nodemon

我们使用 nodemon 来监听代码的变化,使得在开发过程中服务器会自动重启。

在项目根目录下创建一个文件夹 schema,并在其中创建一个新的文件 schema.graphql。在这个文件里,我们定义数据模型和查询的结构:

type User {
  id: ID!
  name: String!
  email: String!
  posts: [Post!]!
}

type Post {
  id: ID!
  title: String!
  content: String!
  published: Boolean!
  author: User!
}

type Query {
  users: [User!]!
  posts: [Post!]!
}

schema.graphql 中,我们定义了两个数据类型 UserPost,以及一个查询类型 QueryUser 类型表示一个用户对象,包含 idnameemailposts 字段,其中 posts 是一个包含 Post 类型对象的数组。Post 类型表示一个帖子对象,包含 idtitlecontentpublishedauthor 字段,其中 author 字段指向一个 User 类型的对象。最后,Query 类型中定义了两个查询字段 usersposts,分别返回一个用户对象数组和帖子对象数组。

接下来,我们创建一个新的文件 resolvers.js,并在其中实现对应的解析器函数:

const users = [
  {
    id: '1',
    name: 'Alice',
    email: 'alice@example.com',
    posts: ['1', '2']
  },
  {
    id: '2',
    name: 'Bob',
    email: 'bob@example.com',
    posts: ['3']
  },
  {
    id: '3',
    name: 'Charlie',
    email: 'charlie@example.com',
    posts: []
  }
];

const posts = [
  {
    id: '1',
    title: 'Introduction to GraphQL',
    content: '...',
    published: true,
    author: '1'
  },
  {
    id: '2',
    title: 'Getting Started with GraphQL Yoga',
    content: '...',
    published: false,
    author: '1'
  },
  {
    id: '3',
    title: 'GraphQL vs RESTful API',
    content: '...',
    p    ```
    odigo
    llowed: true,
    author: '2'
  }
];

const resolvers = {
  Query: {
    users: () => users,
    posts: () => posts
  },
  User: {
    posts: (parent) => parent.posts.map((postId) => posts.find((post) => post.id === postId))
  },
  Post: {
    author: (parent) => users.find((user) => user.id === parent.author)
  }
};

module.exports = resolvers;

resolvers.js 中,我们定义了一个虚拟的数据源,包含了一些用户对象和帖子对象的数据。然后,我们实现了对应的解析器函数,用于处理对应字段的查询。

最后,我们需要更新 index.js 文件来加载和使用 schema 和 resolvers:

const { GraphQLServer } = require('graphql-yoga');
const resolvers = require('./resolvers');

const server = new GraphQLServer({
  typeDefs: './schema/schema.graphql',
  resolvers
});

server.start({ port: 4000 }, () => console.log('Server is running on localhost:4000'));

现在,运行以下命令来启动你的 GraphQL 服务器:

npm run dev

打开 http://localhost:4000,你将进入 GraphQL Playground。尝试以下查询语句:

query {
  users {
    id
    name
    email
    posts {
      title
    }
  }
  posts {
    title
    author {
      name
    }
  }
}

你将会得到类似以下的结果:

{
  "data": {
    "users": [
      {
        "id": "1",
        "name": "Alice",
        "email": "alice@example.com",
        "posts": [
          {
            "title": "Introduction to GraphQL"
          },
          {
            "title": "Getting Started with GraphQL Yoga"
          }
        ]
      },
      {
        "id": "2",
        "name": "Bob",
        "email": "bob@example.com",
        "posts": [
          {
            "title": "GraphQL vs RESTful API"
          }
        ]
      },
      {
        "id": "3",
        "name": "Charlie",
        "email": "charlie@example.com",
        "posts": []
      }
    ],
    "posts": [
      {
        "title": "Introduction to GraphQL",
        "author": {
          "name": "Alice"
        }
      },
      {
        "title": "Getting Started with GraphQL Yoga",
        "author": {
          "name": "Alice"
        }
      },
      {
        "title": "GraphQL vs RESTful API",
        "author": {
          "name": "Bob"
        }
      }
    ]
  }
}

恭喜!你已经成功构建了一个完整的 GraphQL 服务器,带有复杂的查询和数据类型。

结语

在本博客中,我们介绍了如何使用 GraphQL Yoga 来构建强大的 GraphQL 服务器。我们学习了 GraphQL 的概念和基本语法,以及 GraphQL Yoga 的安装和使用。此外,我们还演示了如何使用 GraphQL Yoga 构建一个具有复杂查询和数据类型的 GraphQL 服务器。希望本博客可以帮助你入门 GraphQL 服务器的搭建,祝你在后续的开发中取得更多的成功!


全部评论: 0

    我有话说: