Apollo 클라이언트를 통해 GraphQL의 MERN 응용 프로그램(React Hooks)을 사용합니다.(섹션 1)

본고에서 우리는graphQL, Apollo 클라이언트와 어떻게 우리의 응용 프로그램에서 이 두 가지를 실현하는지 이해하려고 한다.

NOTE : If you don't know about React & Node, then please first understand some basics of both the technologies. It will help me to make you understand about this article.


GitHub Link : MERN-app-using-graphql-apollo-client


GraphQL이란 무엇입니까?


GraphQL은 클라이언트와 서버 간의 데이터 통신을 허용하는 강력한 검색 언어입니다.REST보다 유연하고 효과적입니다.

물론 우리는 어떠한 상황에서도 GraphQL을 사용하여 데이터 통신을 할 필요가 없지만, 어떤 상황에서는 GraphQL이 매우 최적화된 방법이 될 수 있다.예를 들어 우리가 자동차 관리 시스템을 구축해야 한다고 가정하자.이 학습 응용 프로그램에서 다음과 같은 가능성이 있습니다.
1) 차 한 대에 여러 명의 차주가 있을 수 있다.
2) 차주는 여러 대의 차를 소유할 수 있다.
이러한 상황을 고려하여 REST 방법에서는 스택에서 파이라몬 2 API를 사용할 수 있습니다.
=> 차 한 대의 종점을 얻습니다.
API::'도메인 이름/API/car/:id'
응답:'이름, 모델, 회사, 소유자 ID
= > 소유자 정보의 끝점을 가져옵니다.
API::'도메인 이름/API/소유자/:id'
이름, 나이, 성별, 충치
만약 우리가 차 한 대의 차주에 대한 상세한 정보와 그가 가지고 있는 다른 차의 정보가 필요하다면 어떤 상황이 발생할지 상상해 봅시다.이런 상황에서 우리는 그/그녀가 보유한 자동차 수량에 따라 많은api 클릭을 해야 한다.만약 우리의 응용 프로그램이 방대한 고객층을 가지고 있다면, 우리는 성능 문제에 빠질 수 있다.이 문제를 어느 정도 처리하기 위해서 우리는 이런 장면을 처리하는 더 좋은 방법이 있다.우리는 여기에서graphql를 사용할 수 있다.

이러한 장면의 GraphQL 방법은 다음과 같습니다.


{
   car(id:3){
    name
    model
    company
    Owner {
      name
      age
      cars{
        name
        company
      }
    }
   }

   //or
   car(id:3){
     name
     Owner{
       name
       gender
     }
   }
}
이 모든 정보는 API 한 번만 클릭하여 수집됩니다.이것이 바로 그래프ql의 힘이다.시작합시다.

서버 측 구현


먼저 NODE의 최신 버전을 시스템에서 다운로드해야 합니다.설치 후.VSCode 편집기를 사용하여 개발할 수 있습니다.그것은 무료다.
    Open terminal on VScode for ease.
  1) create folder MERNAPP
  2) cd MERNAPP
  3) create folder server
  4) Hit "npm init" command on terminal for creating package.json file
  5) And press "Enter" till it ends asking you question for creating it.

  //After creating package.json, Install the following packages in one go.

  6) npm install express express-graphql graphql lodash mongoose cors --save

  //After doing this step your package.json file look like this:

  //package.json
  {
  "name": "server",
  "version": "1.0.0",
  "description": "Server with Graphql & mongodb",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "vinod Chauhan",
  "license": "ISC",
  "dependencies": {
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "express-graphql": "^0.9.0",
    "graphql": "^14.5.4",
    "lodash": "^4.17.15",
    "mongoose": "^5.6.13"
  }
}

이 모든 패키지를 걱정하지 마세요. 왜 그리고 언제 이 패키지가 필요한지 알려드릴게요.


a) Express 애플리케이션 설치


1) 서버 폴더의 VS 편집기에서 새 파일 응용 프로그램을 만듭니다.js’.
 //Get the express library from node_modules which we have just downloaded.
