issue152:c_c
Différences
Ci-dessous, les différences entre deux révisions de la page.
Prochaine révision | Révision précédente | ||
issue152:c_c [2019/12/30 08:26] – créée d52fr | issue152:c_c [2020/01/04 14:13] (Version actuelle) – auntiee | ||
---|---|---|---|
Ligne 1: | Ligne 1: | ||
- | 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. | + | **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 | + | L' |
+ | |||
+ | **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: | 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:// | + | • 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:// |
- | • 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/ | + | |
- | • 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, | + | Première partie |
- | Part 2 | + | J' |
+ | ••CLI Cookbook - n° 76 du FCM . C'est de celui-là dont je suis le plus fier parce que nous avons réussi à y associer la communauté pour vraiment créer quelque chose ensemble. Je ne peux pas assurer que toutes les commandes soient encore exactes, mais je suis sûr qu'il y a encore quelques bonnes idées qui restent valables. Les vrais documents PDF/LaTeX peuvent être trouvés ici : https:// | ||
+ | |||
+ | |||
+ | **• 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/ | ||
+ | • 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.** | ||
+ | |||
+ | ••Flexbox Stylus - n° 92 du FCM. C' | ||
+ | ••Tailwind CSS - n° 134 du FCM. Cet article présentait à mes lecteurs un outil qui avait complètement changé mon approche à la conception et au style de mes sites Web, et j' | ||
+ | |||
+ | **• 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, | ||
+ | |||
+ | •• Mes articles sur le développement Web. Je ne voudrais pas lister tous les numéros dans lesquels je me suis concentré sur le développement Web (bien qu'il y en ait quelques-uns à la fin de ce sujet). La raison pour laquelle je suis fier de ces articles est plutôt simple : j'ai apprécié le sujet en même temps que j'ai utilisé ces connaissances dans ma vie professionnelle (je continue encore !). En écrivant ces genres d' | ||
+ | |||
+ | Il y a d' | ||
+ | |||
+ | |||
+ | **Part 2 | ||
Now, on to other topics near and dear to my heart: Go & GraphQL. | 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 19x19 grid. It’s also known as Baduk or Weiqi in Korea and China, respectively. | + | 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 19x19 grid. It’s also known as Baduk or Weiqi in Korea and China, respectively.** |
+ | |||
+ | Seconde partie | ||
+ | |||
+ | Et maintenant, passons à d' | ||
+ | |||
+ | Pour ceux qui ne connaissent pas le Go, c'est un jeu chinois ancien sur plateau (on l' | ||
+ | |||
+ | **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.** | ||
+ | |||
+ | GraphQL est une invention (beaucoup) plus récente. C'est un langage de requête pour les API qui définit un schéma de données et permet un requêtage flexible des informations. Un exemple simple : vous pouvez définir un schéma pour un livre et un auteur, et conserver la trace de choses comme l' | ||
+ | |||
+ | **All code has been placed into a Gist here: https:// | ||
- | 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 | + | I will be linking |
- | All code has been placed into a Gist here: https:// | + | Tout le code a été mis dans un Gist ici : https:// |
- | I will be linking to individual files throughout the article! | + | Au long de l'article, je ferai le lien avec des fichiers spécifiques |
- | The Basics | + | **The Basics |
I set up my API using Express.js, mongoose, apollo-server, | I set up my API using Express.js, mongoose, apollo-server, | ||
- | 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/ | + | 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/ |
- | 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. | + | Les bases |
+ | |||
+ | J'ai paramétré mon API en utilisant Express.js, mongoose, apollo-server et apollo-server-express. La plupart des points ne changeront pas suivant l' | ||
+ | |||
+ | Comment fonctionne l'API GraphQL ? Vous définissez quelques schémas (voyez-les comme une définition de classe) pour les requêtes, les types et les mutations. Les mutations sont le côté créer/ | ||
+ | |||
+ | **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: | Basic folder structure: | ||
+ | / | ||
+ | / | ||
+ | / | ||
+ | / | ||
+ | / | ||
+ | |||
+ | GraphQL prend ensuite le schéma défini et l' | ||
+ | |||
+ | Structure de base des dossiers : | ||
/ | / | ||
/ | / | ||
Ligne 38: | Ligne 83: | ||
/ | / | ||
- | Requirements | + | **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). | 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): | 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/ | ||
+ | |||
+ | Requis | ||
+ | |||
+ | Asssurez-vous d' | ||
+ | |||
+ | Pour installer et lancer le projet, vous pouvez faire ce qui suit (si vous préférez npm, toutes les commandes yarn ont des équivalents npm) : | ||
yarn init | yarn init | ||
Ligne 48: | Ligne 103: | ||
yarn add -D nodemon @babel/core @babel/node @babel/ | yarn add -D nodemon @babel/core @babel/node @babel/ | ||
- | Create a .babelrc file with: | + | **Create a .babelrc file with: |
{ | { | ||
" | " | ||
Ligne 58: | Ligne 113: | ||
" | " | ||
- | Using Compass or mongo’s CLI, be sure to create a database to store your data in if you want to use a database. | + | 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 | + | Créez un fichier .babelrc avec : |
+ | { | ||
+ | " | ||
+ | } | ||
+ | |||
+ | yarn add mongoose express graphql apollo-server apollo-server-express | ||
+ | |||
+ | Ajoutez le script suivant dans votre paquet .json : | ||
+ | " | ||
+ | |||
+ | En utilisant Compass ou la ligne de commande de mongo, assurez-vous de créer une base de données pour y stocker vos données si vous voulez utiliser une base de données. | ||
+ | |||
+ | **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/ | 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/ | ||
My Schema for Go looks like this: | My Schema for Go looks like this: | ||
+ | |||
+ | / | ||
+ | |||
+ | Étape 1 - Schéma de Mongoose | ||
+ | |||
+ | Pour une implémentation de mongodb avec mongoose, vous définissez un mongoose.Schema (différent du schéma de GraphQL). Ici, vous définissez en gros la structure du document à charger/ | ||
+ | |||
+ | Mon schéma pour le Go ressemble à ceci : | ||
/ | / | ||
- | Basic explanation | + | **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.** | ||
+ | |||
+ | Explication simple | ||
- | I defined fields for a ‘go’ game to include Title (i.e. Lucas VS George), the date played | + | J'ai défini les champs pour un jeu « go » pour inclure un Titre (par ex., Lucas vs Georges), la date du jeu (actuellement définie comme une chaîne, car je n'ai pas encore réussi à faire fonctionner correctement les dates), |
- | 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. | + | **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 | 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. | + | 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: | + | La collection définit comment je veux l' |
+ | |||
+ | Étape 2 - Schéma de GraphQL | ||
+ | |||
+ | Une fois que nous avons défini notre serveur mongodb, nous devons définir notre schéma GraphQL. Vous devriez baser votre schéma sur la définition de votre base de données, mais il n'est obligatoire de les faire correspondre à 100 %. | ||
+ | |||
+ | **The GraphQL Schema I defined looks like this: | ||
/ | / | ||
- | The GoGame type is a match for the mongoose Schema, and the createGoGame mutation takes pretty much all the fields. | + | The GoGame type is a match for the mongoose Schema, and the createGoGame mutation takes pretty much all the fields.** |
+ | |||
+ | Le schéma GraphQL que j'ai défini ressemble à ceci : | ||
+ | |||
+ | / | ||
+ | |||
+ | Le type GoGame est une correspondance avec le schéma mongoose et la mutation createGoGame prend à peu près tous les champs. | ||
+ | |||
+ | **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.** | ||
- | The queries, however, are specialized. The first query (goGame) can only be filtered by ID and/or title, as it returns a single | + | Cependant, les requêtes sont spécialisées. La première requête |
- | Step 3 Resolvers | + | **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: | 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: | ||
Ligne 92: | Ligne 185: | ||
/ | / | ||
- | 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. | + | 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. | + | Étape 3 - Les résolveurs |
- | 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. | + | Bon ! Nous avons maintenant défini nos schémas et donné quelques éléments de réflexion sur les options disponibles dans une requête. Néanmoins, jusqu' |
- | Step 4 - Putting it all together | + | / |
+ | |||
+ | J' | ||
+ | |||
+ | **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.** | ||
+ | |||
+ | Le résolveur allGoGames est plus compliqué. Je passe tous les arguments, y compris un champ appelé Limit. L' | ||
+ | |||
+ | Le résolveur de createGoGame prend tous les arguments que j'ai spécifié dans le schéma de GraphQL. Cependant, j'ai aussi besoin d'un identifiant (id). Plutôt que de forcer l' | ||
+ | |||
+ | **Step 4 - Putting it all together | ||
The first thing I would recommend you do is create an index.js file in both / | The first thing I would recommend you do is create an index.js file in both / | ||
+ | |||
+ | / | ||
+ | |||
+ | / | ||
+ | |||
+ | Étape 4 - Regrouper tout ça | ||
+ | |||
+ | La première chose que je vous recommande de faire est de créer un fichier index.js à la fois dans / | ||
/ | / | ||
Ligne 106: | Ligne 219: | ||
/ | / | ||
- | Now for the heart of the server: | + | **Now for the heart of the server: |
+ | |||
+ | / | ||
+ | |||
+ | Be sure to replace {MONGO_URL} with your actual mongodb connection string (most likely mongodb:// | ||
+ | |||
+ | Maintenant, le cœur du serveur | ||
/ | / | ||
- | Be sure to replace | + | Assurez-vous de remplacer |
- | Step 5 - Trying it out | + | **Step 5 - Trying it out |
Once you’ve started the server with yarn dev, the server should be running on localhost: | Once you’ve started the server with yarn dev, the server should be running on localhost: | ||
To create items: | To create items: | ||
+ | |||
+ | mutation { | ||
+ | |||
+ | createGoGame(Title:" | ||
+ | _id | ||
+ | } | ||
+ | }** | ||
+ | |||
+ | Étape 5 - Test | ||
+ | |||
+ | Une fois que vous aurez démarré le serveur avec yarn dev, le serveur devrait fonctionner à localhost: | ||
+ | |||
+ | Pour créer des éléments : | ||
mutation { | mutation { | ||
Ligne 125: | Ligne 257: | ||
} | } | ||
- | The above will generate an entry and return the id for you to use in a goGame query. | + | **The above will generate an entry and return the id for you to use in a goGame query. |
To query items: | To query items: | ||
Ligne 139: | Ligne 271: | ||
{ | { | ||
| | ||
+ | Title | ||
+ | } | ||
+ | }** | ||
+ | |||
+ | La commande ci-dessus générera une entrée et retournera son identifiant, | ||
+ | |||
+ | Pour requêter des éléments : | ||
+ | |||
+ | { | ||
+ | | ||
Title | 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! | + | Pour tous les voir, vous pouvez lancer aussi : |
+ | |||
+ | { | ||
+ | | ||
+ | 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!** | ||
+ | |||
+ | Bien ! J' |
issue152/c_c.1577690771.txt.gz · Dernière modification : 2019/12/30 08:26 de d52fr