GRAPHQL Introduction & Building GRAPHQL Query services using NESTJS

Source: Internet
Author: User
Tags dataloader

GRAPHQL Introduction & Build GRAPHQL Query service using NESTJS (at the bottom of the article with demo address)

GRAPHQL a query language that is used for your API. From the facebook,graphql very easy to understand, directly look at the query statement can know what the query data. Essentially belongs to the API layer, which is responsible for the merging of front-end requests, data collation and other functions.

query Example

Use a few simple examples to see what the GRAPHQL query looks like.

General Query
{  {    name  }}

The data format of the query is as follows:

{  "me":{    "name":"wanghao"  }}

1. The returned data is a JSON
2, return data format and query exactly the same

Nested query with Parameters

Enter the parameter format:

{  user(id:6{    name,    {      width,      height,      url    }  }}

The following data is queried:

{  "me"{    "name":"wanghao,"    "profilePicture":{      "width":50,      "height":50,      "url":"https://cdn/some.jpg"    }  }}

Of course, profilepicture can also specify parameters when querying:

{  {    name,    profilePicture(size:300{      width,      height,      url    }  }}

The output might look like this:

{  "me"{    "name":"wanghao,"    "profilePicture":{      "width":300,      "height":300,      "url":"https://cdn/300.jpg"    }  }}
Specify an alias query

Sometimes the same field we want to query two times, but two times the specified parameters are different, such as a user has more than one avatar, we only want to query 2 of them, can be as follows:

{  {    name,    littlePic:profilePicture(size:50{      width,      height,      url    },    bigPic:profilePicture(size:300{      width,      height,      url    }  }}

The output results are as follows:

{  "Me" {    "Name": "Wanghao,"    "Littlepic": {      "width":  -,      "Height":  -,      "url": "Https://cdn/50.jpg"    },    "Bigpic": {      "width":  -,      "Height":  -,      "url": "Https://cdn/300.jpg"    }  }}

For more enquiries, please refer to: http://graphql.cn/learn/queries/

Change

Queries only apply to data queries, but often interfaces have some additions, modifications, and deletions, and this time you need to use changes (mutations).

To add a new piece of data, simply change the entry to the following parameters:

mutation($inputComment: CommentInput!{  addComment(data: $inputComment)}

Where $inputcomment is the variable notation in GRAPHQL, as follows:

{  "inputComment":{    "postId":"5a796104fe9b131a10d9627d",    "text":"测试评论部分23232"    }}

The return data is directly as follows:

{  "data":{    "addComment":true  }}
Data format on actual request

The GRAPHQL request does not limit the GET, post requests, and if it is get, the request body is automatically placed in query, looking at the actual request when the entry is what it looks like:

{    query:"mutation($inputComment: CommentInput!) {?  addComment(data: $inputComment)?}??"    variables:"{?  "inputComment": {?"postId":"5a796104fe9b131a10d9627d",?"text":"测试评论部分23232"?}"}

As you can see, when the request is actually sent a string of strings to the GRAPHQL server, the GRAPHQL server resolves the string content automatically.

GRAPHQL Visual Query Tool

All implementations of GRAPHQL have a basic implementation of this visualizer, simple configuration can be viewed, the EXPRESS-GRAPHQL module is configured as follows:

// GraphqQL server routeapp.use('/graphql',graphqlHTTP=> ({  schema,  pretty:true,         // 配置显示pretty按钮进行代码美化  graphiql:true,       // 配置开启可视化查询})));

Dataloadern+1 Query Questions
{  name: String,  friends: [User]}#查询{  {    name    {      name      {        name      }    }   }}

GRAPHQL supports nested queries, and if there is no dataloader, serious n+1 query performance issues occur.

Dataloader (official website), launched by Facebook, can significantly reduce the frequency of database visits and is often used in graphql scenarios.

ImportSequelize from ' Sequelize 'ImportDataloader from ' Dataloader '//define table structureConstSequelize= New sequelize(' Test ', NULL, NULL, {        dialect: ' SQLite ',    })ConstUsermodel= sequelize.Define(' user ', {    name: sequelize.STRING}) awaitsequelize.Sync({ Force: true})//Insert test Dataawait [Usermodel.Create({name: ' Ron '}),    Usermodel.Create({name: ' John '}),]//Initialize Dataloader, pass in a batch functionConstUserloader= New Dataloader(Keys= Usermodel.FindAll({where: {name: {$in:Keys}}}))//The following 2 load statements are automatically batched and merged into a single database operationawait [Userloader.Load(' Ron '),    Userloader.Load(' John ')]
Executing (defaultSELECTidFROMASuserWHEREIN ('ron''john’);

Typical applications for the Dataloader cache are per-request-scoped caches, which do not replace application-level caches such as Redis.

Building GRAPHQL Server services using Nestjs

Nestjs, official website address: https://docs.nestjs.com, is a framework that uses typescript to build Nodejs backend applications, similar to the spring framework in Java: Dependency injection, interceptors, filters, adorner patterns, and more.

Use Nestjs with GRAPHQL, Typeorm, MySQL to implement a simple GRAPHQL query service, query support single query, list query, association query, change support modification, delete operation, specific demo address: https://github.com/ Caiya/graphql-nestjs-typeorm

GRAPHQL Introduction & Building GRAPHQL Query services using NESTJS

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.