const express = require("express");

//Making const of express() into a variable (JS function first class Object).
const app = express();

//When our application starts, it will listen on port 4000
app.listen(4000, () => {
  console.log("Server is listening on port 4000");
});

이 응용 프로그램을 실행합니다.js는 먼저 시스템에서 전역적으로 "nodemon"을 다운로드합니다. 이렇게 하면 변경 사항을 보기 위해 프로그램을 반복적으로 시작하거나 정지할 필요가 없습니다.
   //Install nodemon package
   npm install nodemon -g

   //Run your app.js with nodemon
   nodemon app.js
   [nodemon] 1.19.1
   [nodemon] to restart at any time, enter `rs`
   [nodemon] watching: *.*
   [nodemon] starting `node app.js`
   Server is listening on port 4000
너의 최애를 열어라.브라우저와 항목localhost: 4000, 현재 빈 페이지가 표시됩니다.
이 단계를 마쳤다면, 다음 express에서graphql를 설정합니다.

b) Express 앱의 GraphQL 설정


우리의'expressgraphql'서버는express서버가graphql를 이해하고 우리로 하여금 우리의 일을 완성하도록 도와줄 것입니다.
   //Get the express library from node_modules which we have just downloaded.
   const express = require("express");

   const graphqlHTTP = require("express-graphql");

   //Making const of express() into a variable (JS function first class Object).
   const app = express();

   /*We can use graphql on express server with middlewares, so that whenever
    we need graphql query from frontend, our express server can handle it
    smoothly.
    graphqlHTTP method let us do what we want to do if we have captured 
    '/graphql' middleware.
   */
   app.use("/graphql", graphqlHTTP({}));

   //When our application starts, it will listen on port 4000
   app.listen(4000, () => {
    console.log("Server is listening on port 4000");
   });
브라우저 종류:localhost:4000/graphql
실행 프로그램에서js, 현재 우리에게 오류를 줄 수 있습니다.
{"errors":[{"message":"GraphQL middleware options must contain a schema."}]}
걱정하지 마세요. 다음 단계는 Graphql 모드를 설정하는 것입니다.

c) GraphQL 모드


서버 폴더에서'schema'폴더를 만들고'schema'를 만듭니다.js가 안에 있어요.
** 모드 파일에는 세 가지 주요 책임이 있습니다.
1) GraphQLObjectType 객체에서 유형을 작성합니다.
2) 유형 간의 관계를 정의합니다.
3) 사용자가 도면에 들어가서 데이터를 사용할 수 있도록 RootQueries를 정의합니다.
구조로 삼다.js 파일은 서버에서 주요 역할을 하기 때문에 우리는 점차적으로 완성할 것이다.
 /// schema.js

const graphql = require("graphql"); //use graphql package

/*Getting GraphQLObjectType function from 'graphql' to define the (dataType) 
 structure of our queries and their model type.
*/
const {
  GraphQLObjectType,
  GraphQLID,
  GraphQLString,
  GraphQLInt,
  GraphQLSchema
} = graphql;

//Defining CarType with its fields.
const CarType = new GraphQLObjectType({
  name: "Car",
  fields: () => ({
    id: { type: GraphQLID },
    name: { type: GraphQLString },
    model: { type: GraphQLInt },
    company: { type: GraphQLString }
  })
});

//Defining RootQuery
const RootQuery = new GraphQLObjectType({
  name: "RootQueryType",
  fields: {
    // Fields here will be the query for frontends
    //We are defining a 'car' query which can take (car ID ) to search in DB.
    car: {
      type: CarType, //Defining model for car Query
      args: { id: { type: GraphQLID } },  //args field to extract argument came with car query, e.g : Id of the car object to extract its details.
      resolve(parent, args) {
        //code to get value  from DB
      } //resolve function
    } //car query ends here
  } //fields end here
});

//exporting 'GraphQLSchema with RootQuery' for GraphqlHTTP middleware.
module.exports = new GraphQLSchema({
  query: RootQuery
});


