Algaja juhend GraphQL-ile

Üks tänapäeval kõige sagedamini arutletud termineid on API. Paljud inimesed ei tea täpselt, mis on API. Põhimõtteliselt tähendab API rakenduse programmeerimisliidest. See, nagu nimigi ütleb, on liides, millega inimesed - arendajad, kasutajad, tarbijad - saavad andmetega suhelda.

Võite mõelda API-st kui baarmenist. Palute baarmenilt juua ja nad annavad teile seda, mida tahtsite. Lihtne. Miks see siis probleem on?

Alates moodsa veebi algusest ei ole API-de loomine olnud nii raske, kui see kõlab. Kuid API-de õppimine ja mõistmine oli. Arendajad moodustavad suurema osa inimestest, kes kasutavad teie API-d millegi loomiseks või lihtsalt andmete tarbimiseks. Nii et teie API peaks olema võimalikult puhas ja intuitiivne. Hästi kujundatud API-d on väga lihtne kasutada ja õppida. See on ka intuitiivne, mida on hea meeles pidada, kui hakkate oma API-d kujundama.

Oleme API-de loomiseks pikka aega kasutanud REST-i. Koos sellega kaasnevad mõned probleemid. REST-i kujunduse abil API loomisel peate silmitsi järgmiste probleemidega:

1) teil on palju lõpp-punkte

2) arendajatel on teie API-d palju raskem õppida ja mõista

3) esineb liiga palju ja liiga vähe teavet

Nende probleemide lahendamiseks lõi Facebook GraphQL-i. Täna arvan, et GraphQL on parim viis API-de loomiseks. See artikkel ütleb teile, miks peaksite seda juba täna õppima hakkama.

Selles artiklis saate teada, kuidas GraphQL töötab. Ma näitan teile, kuidas luua GraphQL-i abil väga hästi kujundatud, tõhus ja võimas API.

Ilmselt olete GraphQL-ist juba kuulnud, kuna paljud inimesed ja ettevõtted kasutavad seda. Kuna GraphQL on avatud lähtekoodiga, on selle kogukond tohutult kasvanud.

Nüüd on aeg hakata praktikas õppima, kuidas GraphQL töötab ja kõike selle maagiat.

Mis on GraphQL?

GraphQL on avatud lähtekoodiga päringukeel, mille on välja töötanud Facebook. See pakub meile tõhusamat viisi meie API-de kujundamiseks, loomiseks ja tarbimiseks. Põhimõtteliselt on see RESTi asendaja.

GraphQL-l on palju funktsioone, näiteks:

  1. Kirjutate soovitud andmed ja saate täpselt need andmed, mida soovite. Enam pole vaja teavet üle hankida, nagu oleme RESTiga harjunud.
  2. See annab meile ühe lõpp-punkti , mitte enam sama API-le versiooni 2 ega versiooni 3.
  3. GraphQL on tugevalt kirjutatud ja sellega saate enne täitmist GraphQL tüüpi süsteemis päringu kinnitada. See aitab meil luua võimsamaid API-sid.

See on GraphQLi põhiline sissejuhatus - miks see on nii võimas ja miks see tänapäeval palju populaarsust kogub. Kui soovite selle kohta rohkem teada saada, soovitan teil minna GraphQL-i veebisaidile ja vaadata seda.

Alustamine

Selle artikli peamine eesmärk ei ole õppida GraphQL-serveri seadistamist, nii et me ei süvene sellesse praegu. Eesmärk on õppida, kuidas GraphQL praktikas töötab, nii et me kasutame nullkonfiguratsiooniga GraphQL-i serverit nimega Graphpack.

Meie projekti alustamiseks loome uue kausta ja saate selle nimetada mis iganes soovite. Ma nimetan seda graphql-server:

Avage terminal ja tippige:

mkdir graphql-server

Nüüd peaksite masinasse olema installitud npm või lõng . Kui te ei tea, mis need on, on npm ja lõng JavaScripti programmeerimiskeele paketihaldurid. Node.js-i puhul on vaikimisi paketihaldur npm .

Sisestage oma loodud kausta järgmine käsk:

npm init -y

Või kui kasutate lõnga:

yarn init 

npm loob teile package.jsonfaili ja kõik teie installitud sõltuvused ning teie käsud on olemas.

Nüüd installime ainsa sõltuvuse , mida kasutama hakkame.

☄️Graphpack võimaldab teil luua GraphQL server null konfiguratsioonist . Kuna me alustame alles GraphQL-iga, aitab see meil palju edasi minna ja rohkem teada saada, ilma et peaksime serveri konfiguratsiooni pärast muretsema.

Installige oma terminalis juurkausta sees see:

npm install --save-dev graphpack

Või kui kasutate lõnga, peaksite minema järgmiselt:

yarn add --dev graphpack

Pärast Graphpacki installimist minge meie skriptidesse package.jsonfailis ja pange järgmine kood sinna:

"scripts": { "dev": "graphpack", "build": "graphpack build" }

Loome kausta nimega srcja see on ainus kaust kogu meie serveris.

Looge kaust nimega src, seejärel loome meie kausta sees ainult kolm faili.

srcLooge meie kausta sees fail nimega schema.graphql. Selle esimese faili sisse pange järgmine kood:

type Query { hello: String }

Selles schema.graphqlfailis saab olema kogu meie GraphQL-i skeem. Kui te ei tea, mis see on, siis seletan hiljem - ärge muretsege.

Nüüd srclooge meie kausta sees teine ​​fail. Helistage sellele resolvers.jsja sisestage selle teise faili sisse järgmine kood:

import { users } from "./db"; const resolvers = { Query: { hello: () => "Hello World!" } }; export default resolvers;

See resolvers.jsfail saab olema viis, kuidas pakume juhiseid GraphQL-i toimingu muutmiseks andmeteks.

Ja lõpuks, srclooge oma kausta sees kolmas fail. Helistage sellele db.jsja sisestage selle kolmanda faili sisse järgmine kood:

export let users = [ { id: 1, name: "John Doe", email: "[email protected]", age: 22 }, { id: 2, name: "Jane Doe", email: "[email protected]", age: 23 } ];

In this tutorial we’re not using a real-world database. So this db.js file is going to simulate a database, just for learning purposes.

Now our src folder should look like this:

src |--db.js |--resolvers.js |--schema.graphql

Now, if you run the command npm run dev or, if you’re using yarn, yarn dev, you should see this output in your terminal:

You can now go to localhost:4000 . This means that we’re ready to go and start writing our first queries, mutations, and subscriptions in GraphQL.

You see the GraphQL Playground, a powerful GraphQL IDE for better development workflows. If you want to learn more about GraphQL Playground, click here.

Schema

GraphQL has its own type of language that’s used to write schemas. This is a human-readable schema syntax called Schema Definition Language (SDL). The SDL will be the same, no matter what technology you’re using — you can use this with any language or framework that you want.

This schema language its very helpful because it’s simple to understand what types your API is going to have. You can understand it just by looking right it.

Types

Types are one of the most important features of GraphQL. Types are custom objects that represent how your API is going to look. For example, if you’re building a social media application, your API should have types such as Posts, Users, Likes, Groups.

Types have fields, and these fields return a specific type of data. For example, we’re going to create a User type, we should have some name, email, and age fields. Type fields can be anything, and always return a type of data as Int, Float, String, Boolean, ID, a List of Object Types, or Custom Objects Types.

So now to write our first Type, go to your schema.graphql file and replace the type Query that is already there with the following:

type User { id: ID! name: String! email: String! age: Int }

Each User is going to have an ID, so we gave it an ID type. User is also going to have a name and email, so we gave it a String type, and an age, which we gave an Int type. Pretty simple, right?

But, what about those ! at the end of every line? The exclamation point means that the fields are non-nullable, which means that every field must return some data in each query. The only nullable field that we’re going to have in our User type will be age.

In GraphQL, you will deal with three main concepts:

  1. queries — the way you’re going to get data from the server.
  2. mutations — the way you’re going to modify data on the server and get updated data back (create, update, delete).
  3. subscriptions — the way you’re going to maintain a real-time connection with the server.

I’m going to explain all of them to you. Let’s start with Queries.

Queries

To explain this in a simple way, queries in GraphQL are how you’re going to get data. One of the most beautiful things about queries in GraphQL is that you are just going to get the exact data that you want. No more, no less. This has a huge positive impact in our API — no more over-fetching or under-fetching information as we had with REST APIs.

We’re going to create our first type Query in GraphQL. All our queries will end up inside this type. So to start, we’ll go to our schema.graphql and write a new type called Query:

type Query { users: [User!]! }

It’s very simple: the usersquery will return to us an array of one or more Users. It will not return null, because we put in the ! , which means it’s a non-nullable query. It should always return something.

But we could also return a specific user. For that we’re going to create a new query called user. Inside our Query type, put the following code:

user(id: ID!): User! 

Now our Query type should look like this:

type Query { users: [User!]! user(id: ID!): User! }

As you see, with queries in GraphQL we can also pass arguments. In this case, to query for a specific user, we’re going to pass its ID.

But, you may be wondering: how does GraphQL know where get the data? That’s why we should have a resolvers.js file. That file tells GraphQL how and where it's going to fetch the data.

First, go to our resolvers.js file and import the db.js that we just created a few moments ago. Your resolvers.js file should look like this:

