GraphQL 소개
오늘 우리는 GraphQL에 대해 배웁니다! GraphQL은 제 인턴십에서 배우고 사용할 수 있는 운이 좋은 새로운 도구입니다. 그래서 저는 GraphQL이 무엇인지, 왜 중요한지, 어떻게 사용할 수 있는지 함께 배울 수 있다고 생각했습니다.
시작하자!
학습 목표
Elements of GraphQL
GraphQL은 쿼리 언어입니다
As the title of this section suggests, GraphQL is a Query language. What does this mean? It means that GraphQL is a programming language used to get and post data.
_It is important to acknowledge what GraphQL is because of its name. While many databases end with "QL", GraphQL is NOT a database! Do not get confused by this. _
A "query", as you may have guessed, is a request usually for information (in programming: data!). In life, I can query how old you are by asking you "Hey, how old are you?". In return, you may answer: "25" "I am not telling!" "I am turning 30 in July."
Using GraphQL, we create queries to get data from our database. We ask our database: "How many users have brown eyes?" "How many pets does user 129i04u83 have?" "What stores are located in NYC?"
Recap: GraphQL is a QUERY language that we use to get and post data from our database.
Now, let's learn how it really works.
작동 방식
The client (the frontend of an application) uses GraphQL API to communicate with the database. Think of GraphQL as the bridge between the client and the database -- it does all the talking -- it is the middleman!
How does the client use GraphQL API? Answer: through the '/graphql'
endpoint. The client makes a request with a query to this endpoint (and this endpoint only) and the query determines what data is received or posted. Ultimately, the query describes to the endpoint what it wants.
The flow is as follows:
- The client makes a request with a query to the GraphQL endpoint =>
- The query is sent to GraphQL API =>
- GraphQL parses (JSON) the query =>
- GraphQL sends the desired data back to the client
GQL + REST의 차이점
In the section above, we learned that the client only has to make requests to a single endpoint: '/graphql'
. Which means GraphQL throws out the idea of REST (and its many, many endpoints) in order to use the single endpoint. Why?
With GraphQL, queries determine exactly what data is to be received or posted. These queries completely diminish the need to specify endpoints. Queries also reduce the amount of overfetching and underfetching of data in an application.
Overfetching occurs when the client receives more data than is needed from a specific REST endpoint.
For example, if I am building an application that takes a user's age and outputs their expected high school graduation year, I only really need the user's age. But say within my database, in addition to the user age data, I also have their address, height and eye color. None of that data is necessary for my application. Graphql querying allows a pinpoint level of specification as to not receive unnecessary data that may slow down the application or cost a lot of money.
Underfetching is quite the opposite: it occurs when a specific REST endpoint does not provide all the data required/desired for an application.
Check out this diagram below for a visual representation:
GraphQL의 요소
Let's look into some of the elements of GraphQL to get a better understanding:
데이터 유형
GraphQL has five (5) data types:
- ID => a unique identifier
- String => a UTF-8 character sequence
- Int => a signed 32-bit integer
- Boolean => true or false
- Float => a decimal
쿼리/유형
Now that we know what a query is, we can look into how GraphQL defines them.
GraphQL describes a query using the type keyword. For example, to create a query for "cat" with fields "name", "age" "color", "breed", we would code it out like this:
type Cat {
name: String
age: Int
color: String
breed: String
}
Within each field, we declare the field name (or a key) and the data type of its value. So the name, color and breed of a Cat is a string, while the age is an integer.
While querying, we can non-nullify the values of a field using an exclamation point(!) -- meaning the value of a cat's name cannot be "null". Like this:
type Cat {
name: String!
age: Int!
color: String!
breed: String!
}
This is the basic, universal syntax for defining a query in GraphQL.
스칼라
While the above, five (5) data types are scalars in GraphQL, GraphQL also allows for custom scalars. What does this mean? It means we can create and initialize our own "data types" to be used to query.
For example, let's say we have to query for website data:
type Website {
id: ID
name: String
url: Url
}
This query returns the website's id, name and url. We could possible store the value of the url field as a string, but then any ol' string could be assigned to "url". Such as "ww.google.com" or "hey hey hey". And those are not valid urls. So, instead, we could just create our own scalar called "Url".
In order to create our own scalar, we need to consider a few things:
1. How the scalar's value is represented in the backend
2. If and how the value's backend representation is JSON-compatible
So, a Url would be represented as a string in the backend, but a regexed string. Meaning, it has to fulfill some requirements, such as:
백엔드에서 정규식 문자열로 표시된 스칼라 값을 사용하여 프런트엔드로 성공적으로 전송하기 위해 JSON과 호환되는지 확인할 수 있습니다. 문자열은 실제로 JSON과 매우 호환됩니다!
더 많은 사용자 지정 스칼라를 만들 수 있습니다.
그 밖의 무엇을 생각할 수 있습니까?
열거형
Enums are basically a "special" data type we can use to catalog all the possible values or options for a given field. In short, the specified values of an enum are the only accepted options.
For example:
enum BoxState {
SHIPPED
DELIVERED
PENDING
}
When querying an object "box" and we want to know the state of the box, BoxState can only be provided the values of: SHIPPED, DELIVERED, or PENDING. The value cannot be "12", true/false, or "Awaiting truck for pickup".
Enums provide a specificity that keeps data values contained and limits bugs.
요약 + 요약
- GraphQL is a QUERY language.
- A query is a request for information/data.
- With GraphQL, the client uses a single endpoint to make requests:
'/graphql'
- GraphQL removes the need for many REST endpoints because of its queries.
- A "type" is a query.
- An "enum" defines all possible, accepted values for a field.
- Custom scalars can be defined and implemented as values for fields.
- Overfetching => receiving too much data that is not necessary for the application.
- Underfetching => an endpoint not providing the desired data necessary for the application.
🍵함께 읽어주시고 함께 배워주셔서 감사합니다. 아래에 자유롭게 공유, 좋아요 및 댓글을 달아주세요. 그러나 모든 사람이 항상 배우고 있으며 "올바른"방법이 항상 최선의 방법은 아니라는 점을 기억하십시오.
Reference
이 문제에 관하여(GraphQL 소개), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/am20dipi/introduction-to-graphql-2bkd텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)