위의 파일 구조에서js, 다음 단계를 완료했습니다.
1) express 서버에서 graphql을 사용하기 위해 "graphql"를 가져옵니다.
2) graphql 라이브러리에서 서로 다른 대상과 데이터 형식을 가져옵니다.
3) GraphQLObjectType()에서 상수 CarType 유형과 필드()를 생성합니다.
4) GraphQLSchema 함수에 대한 포트 쿼리가 "car"인 rootQuery "rootQuery"를 만들고 있습니다.
5) 위의 내용을 매개변수로 "RootQuery"를 사용하여 GraphQLSchema로 내보냅니다.
응용 프로그램.js 변경 사항
 //Get the express library from node_modules which we have just downloaded.
const express = require("express");

const graphqlHTTP = require("express-graphql");

//Imports
const schema = require("./schema/schema");

//Making const of express() into a variable (JS function first class Object).
const app = express();

/*We can use graphql on express server with middlewares, so that whenever
    we need graphql query from frontend, our express server can handle it
    smoothly.
*/
app.use(
  "/graphql",
  graphqlHTTP({
    schema: schema
  })
);

//When our application starts, it will listen on port 4000
app.listen(4000, () => {
  console.log("Server is listening on port 4000");
});

지금까지 브라우저에서 출력이 바뀌었지만 다른 오류가 발생했습니다.
  {"errors":[{"message":"Must provide query string."}]}

//Dont worry guys we will remove this error too.

d) 해석 함수 정의


우선, 우리는 가상 데이터를 가져와서 우리의 조회가 잠시 작동할 수 있도록 한다.
모드에 다음 코드를 넣습니다.js 파일
const graphql = require("graphql"); //use graphql package

const _ = require("lodash");

/*Getting GraphQLObjectType function from 'graphql' to define the (dataType) 
 structure of our queries and their model type.
*/
const {
  GraphQLObjectType,
  GraphQLID,
  GraphQLString,
  GraphQLInt,
  GraphQLSchema
} = graphql;

const CarsArray = [
  { id: "1", name: "S-Class", model: "2019", company: "Mercedes" },
  { id: "2", name: "Continental GT", model: "2019", company: "Bentley" },
  { id: "3", name: "Phantom", model: "2019", company: "Rolls-Royce" },
  { id: "4", name: "Panamera", model: "2019", company: "Porsche" },
  { id: "5", name: "A8", model: "2019", company: "Audi" },
  { id: "6", name: "I-Pace", model: "2019", company: "Jaguar" }
];

//Defining CarType with its fields.
const CarType = new GraphQLObjectType({
  name: "Car",
  fields: () => ({
    id: { type: GraphQLID },
    name: { type: GraphQLString },
    model: { type: GraphQLInt },
    company: { type: GraphQLString }
  })
});

//Defining RootQuery
const RootQuery = new GraphQLObjectType({
  name: "RootQueryType",
  fields: {
    // Fields here will be the query for frontends
    //We are defining a 'car' query which can take (car ID ) to search in DB.
    car: {
      type: CarType, //Defining model for car Query
      args: { id: { type: GraphQLID } },
//args field to extract argument came with car query, e.g : Id of the car object to extract its details.
      resolve(parent, args) {
        //code to get value  from DB
        /**
         * With the help of lodash library(_), we are trying to find car with id from 'CarsArray'
         * and returning its required data to calling tool.
         */
        return _.find(CarsArray, { id: args.id });
      } //resolve function
    } //car query ends here
  } //fields end here
});

//exporting 'GraphQLSchema with RootQuery' for GraphqlHTTP middleware.
module.exports = new GraphQLSchema({
  query: RootQuery
});

다음은 우리가 모델에서 완성한 절차다.js:
1) "lodash"라이브러리를 가져와서 우리의 생활을 완화시킵니다.
2) 필요한 세부 정보가 포함된 가상 "CarsArray"
3) "car"조회의 "resolve"함수를 정의합니다.

