2020-04-28
|~2 min read
|386 words
Imagine the following GraphQL schema for retrieving data about dogs:
type Dog {
name: String!
breed: String
}
type Mutation {
createDog(name: String!, breed: String): Dog
}
type Query {
dogs: [Dog]!
}
Highlights:
But now let’s imagine that we want to test this quickly. So quickly that we can’t be bothered to connect the resolvers to the data layer itself.
How could we do that? We can use the local memory of our server (i.e. our computer if we’re developing locally).
Let’s see how.
First, let’s handle creating a new dog and making sure that it’s available for querying.
const Mutations = {
createDog: function (parent, args, ctx, info) {
global.dogs = global.dogs || [] // attaching our dogs array to the global object
const dog = { name: args.name, breed: args.breed }
global.dogs.push(dog) // this will later be replaced by our data layer, i.e. the insert function for our database
return dog
},
}
module.exports = Mutations
Instead of saving the new dog that we’re creating to the database, we’ve pushed it into an array of dogs stored on our global object.
Then when we’re fetching the data (with our Query), we look to the global object instead of the database:
const Query = {
dogs: function (parent, args, ctx, info) {
return global.dogs || [] // in the future, this will be replaced with interfacing with our data layer
},
}
module.exports = Query
At this point, you should have the beginnings of a fully functional GraphQL server - though it’s not connected to a data layer.
Here’s a CodeSandbox demonstrating the point:
Some notes on how to use the CSB:
yarn dev
https://xxxx-4000.sse.codesandbox.io)
And just like that, we’ve stood up a GraphQL server using GraphQL Yoga and are writing queries without a data layer.
Pretty nifty if all you need is some rapid prototyping!
Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!