Ceci est une ancienne révision du document !
This month marks the final Command & Conquer article I’ll be writing. For more details on why, you may want to look at last month’s article. That being said, I wanted to do something a little different for the last article. The first part of the article will be dedicated to some articles I’m most proud of having written, and the second half will be dedicated to writing a GraphQL API to track my Go games. So if you’re interested in one but not the other, you know where to jump to.
Part 1
I’ve been writing for FCM since issue #21 - 131 issues ago! Over that time I’ve written some articles that are, as of now, obsolete, and some that hold up to the test of time. Below you’ll find a list of my favorite articles that I’ve written, and what issue they appeared in: • CLI Cookbook - FCM #76. I’m most proud of this one because we managed to get the community involved and actually created something together. I can’t guarantee that all the commands are still accurate, but I’m sure there are still a good few ideas that are valid. The actual PDF/LaTeX documents can be found here: https://github.com/lswest/cli-cookbook • Flexbox Stylus - FCM #92. This was another fun little project I wrote for myself that yielded a great article. I built a set of helper functions for Stylus to easily create/manage Flexbox settings. Not terribly useful in this day and age, but still fun. • Tailwind CSS - FCM #134. This article introduced my readers to a tool that completely changed my approach to designing and styling websites, and is a method I still use to this day. Definitely a worthwhile read to anyone who’s interested in web development. • My web development articles. I won’t list all the issues I had web development focused articles in (though there will be a few at the end of this item). The reason I’m proud of these articles is quite simple - I both enjoyed the topic, and used the knowledge in my professional life (I still do!). In writing those sorts of articles, I always hoped to make the entry into new web technologies easier for beginners. Noteworthy articles: Gatsby Multi-Language (151), AMP (127), CSS Grids (125), Static Site Generation (103).
There are other articles on a wide range of topics - guitar, note taking, virtualization, etc. Unfortunately, I don’t have a complete list of articles anywhere for easy browsing. If any readers have something like that, they’re welcome to email it to me (address below).
Part 2
Now, on to other topics near and dear to my heart: Go & GraphQL.
For anyone not familiar with Go, it’s an ancient chinese board game (estimated at over 2500 years old), played with black and white stones on a 19×19 grid. It’s also known as Baduk or Weiqi in Korea and China, respectively.
GraphQL is a (much) more recent invention. It’s a query language for APIs that define a schema of data, and allow flexible querying for information. Basic example - you could define a schema for a book and an author, and keep track of things like ISBN, number of pages, publishing date, author, title, etc. Anyone who has access to the API can, using the same URL, selectively query only the data they want (i.e. title, author, and cover page) instead of getting everything back every time. It’s the backend to Gatsby’s static site generation (controlled via the gatsby-node.js file), and is extremely powerful. Ever since using it for the first time, I’ve wanted to create my own GraphQL API to replace my aging Ruby on Rails application that I use for tracking movies and video games I want to see/buy. I have since converted the information I already had (stored in a sqlite database from Rails) into mongodb, and written the API to the point where it can access and create entries in the database. Now it’s time to expand the functionality - adding in my Go games. I will not be covering the frontend aspect (planned to be a Gatsby PWA that hydrates data on load), as it’s not been completed yet, and GraphQL is flexible enough that you can access it from pretty much anything.
All code has been placed into a Gist here: https://gist.github.com/lswest/d2118f4fa0225b80993acb7337fdefc2
I will be linking to individual files throughout the article! So there’s no need to grab them all now.
The Basics
I set up my API using Express.js, mongoose, apollo-server, and apollo-server-express. Most aspects will remain the same regardless of implementation, but the actual connection to the database will differ.
How does a GraphQL API work? You define a few schemas (think of it as a class definition) for queries, types, and mutations. Mutations are the create/update/delete aspect of CRUD, and queries are the “read” aspect. I won’t go into detail on the mutations, just a basic create function.
GraphQL then takes your defined schema and uses it for validation, typing, and for understanding the requests sent to it. The schemas also control which fields from your database are available in the API.
Basic folder structure: /src/models/ /src/schemas/ /src/resolvers/ /src/index.js /package.json
Requirements
Make sure you’ve installed NodeJS (the LTS should be sufficient if you don’t want to be on the faster moving stable branch), mongodb (or your database system of choice), and have some test data prepared (for example a JSON block to import into mongodb or to hard-code into the app).
To get the project up and running, you can do the following (if you prefer npm, all yarn commands have npm equivalents):
yarn init
yarn add -D nodemon @babel/core @babel/node @babel/preset-env
Create a .babelrc file with: { “presets”: [“@babel/preset-env”] }
yarn add mongoose express graphql apollo-server apollo-server-express
Add the following script to your package.json: “dev”: “nodemon –exec babel-node src/index.js”
Using Compass or mongo’s CLI, be sure to create a database to store your data in if you want to use a database.
Step 1 Mongoose Schema
For a mongodb implementation with mongoose, you define a mongoose.Schema (separate from the GraphQL Schema). Here you’re essentially defining the document structure to be stored/loaded from the collection(s).
My Schema for Go looks like this:
/src/models/goGames.js: https://gist.github.com/lswest/d2118f4fa0225b80993acb7337fdefc2#file-models-gogames-js
Basic explanation
I defined fields for a ‘go’ game to include Title (i.e. Lucas VS George), the date played (currently defined as a String, as I haven’t yet figured out how to make dates work correctly), what server it was played on (KGS, IGS, FGS, online-go, etc), Black and White player names, Komi (the points given to White for going second), Result in the traditional notation - i.e. B+Res, and MyWin which tracks if I won this game (for statistics later on) - if I were to add someone else’s game, I’d simply leave this as false, and SGF. I tend to download my games’ SGF files and store them somewhere on my PC. While I won’t necessarily link them all on a web server, I can at least track the name. If I do eventually add them in as static files, I can then just update them to links.
The collection defines what I want the collection to be called in mongodb (currently, the collection does not exist - so I could have chosen anything here). You then apply the schema to a model, and export the resulting variable to use later on.
Step 2 GraphQL Schema
Once we’ve defined our mongodb server, we need to define our GraphQL schema. You should base the schema off your database definition, but it does not have to be a one-to-one match.
The GraphQL Schema I defined looks like this:
/src/schemas/goGames.js: https://gist.github.com/lswest/d2118f4fa0225b80993acb7337fdefc2#file-schemas-gogames-js
The GoGame type is a match for the mongoose Schema, and the createGoGame mutation takes pretty much all the fields.
The queries, however, are specialized. The first query (goGame) can only be filtered by ID and/or title, as it returns a single instance it makes sense to be as restrictive as possible to avoid weird results. The allGoGames query can be filtered using pretty much all fields except Komi and Result. As my goal for this API is to track my own games, I’m more likely to search for games where I was black or white, and perhaps define if it was a win or a loss. I don’t think I’ll ever search for all games where Komi was 0.5, for example. If I end up needing this, I can simply add it in as an option. Similarly, I won’t necessarily be filtering by result, as I’ll never (at that point) know which player was which. The field is important for a quick overview, but shouldn’t be very useful when filtering what I want to see. I also added a Limit field to the allGoGames, to limit the number of results returned.
Step 3 Resolvers
Okay, we’ve now defined our schemas and given some thought to the options available in a query. However, until we define our resolvers, the query won’t work. A resolver is a function that defines what happens with the parameters we defined in our schema. For my Go games, it looks like this:
/src/resolvers/goGames.js: https://gist.github.com/lswest/d2118f4fa0225b80993acb7337fdefc2#file-resolvers-gogames-js
Admittedly, almost all my resolvers look like this, with the only difference being variable names and the models used. The goGame resolver is the simplest - I take any of the args passed through (Title or _id), and then run a findOne on the collection.
The allGoGames resolver is more complicated. I pass in all the args, including a field called Limit. The idea behind ‘limit’ is to set a maximum number of results (ie. if I want a top 10). As this field doesn’t exist in the mongodb document, it will never yield results if it’s just passed in that way. Instead, I check if args has a property ‘Limit’. If it does, I create a copy of the object and delete the ‘Limit’ property. I then adjust the mongodb command to pass in the remaining arguments and use args.Limit in the .limit() function. If args.Limit doesn’t exist, I just run a find() on all the args.
The createGoGame resolver takes all the arguments I specified in the GraphQL Schema. However, it also needs an id. Instead of forcing the user or client to generate one, I instead add an _id field to the object using mongoose.Types.ObjectId() before creating the item.
Step 4 - Putting it all together
The first thing I would recommend you do is create an index.js file in both /src/schemas and /src/resolvers. This file will serve as an aggregator for all your schemas and resolvers once you have more than one.
/src/schemas/index.js: https://gist.github.com/lswest/d2118f4fa0225b80993acb7337fdefc2#file-schemas-index-js
/src/resolvers/index.js: https://gist.github.com/lswest/d2118f4fa0225b80993acb7337fdefc2#file-resolvers-index-js
Now for the heart of the server:
/src/index.js: https://gist.github.com/lswest/d2118f4fa0225b80993acb7337fdefc2#file-src-index-js
Be sure to replace {MONGO_URL} with your actual mongodb connection string (most likely mongodb:localhost:27017/{database}), where {database} is whatever database name you defined manually in step 1. Step 5 - Trying it out Once you’ve started the server with yarn dev, the server should be running on localhost:5000. However, the root doesn’t return anything as we only defined the path “/graphql”. So head on over to http://localhost:5000/graphql and have a play around on your graphiql instance. To create items: mutation { createGoGame(Title:“Example”,PlayedDate:“2019-12-06”,Server:“Fox”,Black:“Player1”,White:“Player2”,Komi:“7.5”,Result:“B+Res”,MyWin:false,SGF:“2019-12-06 - example.sgf”) { _id } } The above will generate an entry and return the id for you to use in a goGame query. To query items: { goGame(_id: “id from above”) { Title } } To see them all, you can also run: { allGoGames { Title } } So, I hope this last article has gotten you enthused for GraphQL. To all my avid readers - thank you for your time and interest over these years! As always, if you want to send me a message you can reach me at lswest34+fcm@gmail.com. Especially if you happen to have a good list of my articles and what issues they appeared in!