e) 우리의 조회를 테스트합니다.


우선 우리의 조회를 테스트하기 위해서, 우리는 응용 프로그램에서 약간의 변경을 해야 한다.js 파일.
app.use(
  "/graphql",
  graphqlHTTP({
    schema: schema,
    graphiql: true
  })
);
"graphiql:true"를 추가함으로써, 우리는 우리의 검색을 테스트하기 위해 내장된 좋은 도구를 사용합니다.지금 열기:localhost:4000/graphql

위의 그림에서 보듯이 창 왼쪽에 자동차 대상의 id를 제공하여 필요한 상세한 정보를 포함하는 조회를 작성합니다.

Whoooaaaa! we have just made one car query in graphql. Congratulations if you are getting the result similar like me.


f) 소유자 유형을 정의합니다.


구조 중.js, 아래 코드를 작성합니다.
const graphql = require("graphql"); //use graphql package

const _ = require("lodash");

/*Getting GraphQLObjectType function from 'graphql' to define the (dataType) 
 structure of our queries and their model type.
*/
const {
  GraphQLObjectType,
  GraphQLID,
  GraphQLString,
  GraphQLInt,
  GraphQLSchema
} = graphql;

const CarsArray = [
  { id: "1", name: "S-Class", model: "2019", company: "Mercedes" },
  { id: "2", name: "Continental GT", model: "2019", company: "Bentley" },
  { id: "3", name: "Phantom", model: "2019", company: "Rolls-Royce" },
  { id: "4", name: "Panamera", model: "2019", company: "Porsche" },
  { id: "5", name: "A8", model: "2019", company: "Audi" },
  { id: "6", name: "I-Pace", model: "2019", company: "Jaguar" }
];

var OwnersArray = [
  { id: "1", name: "Vinod Chauhan", age: 27, gender: "male" },
  { id: "2", name: "John Dow", age: 46, gender: "male" },
  { id: "3", name: "Kristen", age: 30, gender: "female" },
  { id: "4", name: "Paris", age: 44, gender: "female" },
  { id: "5", name: "Sylvestor", age: 26, gender: "male" }
];

//Defining CarType with its fields.
const CarType = new GraphQLObjectType({
  name: "Car",
  fields: () => ({
    id: { type: GraphQLID },
    name: { type: GraphQLString },
    model: { type: GraphQLInt },
    company: { type: GraphQLString }
  })
});

//Defining CarType with its fields.
const OwnerType = new GraphQLObjectType({
  name: "Owner",
  fields: () => ({
    id: { type: GraphQLID },
    name: { type: GraphQLString },
    age: { type: GraphQLInt },
    gender: { type: GraphQLString }
  })
});

//Defining RootQuery
const RootQuery = new GraphQLObjectType({
  name: "RootQueryType",
  fields: {
    // Fields here will be the query for frontends
    //We are defining a 'car' query which can take (car ID ) to search in DB.
    car: {
      type: CarType, //Defining model for car Query
      args: { id: { type: GraphQLID } }, //args field to extract
      // argument came with car query, e.g : Id of the car object to extract its details.
      resolve(parent, args) {
        //code to get value  from DB
        /**
         * With the help of lodash library(_), we are trying to find car with id from 'CarsArray'
         * and returning its required data to calling tool.
         */
        return _.find(CarsArray, { id: args.id });
      } //resolve function
    }, //car query ends here
    owner: {
      type: OwnerType,
      args: { id: { type: GraphQLID } },
      resolve(parent, args) {
        return _.find(OwnersArray, { id: args.id });
      }
    }
  } //fields end here
});

//exporting 'GraphQLSchema with RootQuery' for GraphqlHTTP middleware.
module.exports = new GraphQLSchema({
  query: RootQuery
});

브라우저를 새로 고치거나 localhost:4000/graphql를 입력할 때 소유자 조회를 찾습니다.

I will try to upload the part-2 as soon as possible. Till the bye.

좋은 웹페이지 즐겨찾기