-
Notifications
You must be signed in to change notification settings - Fork 0
/
schema.ts
86 lines (70 loc) · 2.42 KB
/
schema.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import { faker } from '@faker-js/faker'
import { addMocksToSchema, createMockStore, IMockStore, Ref } from '@graphql-tools/mock'
import { makeExecutableSchema } from '@graphql-tools/schema'
const schema = makeExecutableSchema({
typeDefs: `
type Credential {
id: ID!
createdAt: String!
username: String!
}
type Query {
getCredentials: [Credential]
}
type Mutation {
createCredential: Credential
deleteCredential(credentialId: ID!): [Credential]
}
schema {
query: Query
mutation: Mutation
}
`
})
const store = createMockStore({ schema })
const generateCredential = () => ({
id: faker.datatype.uuid(),
createdAt: faker.date.past().toString(),
username: faker.internet.userName()
})
// Sets the initial return value of `getCredential`
// to an array of 3 uniquely generated credential objects
store.set('Query', 'ROOT', 'getCredentials', Array.from({ length: 3 }, generateCredential))
const mocks = {
Credential: generateCredential,
Query: () => ({
// store.get returns an array of references to the actual entities in the store
// in the form of an object with a `key` and a `typeName` properties
getCredentials: () => store.get('Query', 'ROOT', 'getCredentials') as Ref[]
}),
Mutation: () => ({
createCredential: () => {},
deleteCredential: () => {}
})
}
const resolvers = (store: IMockStore) => ({
Mutation: {
createCredential: () => {
const newCredential = generateCredential()
const credentials = store.get('Query', 'ROOT', 'getCredentials') as Ref[]
store.set('Query', 'ROOT', 'getCredentials', [...credentials, newCredential])
return newCredential
},
// @ts-ignore
deleteCredential: (_, { credentialId }) => {
const credentials = store.get('Query', 'ROOT', 'getCredentials') as Ref[]
const hasCredentialToDelete = store.has('Credential', credentialId)
if (!hasCredentialToDelete) {
throw new Error(`Couldn't find credential with id ${credentialId}`)
}
// Here, we use the reference from the store.get to find the actual item
// to be deleted from the Credentials list
store.set('Query', 'ROOT', 'getCredentials', credentials.filter(
ref => store.get(ref, 'id') !== credentialId
))
return credentials
}
}
})
const schemaWithMocks = addMocksToSchema({ schema, mocks, resolvers })
export default schemaWithMocks