본문 바로가기

node.js & graphQL 본문

개발/node.js

node.js & graphQL

자전하는명왕성 2023. 4. 11. 01:28

오늘은 node.js 에서 graphQL 을 사용하는 방법에 대해 공부한 내용에 대해 다룬다.

 

먼저 구조에 대해 얘기하면,  node.js 도 nest.js 와 비슷하게 모듈화해서 사용하는 방식이 효율적이다.

index.js 를 뿌리로 하여 연결된 모습이라 이해하면 편하다. 

// index.js
const module1 = require("resolver/module1")
const module2 = require("resolver/module2")

const typeDefs = [
  queries,
  mutations,
  module1.typeDefs,
  module2.typeDefs,
  // enums,
]

const resolvers = [
  module1.resolvers,
  module2.resolvers
]

const server = new ApolloServer({ typeDefs, resolvers });

server.listen().then(({ url }) => {
  console.log(`🚀  Server ready at ${url}`);
});

node.js의 뿌리인 index.js 는 다음과 같은 모습으로 간추릴 수 있다.

nest.js 는 ES6 방식으로 모듈을 'import' 해오는 것과 달리

node.js 는 CommonJS 방식이라고 하여, require 하여 모듈을 가져오는 방식을 사용한다.

(물론, node.js에서도 ES6 문법 방식을 적용할 수 있다.)

 

// example // module1.js
const { gql } = require("apollo-server");

const typeDefs = gql`
  type Example {
	id : ID!
    name : String!
  }
  input ExampleInput {
	name : String
  }
`;

const resolvers = {
  Query: {
    fetchExample: (parent, args) => db.getExample(args),
  },
  Mutation: {
    createExample: (parent, args) => db.postExample(args),
  },
};
module.exports = {
  typeDefs: typeDefs,
  resolvers: resolvers,
};

module1.js 의 파일에 대해 살펴보면 위와 같은 구조를 띈다.

module.exports 를 활용하여, typeDefs, resolvers 를 따로 내보낸 뒤 index.js 에 합류시킨다고 볼 수 있다.

 

재밌는 점은 여기서 끝나는 게 아니라, 추가로 query와 mutation 파일을 따로 구현해주어야 하는데, 다음과 같다.

// _queries.js
const { gql } = require("apollo-server");

const typeDefs = gql`
  type Query {
    fetchExample : Example
  }
`;

module.exports = typeDefs;

// _mutations.js
const { gql } = require("apollo-server");

const typeDefs = gql`
  type Mutation {
    createExample : Example
  }
`;

module.exports = typeDefs;

 

위와 같이 작성해야만 정상적으로 node.js의 graphQL을 완성할 수 있게 된다.

'개발 > node.js' 카테고리의 다른 글

Node.js - PM2  (0) 2023.04.20
Node.js, 미들웨어 & 라우터 핸들러  (0) 2023.04.13
ORM / Sequelize & typeORM  (0) 2023.01.29
NestJS - 기초 구조 / graphQL  (0) 2023.01.25
node.js - about TypeScript (타임스크립트)  (0) 2023.01.25
Comments