返回

用Node.js和Vue构建完整的GraphQL应用

前端

Node.js服务端搭建

1. 安装Node.js和npm

首先,请确保您已安装Node.js和npm。您可以通过以下命令进行安装:

$ curl -sL https://deb.nodesource.com/setup_19.x | sudo -E bash -
$ sudo apt-get install -y nodejs

2. 安装Egg.js框架

接下来,我们将使用Egg.js框架来搭建Node.js服务端。Egg.js是一个高效、灵活且易用的Node.js框架,非常适合构建RESTful API。

$ npm install egg-init -g
$ egg-init my-egg-app
$ cd my-egg-app
$ npm install

3. 创建GraphQL控制器

在Egg.js中,控制器是处理请求和返回响应的类。我们要创建一个GraphQL控制器来处理GraphQL请求。

$ touch app/controller/graphql.js

app/controller/graphql.js文件中,添加以下代码:

'use strict';

const Controller = require('egg').Controller;

class GraphqlController extends Controller {
  async index() {
    const { ctx } = this;
    const query = ctx.request.body.query;
    const variables = ctx.request.body.variables;
    const result = await ctx.service.graphql.query(query, variables);
    ctx.body = result;
  }
}

module.exports = GraphqlController;

4. 创建GraphQL服务

在Egg.js中,服务是提供特定功能的模块。我们要创建一个GraphQL服务来处理GraphQL查询和变异。

$ touch app/service/graphql.js

app/service/graphql.js文件中,添加以下代码:

'use strict';

const Service = require('egg').Service;

class GraphqlService extends Service {
  async query(query, variables) {
    const { app } = this;
    return await app.gql.query({ query, variables });
  }
}

module.exports = GraphqlService;

5. 配置Egg.js

config/config.default.js文件中,添加以下配置:

module.exports = {
  // ...其他配置
  graphql: {
    router: '/graphql',
    graphiql: true,
  },
};

6. 启动Egg.js服务端

现在,您可以通过以下命令启动Egg.js服务端:

$ npm start

Vue客户端接入

1. 安装Vue.js和Vue CLI

首先,请确保您已安装Vue.js和Vue CLI。您可以通过以下命令进行安装:

$ npm install -g @vue/cli
$ vue create my-vue-app

2. 安装Apollo Client

接下来,我们将使用Apollo Client来连接GraphQL服务端。Apollo Client是一个流行的GraphQL客户端库,可以帮助您轻松地发送GraphQL查询和变异。

$ npm install apollo-boost vue-apollo

3. 配置Vue.js

src/main.js文件中,添加以下代码:

import Vue from 'vue';
import VueApollo from 'vue-apollo';
import { ApolloClient, InMemoryCache } from 'apollo-boost';

// 创建Apollo客户端
const client = new ApolloClient({
  uri: 'http://localhost:7001/graphql',
  cache: new InMemoryCache(),
});

// 将Apollo客户端集成到Vue实例中
Vue.use(VueApollo);

// 创建Vue Apollo提供程序
const apolloProvider = new VueApollo({
  defaultClient: client,
});

// 创建Vue实例
new Vue({
  apolloProvider,
  // ...其他配置
}).$mount('#app');

4. 发送GraphQL查询

现在,您可以在Vue组件中发送GraphQL查询了。例如,在src/components/MyComponent.vue文件中,添加以下代码:

<template>
  <div>
    <h1>{{ data.name }}</h1>
  </div>
</template>

<script>
import gql from 'graphql-tag';

export default {
  data() {
    return {
      data: null,
    };
  },
  mounted() {
    // 发送GraphQL查询
    this.$apollo.query({
      query: gql`
        query {
          user(id: 1) {
            name
          }
        }
      `,
    }).then(({ data }) => {
      this.data = data;
    });
  },
};
</script>

结语

现在,您已经构建了一个完整的GraphQL应用,包括Node.js和Vue部分。您可以使用这个应用来构建各种各样的项目,如博客、电子商务网站、社交网络等。