import { users } from "./db"; const resolvers = { Query: { hello: () => "Hello World!" } }; export default resolvers;

Now, we’re going to create our first Query. Go to your resolvers.js file and replace the hello function. Now your Query type should look like this:

import { users } from "./db"; const resolvers = { Query: { user: (parent, { id }, context, info) => { return users.find(user => user.id === id); }, users: (parent, args, context, info) => { return users; } } }; export default resolvers;

Now, to explain how is it going to work:

Each query resolver has four arguments. In the user function, we’re going to pass id as an argument, and then return the specific user that matches the passed id. Pretty simple.

In the users function, we’re just going to return the users array that already exists. It’ll always return to us all of our users.

Now, we’re going to test if our queries are working fine. Go to localhost:4000 and put in the following code:

query { users { id name email age } }

It should return to you all of our users.

Or, if you want to return a specific user:

query { user(id: 1) { id name email age } }

Now, we’re going to start learning about mutations, one of the most important features in GraphQL.

Mutations

In GraphQL, mutations are the way you’re going to modify data on the server and get updated data back. You can think like the CUD (Create, Update, Delete) of REST.

We’re going to create our first type mutation in GraphQL, and all our mutations will end up inside this type. So, to start, go to our schema.graphql and write a new type called mutation:

type Mutation { createUser(id: ID!, name: String!, email: String!, age: Int): User! updateUser(id: ID!, name: String, email: String, age: Int): User! deleteUser(id: ID!): User! }

As you can see, we’re going to have three mutations:

createUser: we should pass an ID, name, email, and age. It should return a new user to us.

updateUser: we should pass an ID, and a new name, email, or age. It should return a new user to us.

deleteUser: we should pass an ID. It should return a new user to us.

Now, go to our resolvers.js file and below the Query object, create a new mutation object like this:

Mutation: { createUser: (parent, { id, name, email, age }, context, info) => { const newUser = { id, name, email, age }; users.push(newUser); return newUser; }, updateUser: (parent, { id, name, email, age }, context, info) => { let newUser = users.find(user => user.id === id); newUser.name = name; newUser.email = email; newUser.age = age; return newUser; }, deleteUser: (parent, { id }, context, info) => { const userIndex = users.findIndex(user => user.id === id); if (userIndex === -1) throw new Error("User not found."); const deletedUsers = users.splice(userIndex, 1); return deletedUsers[0]; } }

Now, our resolvers.js file should look like this:

import { users } from "./db"; const resolvers = { Query: { user: (parent, { id }, context, info) => { return users.find(user => user.id === id); }, users: (parent, args, context, info) => { return users; } }, Mutation: { createUser: (parent, { id, name, email, age }, context, info) => { const newUser = { id, name, email, age }; users.push(newUser); return newUser; }, updateUser: (parent, { id, name, email, age }, context, info) => { let newUser = users.find(user => user.id === id); newUser.name = name; newUser.email = email; newUser.age = age; return newUser; }, deleteUser: (parent, { id }, context, info) => { const userIndex = users.findIndex(user => user.id === id); if (userIndex === -1) throw new Error("User not found."); const deletedUsers = users.splice(userIndex, 1); return deletedUsers[0]; } } }; export default resolvers;

Now, we’re going to test if our mutations are working fine. Go to localhost:4000 and put in the following code:

mutation { createUser(id: 3, name: "Robert", email: "[email protected]", age: 21) { id name email age } }

It should return a new user to you. If you want to try making new mutations, I recommend you to try for yourself! Try to delete this same user that you created to see if it’s working fine.

Finally, we’re going to start learning about subscriptions, and why they are so powerful.

Subscriptions

As I said before, subscriptions are the way you’re going to maintain a real-time connection with a server. That means that whenever an event occurs in the server and whenever that event is called, the server will send the corresponding data to the client.

By working with subscriptions, you can keep your app updated to the latest changes between different users.

A basic subscription is like this:

subscription { users { id name email age } }

You will say it’s very similar to a query, and yes it is. But it works differently.

When something is updated in the server, the server will run the GraphQL query specified in the subscription, and send a newly updated result to the client.

We’re not going to work with subscriptions in this specific article, but if you want to read more about them click here.

Conclusion

Nagu nägite, on GraphQL uus tehnoloogia, mis on tõesti võimas. See annab meile tõelise jõu paremate ja hästi kujundatud API-de loomiseks. Sellepärast soovitan teil seda kohe õppima hakata. Minu jaoks asendab see lõpuks RESTi.

Täname artikli lugemise eest.

Jälgi mind Twitteris!

Jälgi mind GitHubis!

Ma otsin kaugemat võimalust, nii et kui mul on mõnda neist hea meel kuulda, siis võtke minuga ühendust oma Twitteris !