Graphql introduction

GraphQL is a query language for apis, a server-side runtime that executes queries using a type based system (defined by your data).

The official website

  • GraphQL website
  • Apollo’s official website

Graphql Node Egg server access from zero to one

First, build egg project

You already have an Egg project, so you can go straight to step 2 and access GraphQL. No project is created and can be set up quickly

Direct scaffolding is recommended for quick project generation (NPM >=6.1.0) :

$ mkdir egg-example && cd egg-example 
$ npm init egg --type=simple 
$ npm i 
Copy the code

Launch project:

$ npm run dev 
$ open http://localhost:7001
Copy the code

Access graphQL

Github.com/eggjs/egg-g…

The installation

npm i --save egg-graphql
Copy the code

Open the plug-in

// config/plugin.js
exports.graphql = {
  enable: true.package: 'egg-graphql'};Copy the code

configuration

// config/config.${env}.js

// ⚠️ Add middleware to intercept requests (required)
exports.middleware = [ 'graphql' ];

// Configure (optional)
exports.graphql = {
  // Visualize interface routing
  router: '/graphql'.// Whether to load to app, enabled by default
  app: true.// Whether to load it to the agent
  agent: false.// Whether to load the developer tool graphiQL. It is enabled by default. The same route as the Router field. Use a browser to open the visibility.
  graphiql: true.// Whether to set the default Query and Mutation, off by default
  defaultEmptySchema:true.// graphQL interceptor before routing
  onPreGraphQL: function* (ctx) {},
  // The developer tool graphiQL interceptor is recommended to do permission operations (such as only developers use)
  onPreGraphiQL: function* (ctx) {},
  / / Apollo server passthrough parameters, refer to [documents] (https://www.apollographql.com/docs/apollo-server/api/apollo-server/#parameters)
  apolloServerOptions: {
    rootValue,
    formatError,
    formatResponse,
    mocks,
    schemaDirectives,
    introspection,
    playground,
    debug,
    validationRules,
    tracing,
    cacheControl,
    subscriptions,
    engine,
    persistedQueries,
    cors,
  }
};
Copy the code

Use the Egg directory structure of GraphQL

├ ─ ─ app │ ├ ─ ─ controller │ │ └ ─ ─ home. Js │ ├ ─ ─ graphql │ │ ├ ─ ─ img │ │ │ ├ ─ ─ the js// Handle fetch logic (optional)│ │ ├─ resolver.js// Handle queries or changes ()│ ├ ─ ├ ─ garbage//1. Describe the data, indicating which fields are in the SCHEMA data model│ ├── ├─ ├─ ├─ ├─ ├─ ├─ ├─ download.txt ├─ ├─ download.txt ├─ download.txtCopy the code
  • Schema.graphql (must) (define – data) describes the data, indicating which fields are in a data model.

  • Resolver.js (must) (processing – data) handles the user’s query. For the exposed query interface, call the corresponding connector to fetch the number.

  • Connector.js (optional) (fetch logic) is responsible for fetching data. The plug-in can fetch data, and you can also call the Egg service directly. Connector is mounted to the context and can be used directly with ctx.connector.

To define the schema

// schema.graphqlType Query {imglist: [ImgData]
}

type ImgData {
  id: String
  name: String!
  remark: String
  deletedType Mutation {addImgList(name:String.remark: String.deleted: Int): ImgData
}

input addImgList {
    name: String!
    remark: String
    deleted: Int
}

Copy the code

In the schema. graphQL file, you need to define Query and Mutation

Define the resolver

// resolve.js

const list = [
  {
    id: 1.name: 'aaa'.remark: 'note'.deleted: 0}, {id: 2.name: 'bbb'.remark: 'note'.deleted: 0,},];module.exports = {
  / / query
  Query: {
    imglist: () = > {
      returnlist; }},/ / change
  Mutation: {
    addImgList(root, params, ctx) {
    // ctx.connector
    // console.log('root', root);
    // console.log('ctx', ctx);
      params.id = list.length++;
      list.push(params);
      returnparams; ,}}};Copy the code

Define Query and Mutation,

run

npm run dev
Copy the code
/ / http://127.0.0.1:7001/graphql

// Query statement
{
  imglist {
    id
    name
  }
}
Copy the code


// Change the statement
mutation {
  addImgList(name: "ccc", remark: "remark"){
    name
    remark
    id
  }
}

Copy the code

This completes the access of the Graphql server. Then you can access the client

Graphql server with Sequelize 0 to 1

Graphql Vue client access zero to one

  • vue-apollo
  • Apollo Client (vue-Apollo plug-in underlying)

The installation

// Quick installation
vue add apollo

// Install manually
Copy the code

Installation problems using vue Add Apolle installation problems

1. Fault location: The suspected Node version, NPM version, or VUE version is too old

Solution: View the version (node -v; npm -v; Vue-version) to upgrade the version

Node and NPM: nodejs.org/en/, download the update. Updating node also updates NPM

2. When using @ali dependencies, vue add Apolle will reinstall dependencies

Solution:

Delete the downloaded node_modules folder,

Delete the relevant @ali package from package.json folder

Then execute vue Add Apolle

  1. The project uses

“Node – sass” : “^ 4.9.0”,

“Sass – loader”, “^ 7.1.0”,

configuration

// src/vue-apollo.js 

// Change the server interface to the actual path
const httpEndpoint = process.env.VUE_APP_GRAPHQL_HTTP || 'http://127.0.0.1:7001/graphql'

// Close WS and do not use subscriptions
wsEndpoint: null.Copy the code

Use (query and change)

The query

Two ways:

  • Common query
  • Intelligent query, official documents
<template>
    <div> {{imglist}} </div> 
</template> 

import gql from 'graphql-tag' 
export default { 
    //⚠️ Note: Imglist names must be the same
    apollo: { 
        imglist: gql`query{ imglist { id name } }`}}Copy the code
change
data(){
 return {
  name: 'gqlname'.remark: 'note'}}// Execute the mutate event
this.$apollo
  .mutate({
    // GQL needs to define individual values
    mutation: gql`mutation($name:String! , $remark:String, $id:String, $deleted:Int) { addImgList(name: $name, pid: $pid, id: $id, deleted:$deleted) { name remark deleted } }`.variables: {
      data: {
          name: this.name, // You can use this
          remark: this.remark,
          deleted: 0
      }
    }
  })
  .then((data) = > {
    console.log('success', data)
  })
  .catch((error) = > {
    this.$message.error(error.message)
  })

Copy the code

Graphql with sequelize zero to one

To be updated

reference

Website graphql. Cn

Simple tutorial www.howtographql.com/

An egg – graphql github.com/eggjs/egg-g plugin…

Apollo-server is a Node extension based on expressjs github.com/apollograph…

Tutorial www.howtographql.com/graphql-js/…

Apollo-client front-end add-on github.com/apollograph…

Tutorial React + Apollo – client www.howtographql.com/react-apoll…