mock數據
模式mock.js
組件進行數據模擬模擬數據配置html
mock.js
依賴包npm -S install mockjs
import
所需包對象import {makeExecutableSchema, addMockFunctionsToSchema, MockList} from 'graphql-tools' import {graphql, GraphQLScalarType} from 'graphql' import Mock from 'mockjs' const Random = Mock.Random
addMockFunctionsToSchema
合成模擬函數MockList
指定模擬數據條數Mock
模擬數據生成對象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 } `
自定對象
接口
類型
查詢
更新
,複合廣泛狀況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
Schema
const schema = makeExecutableSchema({ typeDefs, typeResolvers, resolverValidationOptions: { requireResolversForResolveType: false }})
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 addMockFunctionsToSchema({schema, mocks, preserveResolvers: true})
addUser
方法# 請求 mutation { addUser { id name } } # 輸出 { "data": { "addUser": { "id": 61700, "name": "蔡傑" } } }
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": "器隊熱農時斯心" } ] } ] } }