In the front-end projects using GraphQL (hereinafter referred to as GQL), it is often necessary to wait for the background students to define the Schema and set up the Playground before joint adjustment. If the background students are blocked, the front end can only passively wait. It would be nice if you could have a mock scheme for GQL projects like REST. After a series of practices, I chose the mocker-API plus Apollo scheme to achieve.

mocker-api

Mocker-api is an interface mock tool based on node implementation (formerly webpack-api-mocker, dependent on webpack-dev-server, can now run independently). Since most of our projects are integrated with WebPack, this is a brief introduction to its use in conjunction with WebPack.

In the devServer configuration item for WebPack, introduce the following:

devServer: {
  before (app) {
    require('mocker-api')(app, resolve('./mock/index.js'))}}Copy the code

This completes the integration of WebPack and Mocker-API. /mock/index.js /mock/index.js

// /mock/index.js

module.exports = {
  'POST /api': (req, res) = > {
    return res.send('Hello world')}}Copy the code

In this case, open webpack-dev-server, and use the POST mode to request/API in the page. You can get the response with the content of Hello world.

Apollo

Apollo is a complete set of GraphQL implementation solutions, supporting multiple languages server and client, here we mainly use Apollo-server to build front-end GQL mock service.

Create a new/GQL directory under /mock and add the /resolvers directory, the types directory and the index.js entry file. Let’s use an example of “querying book information” to illustrate how this GQL mock service works.

Create books.js under /types:

const { gql } = require('apollo-server')

module.exports = gql'""" Book """ type Book {id: id! Title: String "author" author: String} type Query {books: [Book]} type Mutation {addBook(title: String, author: String): [Book] } `
Copy the code

Next, create books.js under the /resolvers directory:

const books = [
  {
    id: parseInt(Math.random() * 10000),
    title: 'Harry Potter and the Chamber of Secrets'.author: 'J.K. Rowling'
  },
  {
    id: parseInt(Math.random() * 10000),
    title: 'Jurassic Park'.author: 'Michael Crichton'}]module.exports = {
  query: {
    books: (a)= > books,
  },
  mutation: {
    addBook: (root, book) = > {
      book.id = parseInt(Math.random() * 10000)
      books.push(book)
      return books
    }
  }
}
Copy the code

Finally, import the above two files in the entry file index.js:

const { ApolloServer } = require('apollo-server')

const typeDefs = [
  require('./types/Books')]const resolvers = {
  Query: {
    ...require('./resolvers/Books').query
  },
  Mutation: {
    ...require('./resolvers/Books').mutation
  }
}

const server = new ApolloServer({ typeDefs, resolvers })

server.listen().then(({ url }) = > {
  console.log('🚀 Apollo Server ready at${url}`);
})
Copy the code

Run node./mock/ GQL /index.js to open Playground at localhost:4000 for debugging.

Use mocker-API to forward requests to the local Playground

In real business, THE GQL interface is often encapsulated in a form such as/API/GQL, which can be called by clients along with other REST interfaces. In order for the/API/GQL interface to be forwarded to Playground at localhost:4000, we can use mocker-API for forwarding.

Alter /mock/index.js to add a/API/GQL address:

const axios = require('axios')

module.exports = {
  'POST /api': (req, res) = > {
    return res.send('Hello world')},'POST /api/gql': async (req, res) => {
    const reqBody = req.body
    const { data: result } = await axios({
      url: 'http://localhost:4000'.method: 'POST'.data: reqBody
    }).catch(e= > e)
    return res.send({
      data: result.data
    })
  }
}
Copy the code

So here I’m using AXIos to make a request to Apollo-server.

/ API/GQL = / API/GQL = / API/GQL

      fetch('/api/gql', {
        method: 'POST'.headers: {
          'Accept': 'application/json'.'Content-Type': 'application/json'
        },
        body: JSON.stringify({ query: 'query GetBooks { books { title }}' })
      })
        .then(res= > res.json())
        .then(result= > console.log(result))
Copy the code

Because mocker-API supports hot Reload, we can comment out ‘POST/API/GQL ‘in /mock/index.js when we no longer need mock data without restarting the dev server.

At this point, the front-end mock scheme in the GraphQL project is complete.