This content originally appeared on JavaScript January and was authored by Emily Freeman
I’m incredibly grateful to Eve Porcello for this amazing post. Eve is the author of Learning GraphQL and Learning React. You can access her training courses on her website.
It's January! It's a time to learn new things, to blaze new trails, to maybe start using some GraphQL?
If you haven't worked with GraphQL before, the short description is that it is a query language for your API. The query language gives us a way to ask questions of our data. When I send a query, I expect to see data returned in the same shape of the query.
For example, I could write a query for a total number of users that are part of our data source:
query
When I send this query to a GraphQL server, I will receive the data back as JSON:
{ "data": { "totalUsers": 101 } }
Notice that the fields we request can be found in the JSON response under the data
key. You may be thinking "Where does that data come from?" The answer to that question can be summarized by the most vague computer science answer ever: "It depends!" More specifically, when we build a GraphQL server, we can build it to return data from anywhere: from databases to files to REST APIs.
So how do we build a GraphQL server? "It depends!" You can use a multitude of different languages to build a GraphQL server. If you like Python, use Python! If you like C++, use C++! Since this is JavaScript January, we'll be using Node.js. Let's build a simple GraphQL server using Apollo Server, one of the many server libraries that exist for GraphQL.
We'll start by initializing a Node project and installing the dependencies with npm. In your Terminal or Command Prompt, you can run the following commands:
mkdir taco-app cd taco-app npm init -y npm install graphql apollo-server
Then create a file called index.js
, and add the following:
const { ApolloServer } = require("apollo-server"); const server = new ApolloServer({}); server.listen().then(({ url }) => console.log(`Server running on port ${url}`));
You'll require ApolloServer
, your GraphQL server library of choice, from the apollo-server
package. Then create a new instance of the ApolloServer
.
Any new instance of Apollo Server must take in typeDefs
, your GraphQL schema. A schema describes all of the types and queries that will be available on your API. You also will define resolvers
, the functions that are used to get the data to fulfill the requirements of the schema (aka returns the data for the schema).
const server = new ApolloServer({ typeDefs, resolvers });
You'll start with the schema. You need to grab the direct url for a taco recipe. All of the queries available on a GraphQL API are found in the Query
type:
const typeDefs = ` type Query { recipeURL: String } `;
When you send a query for the recipeURL
, it should return a value of type String
.
Next, you create a resolver for this query. The resolver will go get the data you need from the API by using a simple fetch
call. Start by installing node-fetch
with npm:
npm install node-fetch
Add this to your list of require statements at the top of the file too:
const fetch = require("node-fetch");
Then create the resolvers object. These functions will return the data we need for the recipeURL
:
const resolvers = { Query: { recipeURL: () => } };
Think about what you need the recipeURL
resolver to do. It needs to make a fetch
call to the Taco API to get a random recipe. Then it needs to transform the data response and just grab the URL out of the response, not all of the extra fields.
Resolvers can be asynchronous, so you use an async function for the recipeURL
. Within this function, you fetch from the API and log the result to the console:
const resolvers = { Query: { recipeURL: async () => { let taco = await fetch( "http://taco-randomizer.herokuapp.com/random/" ).then(res => res.json()); console.log(taco); } } };
Now you run node index
in the Terminal to run this file. When you open up localhost:4000
in your browser, you will see the GraphQL Playground, which will allow you to send GraphQL queries directly in the browser. On the left side, you'll write the query:
query { recipeURL }
Then click the Play
button in the center. The data returned on the right side is the following:
{ "data": { "recipeURL": null } }
This is ok, because you're really trying to take a look at the full object logged to the console or Terminal. If you open the Terminal, you'll see a blob of data. Remember that this is a random taco, so your result will differ slightly:
{ base_layer: { url: "https://raw.github.com/sinker/tacofancy/master/base_layers/spaghetti_squash.md", } }
Now that you know what the response object looks like you can drill down into it to grab just the URL.
You change the resolver to return just the URL string:
const resolvers = { Query: { recipeURL: async () => { let taco = await fetch( "http://taco-randomizer.herokuapp.com/random/" ).then(res => res.json()); return taco.base_layer.url; } } };
Now you can stop and restart the index file: node index
and click Play to run the query again in the Playground:
query { recipeURL }
Now you should receive the correct response:
{ "data": { "recipeURL": "https://raw.github.com/sinker/tacofancy/master/base_layers/bellpepper.md" } }
Copy and paste the recipeURL
into the browser, and you have your recipe. You did it. You built a GraphQL server! Now you can make dinner!
This is a quick introduction to GraphQL but hopefully it got your gears turning on how you could use a GraphQL server to pull together your various data sources in one location. For more information about getting started with GraphQL, check out the links below or feel free to reach out to me on Twitter with any questions!
This content originally appeared on JavaScript January and was authored by Emily Freeman
Emily Freeman | Sciencx (2020-01-17T15:50:00+00:00) Building a GraphQL Server with JavaScript. Retrieved from https://www.scien.cx/2020/01/17/building-a-graphql-server-with-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.