yoga720 -12_如何使用GraphQL-yoga和MongoDB在Node.js中构建GraphQL服务器

yoga720 -12

Most applications today have the need to fetch data from a server where that data is stored in a database. GraphQL is a new API standard that provides a more efficient, powerful and flexible alternative to REST. It allows a client fetch only the data it needs from a server. GraphQL is often confused with being a database technology, but his is a misconception, GraphQL is a query language for APIs , not databases. In that sense, it’s database agnostic and effectively can be used in any context where an API is used.

如今,大多数应用程序都需要从服务器中获取数据,而该服务器将数据存储在数据库中。 GraphQL是新的API标准,它提供了REST的更有效,更强大和更灵活的替代方法。 它允许客户端仅从服务器获取其需要的数据。 GraphQL通常与作为数据库技术混淆,但是他是一个误解,GraphQL是API而不是数据库的查询语言。 从这个意义上讲,它与数据库无关,并且可以在使用API​​的任何上下文中有效使用。

graphql-yoga is a fully-featured GraphQL Server with focus on ease-of-use, performance, and great developer experience. Additionally, it supports all GraphQL clients like Apollo.

graphql-yoga是功能齐全的GraphQL服务器,其重点在于易用性,性能和出色的开发人员经验。 此外,它支持所有GraphQL客户端(例如Apollo)。

Now that you understand what GraphQL is, you can learn to use it in your Nodejs applications in place of REST.

现在您了解了GraphQL是什么,您可以学习在Nodejs应用程序中代替REST使用它。

创建一个新项目 (Creating a New Project)

Create a new folder called UsersAPI, open your terminal and navigate into the folder then run the following command:

创建一个名为UsersAPI的新文件夹,打开您的终端并导航到该文件夹​​,然后运行以下命令:

  • npm init

    npm初始化

Create a file named index.js inside your project folder:

在项目文件夹中创建一个名为index.js的文件:

  • touch index.js

    触摸index.js

That takes care of setting up your application.

这样就可以设置您的应用程序了。

安装所需的依赖项 (Installing Required Dependencies)

You’ll need to install graphql-yoga to help set up your GraphQL server and then mongoose for help with connecting to your Mongo database.

您需要安装graphql-yoga来帮助设置GraphQL服务器,然后安装mongoose来帮助您连接到Mongo数据库。

Inside your terminal run the following:

在终端内部运行以下命令:

  • npm install graphql-yoga mongoose

    npm安装graphql-瑜伽猫鼬

定义用户模型 (Defining User Model)

Models are responsible for creating and reading documents from the underlying MongoDB database. Here, we’ll create a User model for our GraphQL application.

模型负责从底层MongoDB数据库创建和读取文档。 在这里,我们将为我们的GraphQL应用程序创建一个用户模型。

Inside index.js type in the following lines of code:

index.js键入以下代码行:

const { GraphQLServer } = require('graphql-yoga')
const mongoose = require('mongoose');
mongoose.connect("mongodb://localhost:27017/UserApp");


const User= mongoose.model("User",{
    fullname: String,
    username: String,
    phone_number: String,
    city: String
});

We have successfully defined our User model and established a mongoose connection, it is time to get into GraphQL Schemas.

我们已经成功定义了我们的用户模型并建立了猫鼬连接,是时候进入GraphQL模式了。

定义GraphQL模式 (Defining a GraphQL Schema)

A GraphQL Schema describes the functionality available to the clients which connect to it. It is built using the Schema Definition Language.

GraphQL模式描述了连接到它的客户端可用的功能。 它是使用架构定义语言构建的。

Add these following lines of code to your index.js file:

将以下几行代码添加到index.js文件:

const typeDefs = `type Query {
    getUser(id: ID!): User
    getUsers: [User]
  }
  type User {
      id: ID!
      fullname: String!
      username: String!
      phone_number: String!
      city: String!
  }
  type Mutation {
      addUser(fullname: String!, username: String!, phone_number: String!, city: String!): User!,
      deleteUser(id: ID!): String
  }`

We have three types inside our Schema, let’s break them down.

我们的架构中有三种类型,让我们对其进行细分。

使用查询类型 (Using the Query Type)

A GraphQL query is for fetching data and compares to the GET verb in REST-based APIs. In order to define what queries are possible on a server, the Query type is used within the Schema Definition Language. The Query type is a root-level type which defines functionality for clients and acts as an entrypoint to other more specific types within the schema.

GraphQL查询用于获取数据,并与基于REST的API中的GET动词进行比较。 为了定义在服务器上可以进行哪些查询,在架构定义语言中使用了查询类型。 查询类型是根级别的类型,它定义了客户端的功能,并充当架构中其他更特定类型的入口点。

type Query {
    getUser(id: ID): User
    getUsers: [User]
}

In this Query type, we define two types of queries which are available on this GraphQL server: getUser: which returns a particular User object that matches the ID provided. getUsers: which returns a list of User objects.

在这种查询类型中,我们定义了在GraphQL服务器上可用的两种查询类型:getUser:返回与提供的ID匹配的特定User对象。 getUsers:返回用户对象列表。

If you are familiar with REST-based APIs, you would normally find these located on separate end-points, but GraphQL allows them to be queried at the same time and returned at once.

如果您熟悉基于REST的API,通常会发现它们位于单独的端点上,但是GraphQL允许同时查询它们并立即返回它们。

Note: Square brackets signifies that you expect an iterable object or an array in the JSON response. You will only be returning a single User object for getUser and an array for getUsers.

注意:方括号表示您希望JSON响应中包含可迭代的对象或数组。 您将只为getUser返回一个User对象,为getUsers返回一个数组。

使用用户类型 (Using the User Type)

User is a GraphQL Object Type, meaning it’s a type with some fields. The object type is the most common type used in a schema and represents a group of fields.

