GraphQL 漸進學習 06-graphql-採用-mockjs-mock數據

GraphQL 漸進學習 06-graphql-採用-mockjs-mock數據

目標

  • 開啓 mock數據 模式
  • 採用 mock.js 組件進行數據模擬
  • 模擬數據配置html

    • 對象
    • 接口
    • 自定義類型
    • 聯合
    • 查詢

代碼

步驟

1. 安裝 mock.js 依賴包

npm -S install mockjs

3. import 所需包對象

import {makeExecutableSchema, addMockFunctionsToSchema, MockList} from 'graphql-tools'
import {graphql, GraphQLScalarType} from 'graphql'
import Mock from 'mockjs'
const Random = Mock.Random
  • addMockFunctionsToSchema 合成模擬函數
  • MockList 指定模擬數據條數
  • Mock 模擬數據生成對象

3. 編寫 typeDefs

const typeDefs = `
  scalar Date

  type User {
    id: Int
    name: String
    posts(limit: Int): [Post]
  }

  type Post {
    id: Int
    title: String
    views: Int
    author: User
  }

  interface Message {
    content: String
  }
  type Notice implements Message {
    content: String
    noticeTime: Date
  }
  type Remind implements Message {
    content: String
    endTime: Date
  }

  type Query {
    aString: String
    aBoolean: Boolean
    anInt: Int
    my: [User]
    author(id: Int): User
    topPosts(limit: Int): [Post]
    notices: [Notice]
  }

  type Mutation {
    addUser: User
  }
`
  • 定義中有 自定對象 接口 類型 查詢 更新 ,複合廣泛狀況

4. 編寫 typeResolvers

const typeResolvers = {
  Message: {
    __resolveType(data) {
      return data.typename // typename property must be set by your mock functions
    }
  },
  Date: new GraphQLScalarType({
    name: 'Date',
    description: 'Date custom scalar type',
    parseValue(value) {
      return new Date(value) // value from the client
    },
    serialize(value) {
      // return new Date(value).getTime()
      return new Date(value) // value sent to the client
    },
    parseLiteral(ast) {
      if (ast.kind === Kind.INT) {
        return parseInt(ast.value, 10) // ast value is always in string format
      }
      return null
    }
  })
}

接口 聯合 自定義類型 須要編寫 typeResolvers 對象 git

5. 合併 Schema

const schema = makeExecutableSchema({
  typeDefs,
  typeResolvers,
  resolverValidationOptions: {
    requireResolversForResolveType: false
  }})

6. 編寫模擬數據

const min = 100
const max = 99999
const mocks = {
  Int: () => Random.natural(min, max),
  Float: () => Random.float(min, max),
  String: () => Random.ctitle(10, 5),
  Date: () => Random.time(),
  User: () => (
    {
      id: Random.natural(min, max),
      name: Random.cname(),
      posts: () => new MockList([6, 12]),
    }
  ),
}
  • 能夠發現都是對類型進行定義
  • MockList([6, 12]) 表示模擬 6 ~ 12 條數據
  • mock.js 語法請移步 Mock.js/Random

7. 開啓模擬方式

addMockFunctionsToSchema({schema, mocks, preserveResolvers: true})
  • 沒有看錯就是一行代碼

測試

1. 請求 addUser 方法

# 請求
mutation {
  addUser {
    id
    name
  }
}

# 輸出
{
  "data": {
    "addUser": {
      "id": 61700,
      "name": "蔡傑"
    }
  }
}

2. 請求 me 查詢

# 請求
{
  my {
    id
    name
    posts {
      id
      title
    }
  }
}

# 輸出
{
  "data": {
    "my": [
      {
        "id": 10861,
        "name": "林霞",
        "posts": [
          {
            "id": 5295,
            "title": "老學通階本照機世"
          },
          {
            "id": 74760,
            "title": "勞報辦劃說團可向代"
          },
          {
            "id": 96701,
            "title": "那管己單等半作狀基"
          },
          {
            "id": 57025,
            "title": "值前真水員般兩據和"
          },
          {
            "id": 15801,
            "title": "克文實驗很即手邊物"
          },
          {
            "id": 80493,
            "title": "強統消權紅方"
          }
        ]
      },
      {
        "id": 22464,
        "name": "蕭超",
        "posts": [
          {
            "id": 45890,
            "title": "子爭安能軍"
          },
          {
            "id": 6975,
            "title": "年階高戰思與稱統爭"
          },
          {
            "id": 52466,
            "title": "長需準之確"
          },
          {
            "id": 35372,
            "title": "手備造方專樣反則"
          },
          {
            "id": 98486,
            "title": "種觀點聽進段周"
          },
          {
            "id": 35529,
            "title": "名據級個況交各"
          },
          {
            "id": 40534,
            "title": "要也義理平示家治"
          },
          {
            "id": 57121,
            "title": "觀如王部被關約法"
          },
          {
            "id": 29170,
            "title": "求經風斷治往市程"
          },
          {
            "id": 36344,
            "title": "器隊熱農時斯心"
          }
        ]
      }
    ]
  }
}

參考

相關文章
相關標籤/搜索