Let’s create the allMoves
query so we can retrieve all the available moves from our backend. We will do this in a paginated way like we implemented allPokemon
.
We will add the allMoves
query to be able to fetch a move listing from our front-ends.
We will use 2 optional arguments, page
and itemsPerPage
for paging functionality.
# allMoves query
allMoves(page: Int, itemsPerPage: Int): MovePage
The return type
will be of MovePage
The MovePage
type has not been defined, and it will resemble the existing type PokemonPage
type MovePage {
items: [Move]!
paging: Paging!
}
items
is an array of Move
. paging
has Paging fields.
I will add this new MovePage
type in a new file /g/entities/MovePage.gql
.
It really doesn’t matter if it is in a new file or along side other type definitions in an existing file.
Because or moves.json
file is not an array, but a big map of moves, we will transform it a little.
Here is the resolver:
/** /g/resolvers/Query/allMoves.js **/
let moves = require('./../../../data/moves.json');
var resolver = (obj, args, ctx, info) => {
let page = args.page || 1;
let itemsPerPage = args.itemsPerPage || 10;
// transform the move data into an array
let moveAry = [];
for (let moveId in moves) {
moveAry.push(moves[moveId]);
}
// also sort alpha by Name
moveAry.sort((a, b) => {
if (a.Name < b.Name) return -1;
return 1;
});
let items = [];
let paging = {
total: moveAry.length,
totalPages: Math.ceil(moveAry.length / itemsPerPage),
page,
itemsPerPage
};
let startIndex = (page - 1) * itemsPerPage;
let endIndex = startIndex + itemsPerPage;
moveAry.forEach((move, idx) => {
if (idx >= startIndex && idx < endIndex) {
items.push(move);
}
});
return {
items,
paging
};
};
module.exports = resolver;
Let’s deploy our new query:
> npm run deploy-gql
6 moves in total, :thumbsup:
Good job if you have a working backend at this point!
I have pushed changes from this post into the query-allmoves branch.
For extra credit:
Make a query
that returns all pokemon of type, in a paginated form
pokemonOfType(type: String!): PokemonPage
Make a query
that returns all moves of type, in a paginated form
moveOfType(type: String!): MovePage
Advanced graphql
powers…