用户是GraphQL对象类型,这意味着它是具有某些字段的类型。 对象类型是模式中最常用的类型,代表一组字段。

type User {
    id: ID!
    fullname: String!
    username: String!
    phone_number: String!
    city: String!
}

id, fullname, username, phone_number and city are fields on the User type.

ID,全名,用户名,电话号码和城市是用户类型上的字段。

  • String is one of the built-in scalar types. It specifies the data type of a field.

    字符串是内置标量类型之一。 它指定字段的数据类型。

  • String means that the field is non-nullable. In the Schema Definition Language, we’ll represent those with an exclamation mark.

    字符串表示该字段不可为空。 在模式定义语言中,我们将用感叹号表示它们。

  • ID is a unique identifier, often used as the key for a cache.

    ID是唯一的标识符,通常用作缓存的键。

使用变异类型 (Using the Mutation Type)

Mutations are sent to the server to create, update or delete data similar to the PUT, POST, PATCH and DELETE verbs on RESTful APIs. Much like how the Query type defines the entry-points for data-fetching operations on a GraphQL server, the root-level Mutation type specifies the entry points for data-manipulation operations.

将变异发送到服务器以创建,更新或删除类似于RESTful API上的PUT,POST,PATCH和DELETE动词的数据。 类似于Query类型如何定义GraphQL服务器上的数据获取操作的入口点,根级Mutation类型指定数据操作的入口点。

type Mutation {
    addUser(fullname: String!, username: String!, phone_number: String!, city: String!): User!,
    deleteUser(id: ID!): String
}

This implements two mutations:

这实现了两个突变:

  • addUser: which accepts fullname, username, phone_number and city as arguments known as “input types” and the mutation will return the newly-created User object.

    addUser :接受全名,用户名,电话号码和城市作为参数,称为“输入类型”,并且该突变将返回新创建的User对象。

  • deleteUser: which accepts a valid User ID and returns a String message to tell if the delete operation was successful or not.

    deleteUser :它接受有效的用户ID并返回String消息以告知删除操作是否成功。

Let’s move on to writing Resolvers for our defined Schema.

让我们继续为定义的模式编写解析器。

添加解析器 (Adding Resolvers)

Resolvers are the actual functions to implement business logic on your data in a GraphQL API. Each query and mutation will have corresponding resolver functions to perform the logic.

解析器是在GraphQL API中对数据实现业务逻辑的实际功能。 每个查询和变异都将具有相应的解析器功能来执行逻辑。

Add the following lines of code to your index.js file:

将以下代码行添加到index.js文件:

const resolvers = {
    Query: {
      getUsers: ()=> User.find(),
      getUser: async (_,{id}) => {
        var result = await User.findById(id);
        return result;
    }
},
    Mutation: {
        addUser: async (_, { fullname, username, phone_number, city }) => {
            const user = new User({fullname, username, phone_number, city});
            await user.save();
            return user;
        },
        deleteUser: async (_, {id}) => {
            await User.findByIdAndRemove(id);
            return "User deleted";
        }
    }
  }

设置您的GraphQL服务器 (Setting up your GraphQL Server)

After building your Schema and Resolvers, it’s time to set up your server to handle requests. graphql-yoga is the easiest way to get a GraphQL server up and running, it is a full-featured GraphQL Server with focus on user-friendly configuration, performance & great developer experience.

构建了架构和解析器之后,是时候设置服务器来处理请求了。 graphql-yoga是启动和运行GraphQL服务器的最简单方法,它是功能齐全的GraphQL服务器,专注于用户友好的配置,性能和出色的开发人员经验。

Inside index.js, add the following lines of code to setup your server:

index.js ,添加以下代码行以设置服务器:

const server = new GraphQLServer({ typeDefs, resolvers })
mongoose.connection.once("open", function(){
    server.start(() => console.log('Server is running on localhost:4000'))
});

With that, you’ve built a functional GraphQL server from scratch, it’s time to make some requests. Open your terminal and run the following command to start the server:

这样,您便可以从头开始构建功能强大的GraphQL服务器,是时候提出一些要求了。 打开终端并运行以下命令以启动服务器:

node index.js

Open your web browser and navigate to http://localhost:4000/ a nice GraphQL playground will come up on your browser where you can run sample queries.

打开您的Web浏览器并导航到http:// localhost:4000 / ,浏览器上会出现一个不错的GraphQL游乐场,您可以在其中运行示例查询。

添加新用户 (Adding a New User)

Run the following query inside the playground to add a new user:

在操场上运行以下查询以添加新用户:

mutation{
  addUser(fullname:"Ibe Ogele",username:"ibesoft",phone_number:"2348102331921",city:"Enugu"){
    id
    fullname
    username
    phone_number
    city
  }
}

获取用户信息 (Fetching User information)

Run the query below to fetch information for a particular user:

运行以下查询以获取特定用户的信息:

query{
  getUser(id:"user_id"){
    id
    fullname
    username
    phone_number
    city
  }
}

To get all Users run:

要使所有用户运行:

query{
  getUsers{
    id
    fullname
    username
    phone_number
    city
  }
}

删除用户 (Deleting a User)

You can delete a particular User by running the query below:

您可以通过运行以下查询来删除特定用户:

mutation{
  deleteUser(id: "user_id")
}

结论 (Conclusion)

With GraphQL you send a query to your API and get exactly what you need, nothing more and nothing less. GraphQL queries always return predictable results.

使用GraphQL,您可以将查询发送到您的API并获得所需的信息,仅此而已。 GraphQL查询始终返回可预测的结果。

翻译自: https://www.digitalocean.com/community/tutorials/how-to-build-a-graphql-server-in-node-js-using-graphql-yoga-and-mongodb

yoga720 -12

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值