Apollo-express로 graphql 서버 구축

Graphql은 Facebook에서 개발한 REST API에 대한 현대적인 대안 접근 방식입니다. 일반 API와 마찬가지로 서버에서 데이터를 가져오고 서버에 데이터를 다시 넣는 데 사용됩니다.

Graphql은 적은 양의 데이터를 가져오려는 경우(필수) REST API가 많은 데이터를 가져오는 곳에서 빛을 발합니다. 너무 많은 데이터를 가져올 수 있습니다. API에는 graphql이 있는 여러 끝점이 있습니다. graphql의 문제점 중 하나는 graphql 서버를 만드는 것이 간단하지 않다는 것입니다. 한 번 완료되면 사용하는 것은 매우 간단합니다.

설정



Apollo 서버를 사용하여 graphql 서버를 구축하고 실행할 수 있습니다. graphql 끝점에 대한 경로를 생성하기 위해 노드 개발자가 선호하는 익스프레스 모듈을 활용할 수 있습니다.

종속성



시작하려면 폴더 프로젝트를 만든 다음 pacakge.json을 생성하기 위해 npm init -y 폴더로 cd해야 합니다.

또한 익스프레스와 함께 몇 가지 Apollo 종속성을 설치해야 합니다.

npm i -s apollo-server apollo-core express nodemon


nodemon help us to detect changes and automatically restart server for us.



VS Code에서 폴더를 열고 index.js 파일(루트 디렉토리에 있음)을 만들고 다음과 같이 서버를 실행하기 위해 package.json에 스크립트를 만듭니다.

//package.json
"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon ./index.js"
  },


모의 데이터



또한 프로젝트 루트에 다음 내용이 포함된 일부 모의 데이터 생성 users.js 파일을 표시하는 데 사용되는 사용자 목록이 있습니다.

//users.js
const users =[
    {
        name:"Dev",
        role: "DBA",
        id:1
    },
    {
        name:"Jhon Doe",
        role: "Admin",
        id:2
    },
    {
        name:"Martin",
        role: "Dev",
        id:3
    }
]
module.exports = users;


Apollo 서버 구축



모든 Apollo-graphql 서버 코드는 index.js에 있으며 선택적으로 스키마와 리졸버를 별도의 파일에 보관할 수 있습니다. 단순화를 위해 하나의 파일에 보관합니다.

//index.js
const users =require("./users")
const express = require('express');
const { ApolloServerPluginLandingPageDisabled, ApolloServerPluginLandingPageGraphQLPlayground } = require('apollo-server-core');
const { ApolloServer, gql } = require('apollo-server-express');

const typDefs = gql`
   type User{
        name:String!,
        role:String!,
        id:Int
   }
   type Query{
       getAll: [User!]!
   }
   type Mutation{
       newUser(name :String!,role:String ,id:Int):User
   } 
`;
const resolvers = {
    Query: {
        getAll() {
            return users;
        }
    },

    Mutation: {
        newUser(parent, args) {
            const usr = args;
            users.push(usr);
            return usr;
        }
    }
}
const server = new ApolloServer({
    typeDefs, resolvers,
    plugins: [
        ApolloServerPluginLandingPageGraphQLPlayground({
            // options
        })
        , ApolloServerPluginLandingPageDisabled()
    ]
});

const app = express();
server.start().then(r => {
    server.applyMiddleware({ app });
    app.listen({ port: 3000 }, () =>
        console.log('Now browse to http://localhost:4000' + server.graphqlPath)

    )
})



유형 정의



typedef 상수는 graphql 유형 정의, 쿼리 및 돌연변이를 포함하며 여러 키가 있는 사용자 정의 개체일 수 있습니다. 전체 데이터 유형 목록은 공식documentation을 참조하십시오.

질문



이름에서 알 수 있듯이 쿼리는 일부 데이터를 가져오는 데 사용되며 배열 구문을 사용하여 데이터를 가져옵니다.

돌연변이



돌연변이는 생성, 업데이트, 삭제 기능의 graphql 부분을 정의하기 위한 것입니다.

해결사



따라서 graphql의 첫 번째 부분은 type,query 및 Mutations로 완료됩니다. 하지만 이것만으로는 충분하지 않습니다. 이러한 구조는 리졸버 기능을 사용하여 작동하게 만들어야 합니다.

Resolver는 Query와 Mutation을 동작시키는 기능입니다.

플레이그라운드 및 플러그인



서버를 시작하기 전에 서버 설정의 플러그인 어레이가 쿼리 및 돌연변이를 테스트할 수 있는 새로운 Apollo 플레이 그라운드를 대체한다는 점에 유의하십시오. 플러그인을 제거하면 새 플러그인을 얻을 수 있습니다.

프로젝트 실행



서버를 실행하려면 npm을 실행하고 서버를 중지하려면 Ctrl + C를 사용하십시오.
for good read

좋은 웹페이지 즐겨찾기