SS

Meshing GraphQL

SS

Siddharth Sharma / October 13, 2020

7 min read

A few months ago I made a blog post on how GraphQL was changing the game for the Web. I highlighted some GraphQL terms and lingo. It was a good intro to GraphQL and I recommend checking it out. However, I honestly believe the best way to learn is to build. Seriously, if you don't know how to do something, literally try to do it, and with the way the modern internet works right now, you'll figure it out.

Graphqlifying Stuff#

A while ago I had planned on making an application call GraphQlify which aimed to take popular services and serve as a GraphQL wrapper. It's a good idea, and a great way to allow people new to GraphQL to feel comfortable of using popular services they already know how to use and making a GraphQL API out of it. While cool, there is no possible way for me to convert every single REST API in the world to GraphQL. Sorry guys contrary to popular belief, I do have some semblance of life, lol.

BUT recently, as in literally an hour ago, I was researching technologies to expand on Airport, one of the recent projects I've been working on. Our backend needs an overhaul to handle a lot of the new features we're planning. To do that we're heavily considering using GraphQL with Hasura. While stumbling on Hasura videos on Youtube (completely normal 1 AM Behavior) I found out about this Library called GraphQL Mesh

I love exploring new libraries, and I've seen a lot of good ones, but let me not sugar-coat this, GraphQL Mesh is singlehandedly one of the MOST IMPACTFUL Libraries I've ever come across. So much so I thought it was worth making a blog post at 2:30 AM. Let me show you what it is, I strongly urge you to make a new Codesandbox with me and code along to build and really understand whats going on.

What Are We Making?#

GraphQL Mesh is exactly what it sounds like, it's a Mesh for GraphQL. It makes it super easy to convert an existing REST API into GraphQL. And when I say super easy I mean SUPER EASY.

Let's convert a free public REST API and turn it into a GraphQL one in minutes. I like to use this resource to find out Free Existing Public REST APIs I picked Metaweather but you can pick whatever you want

Why Use This?#

So before writing anything a good reason is to explain the use case for this library. Like I said in my earlier blog post, GraphQL is new, aka people take longer to buy into it. It's a lot of work to migrate OLD bloaty, existing unmanaged services that are running just fine, and the resources aren't there to focus on migrations of these apps--completely understandable. GraphQL does have a learning curve and may not be for everyone, which is EXACTLY why GraphQL mesh is amazing.

You can use this to build POC's or full-fledged Production-ready wrappers on GraphQL services. Our use case will be fairly simple as I want to use this as an opportunity to show how easy it is to convert existing APIs to GraphQL so people can see the power of it.

ENOUGH TALKING! LETS CODE! "Code" is in quotes cause we're not doing much, this powerhouse library is. Let's get started by creating a new Codesandbox, you'll want to select Node-Http-Server or for the lazy, click me You can start by deleting the existing src folder.

Steps

Install Dependencies#

On Codesandbox select the Dependencies Section on the Explorer Tab (or if you're doing this locally, install these via NPM or Yarn)

graphql @graphql-mesh/cli @graphql-mesh/json-schema

What Did We Just Do?#

  • We've added GraphQL, GraphQL Mesh, and a JSON handler library for Mesh. A handler Library allows us to plug in a bunch of different types of Popular existing API schemas such as Open API, Swagger, and many others. You can see all available Mesh Handlers here.
  • Mesh now expects us to provide us some sort of Sample Response and some configuration so it can build us a GraphQL API. Let's start configuration firsts

Configure#

Create a .mechrc.yml file in the root and paste the following yml file

sources:
  - name: Weather By Location
    handler:
      jsonSchema:
        baseUrl: https://www.metaweather.com/api
        operations:
          - type: Query
            field: queryLocations
            description: Fetch The Id
              of a particular Location!
            path: location/search/?query={args.searchQuery}
            method: GET
            responseSample: ./json-samples/locationResponse.json
          - type: Query
            field: weatherByLocation
            path: location/{args.woeid}
            method: GET
            responseSample: ./json-samples/weatherResponse.json

What Did We Just Configure#

So in this configuration file, we're essentially describing our API. We have a name, and essentially how we want to handle it. We're using jsonSchema so we say that and then provide the base URL.

We're only adding 2 operations as of now. The first is to get the information about our current location, as well as provide us a woeid. We can then use this woeid in the second query to fetch the weather. Again, we can check the Metaweather Docs for more info.

Notice the args.searchQuery, this tells Mesh that we have a user query input we need to take to be able to make the proper API call.

Once we're done with the first operation and we have the woeid we can then call the 2nd operation and get the weatherByLocation In GraphQL actually, we can do all of this in one call (but that will most likely be covered in a later post). When we execute the second operation we will get back the relevant information we have requested in our query.

Provide Some Sample Input#

For Mesh to be able to make a fully typed schema for us, we need to provide it as an example of a response. I went ahead to the following endpoint

🔗 https://www.metaweather.com/api/location/search/?query=San%20Francisco

to get a sample response of locationResponse.json

[
  {
    "title": "San Francisco",
    "location_type": "City",
    "woeid": 2487956,
    "latt_long": "37.777119, -122.41964"
  }
]

weatherResponse.json This is a slightly larger file so I won't paste it here, but you can click the link to view it!

Once we provide the example responses, we're done. Seriously that's all we had to do! We can now run mesh serve and that's it!

Here's an example query you can paste into the window that should open on port 4000 when you run mesh serve.

query getLocationInfo {
  queryLocations(searchQuery: "San Francisco") {
    woeid
    latt_long
    location_type
  }
}

query getWeather {
  weatherByLocation(woeid: 2487956) {
    time
    sun_set
    sun_rise
    consolidated_weather {
      air_pressure
      weather_state_name
      wind_direction
    }
  }
}

This has both our queries. You can try it out for any city, this is real-life data! I recommend writing queries from scratch to truly see the power of GraphQL and how easy it makes querying on the client-side.

GraphQL Playground

The schema serves as a contract between the front and the backend. You can view the Docs or Schema tabs by clicking on the GraphQL Playground. This gives you Comprehensive Documentation OUT OF THE BOX. As a client, you can see which fields you can request for, only take the data you need, and scratch the rest.

That's It!#

Hopefully, you enjoyed this tutorial, let me know if you have any questions or if something doesn't work.

You can reach me on Twitter (link above in navbar)

I've also gone ahead and put the code for this repo so you can clone it locally and run it (if code sandbox doesn't work)

Also, I strongly urge checking out GraphQL Mesh. There's so much more this library can do like handle Mutations, Subscriptions, and lots of other stuff I haven't gotten to yet myself. Super pumped to continue using this library.