#
Tips and gotchas
#
Tips
#
Modify the length of lists
Any list type (ie. [String]
) will by default return a list of two items.
You can modify this default behavior via mocks
. Let's assume a field Query.books
returns a type [Book]
:
import { utils } from '@datacamp/poser';
const mocks = {
Query: {
books: () => utils.mockList(10), // return 10 items for the `book` query
}
}
#
Fix getById queries
By default, queries such as getSomethingById
, where user provides an id, won't return the proper instance.
This happens because without a custom resolver, a random instance will be returned.
We can fix this easily by providing a custom resolver:
const resolvers = (store) => {
return {
Query: {
getSomethigById: (_, { id }) => {
return store.get('Something', id);
}
}
}
}
#
Mocking pagination
Pagination won't work out of the box but can be easily implemented using mocks and resolvers.
Let's assume the following schema for example:
type Query {
books(limit: Int, offset: Int): [Book]
}
type Book {
id: ID
title: String
}
By default, Query.books
will return only 2 Book
. To make this query more realistic, the first step is to pretend we have a lot of books. For this we'll use a mock, so Query.books
returns the full list of books, without any pagination:
import { utils } from '@datacamp/poser';
const mocks = {
Query: {
books: () => utils.mockList(100)
}
}
Query.books
will now return 100 random books. Let's implement pagination over this list:
const resolvers = {
Query: {
books: (src, args = {}) => {
// grab the full list of books
const $books = store.get('Query', 'ROOT', 'books') as Ref[];
// apply some defaults to arguments
const limit = args.limit || $books.length;
const offset = args.offset || 0;
// return only a slice
return $books.slice(offset, offset + limit);
}
}
}
You could even apply filtering:
return $books
.filter($book => {
return store.get($book, 'title').includes('something')
})
.slice(offset, offset + limit);
#
Relay-style pagination
To mock relay-style pagination, use the relayStylePaginationResolver
helper:
import { helpers } from '@datacamp/poser';
const resolvers = (store) => {
Query: {
booksRelayStyle: helpers.graphql.relayStylePaginationResolver(store)
}
}
#
Gotchas
#
Always return a Ref
from resolvers
Unless a resolver returns a Scalar type, all resolvers should return a Ref
from the store.
If a resolver doesn't return a Ref
, then mocks can't easily make use of source
(the first argument of resolver functions). It's easier for source
to always be a Ref
.