background

When it comes to network requests between clients and servers, REST is definitely the most popular option for connecting the two. In REST, all concepts evolve through resources that can be accessed through urls. You can read a resource with an HTTP GET request, create a resource with an HTTP POST request, or update or DELETE a resource with HTTP PUT and HTTP DELETE. These are called CRUD (Create, Read, Update, Delete) operations. A resource can be any entity, such as authors, articles, or users. With REST, there is no definitive format for transferring data, but most people will use JSON as the medium for transferring data. Finally, REST enables applications to interact with data directly through native HTTP urls and HTTP methods.

/ / / / GET a RESTful request https://api.domain.com/authors/7 JSON data in the response {" id ":" 7 ", "name" : "Robin Wieruch", "avatarUrl" : "https://domain.com/authors/7", "firstName": "Robin", "lastName": "Wieruch" }Copy the code

What is GraphQL?

Let’s answer the question: What is GraphQL? GraphQL is an open source query language created by Facebook in 2012. Before it became open source, Facebook used it for internal mobile applications. Why mobile apps? GraphQL was developed as an alternative to the generic REST architecture, allowing clients to request only the data they need — no more, no less, and everything is client-led. In a RESTful architecture, it is difficult to get data on demand because the back-end developer defines the data returned on the resources of individual urls, rather than the front-end developer making the demand for the data. Often the front end needs to request all the information in a resource, even if only part of the data is needed. This problem is known as overfetching. In the worst case scenario, a client application has to request more than one resource instead of one, which often leads to multiple network requests. This can lead not only to overacquisition, but also to waterfall network requests. So if you use a query language like GraphQL, not only on the server side, but also on the client side, the client decides what data it needs, so it just sends a request to the server. In the case of Facebook’s GraphQL mobile development scenario, this greatly reduces the number of forgotten requests, because GraphQL only has to make one request at a time, and the amount of data in transit is reduced.

Facebook has opened source the GraphQL standard and its JavaScript version of the implementation. Later standards were implemented in major programming languages. In addition, the ecology around GraphQL not only extends the implementation of different languages horizontally, but also gives rise to class libraries (such as Apollo and Relay) that implement GraphQL on top of it.

A GraphQL operation can be a query (read operation), a modification (mutation (write operation), and a subscription (continuous read operation). Each of these operations is just a string constructed according to the GraphQL standard. Once a GraphQL operation has moved from the front-end application to the back-end application, the entire GraphQL Schema is first interpreted on the back-end, and then the related data is parsed for the front-end. GraphQL does not require network layer selection (usually HTTP), nor does it require the data format to be transmitted (usually JSON). It does not even require an application architecture (usually a front-end decoupled architecture). It’s just a query language.

Author (id: "7") {id name avatarUrl articles(limit: 2) {name urlSlug}} // GraphQL query result {"data": { "author": { "id": "7", "name": "Robin Wieruch", "avatarUrl": "https://domain.com/authors/7", "articles": [ { "name": "The Road to learn React", "urlSlug": "the-road-to-learn-react" }, { "name": "React Testing Tutorial", "urlSlug": "react-testing-tutorial" } ] } } }Copy the code

As you can see, a query requests multiple resources (author, article), called fields (Fileds) in GraphQL, Even if the GraphQL Schema provides more data (such as description and releaseDate in the article), we will only get a subset of these fields (name and urlSlug in the article). In contrast, in a RESTful architecture, where you need at least two consecutive requests for the author entity and its article, GraphQL can do this with a single query. In addition, queries only need to select the necessary fields, not the entire data entity.

The pros and cons of GraphQL

Advantages:

  • Declarative data retrieval
  • There is no over-fetching in GraphQL
  • GraphQL in React, Angular, Node, and Co
  • GraphQL Introspection

Disadvantages:

  • Complexity of the GraphQL query
  • Query frequency limit
  • GraphQL cache

More details we can see here: www.jianshu.com/p/f45fe96de…

In actual combat

Use two minutes, we use Prisma-server +MemFireDB+ Docker hand in hand step by step to carry out a simple combat. Prisma and MemFireDB access addresses are referenced in the last section

The deployment environment

Here we get ubuntu18.4 ready, install docker, and turn off the firewall (very important)

apt-get update
apt-get install docker
sudo ufw disable
sudo iptables -F
Copy the code

Install the latest version of NodeJS

sudo npm config set registry https://registry.npm.taobao.org
sudo npm install n -g
sudo n stable
Copy the code

Install the CLI tool of Prisma, here is installed prisma1, the latest prisma2 has not provided graphqL-server image

npm install -g prisma1
Copy the code

Edit the docker-compose file, mainly to change the database service address, database name, user name and password, here directly in the MemFireDB console view to obtain

mkdir hello-world cd hello-world touch docker-compose.yml cat docker-compose.yml version: '3' services: prisma: image: Prismagraphql/prisma: restart 1.34: always ports: - '4466-4466' environment: PRISMA_CONFIG: | port: 4466 databases: default: connector: postgres host: "" port: "" user: "" password: "" database: "" volumes: postgres: ~Copy the code

Start the prisma – server

docker-compose up -d
Copy the code

Check whether prisma-server is started successfully and whether the database is connected properly

Docker logs {docker id}Copy the code

The following logs indicate that the service has started normally

[INFO] Obtaining exclusive agent lock...
[INFO] Initializing workers...
[INFO] Successfully started 1 workers.
Server running on :4466
[INFO] Obtaining exclusive agent lock... Successful.
[INFO] Deployment worker initialization complete.
Copy the code

It can be accessed directly from the browser

Configure the server address information for the CLI that you downloaded earlier

prisma1 init --endpoint http://localhost:4466
Copy the code

Deploy the API to Prisma-Server, which generates API interfaces based on the Datamode for other client applications to access

prisma1 deploy
Copy the code

Data management is possible on the back end of Prisma-Server

Using dBeaver to connect to MemFireDB, we can also see the schema and table we just created

We can insert some data

Look at all the data again through GraphQL

If the interface changes, we don’t need to change any backend code. We just need to change the front end query statement to query the User information with the specified ID again

conclusion

Because REST proposes identifying resources by URL, you often end up with inefficient sequential requests. For example, you start by locating an author entity by id, and then you request all of his articles based on information obtained by the author’s ID. It only takes one request in GraphQL, which is much more efficient. Further, if you just want to get all of the author’s article data and don’t care about the author’s information, GraphQL allows you to select only the information you need. In REST, you need to get all of the author’s physical information first, even if you only care about the author’s article.

In the end, GraphQL turns what data is returned from the server side to the client side deciding what is needed.

reference

www.jianshu.com/p/f45fe96de… Juejin. Cn/post / 684490… V1. Prisma. IO/docs / 1.34 / g… memfiredb.com