Express + GraphQL + MongoDB 시작하기 - 3

HOONEY·2022년 1월 4일
0

Express

목록 보기
3/5
post-thumbnail

GraphQL 설정 - user

  • src/graphql/schema.js 생성
  • src/graphql/userTypeDefs.js 생성
import { makeExecutableSchema } from "@graphql-tools/schema";
import { userTypeDefs } from "./userTypeDefs";
import { userResolvers } from "../resolvers/user";
export const schema = makeExecutableSchema({
  typeDefs: [userTypeDefs],
  resolvers: [userResolvers],
});
const jsSchema = makeExecutableSchema({
  typeDefs,
  resolvers, // optional
  logger, // optional
  resolverValidationOptions: {}, // optional
  parseOptions: {}, // optional
  inheritResolversFromInterfaces: false // optional
})
  • userTypeDefs.js에 하단의 코드를 입력한다.
export const userTypeDefs = `
type User {
    _id: ID
    email: String
    password: String!
    name: String
}
type Query {
    getUser(
        email: String!
        password: String!
    ): User
}
type Mutation {
    postUser(
        email: String!
        password: String
        name: String!
    ): User
}
`;
  • 간단한 설명으로 Type User는 _id, email, password, name의 내용을 가진 객체가 클라이언트로부터 넘어올 경우 받기 위한 DTO느낌이다.

  • Type Query는 CRUD 중 R에 해당하는 것으로, getUser라는 함수(Resolver에 생성할 예정)을 이용해 User 타입의 객체를 Read 하는 역할.

  • Type Mutation은 CRUD 중 CUD에 해당하는 것으로 postUser 함수(Resolver에 생성할 예정)를 이용해 ()안에 있는 변수들을 받는다. 타입은 마찬가지로 User타입. email:String!은 email라는 변수의 타입은 String이며 !는 required를 뜻한다.

  • 자세한 내용은 하단 링크 참조
    https://graphql-kr.github.io/learn/schema/

  • src/graphql/schema.js

  • src/graphql/userTypeDefs.js

리졸버 설정

  • src/resolvers/user.js 생성
export const userResolvers = {
    Query: {
    async getUser(_, {email, password}) {
    	... coding
        }
            },
    Mutation: {
    async postUser(_, {email, password, name}) {  
       	... coding
        }
    },
}
  • getUser()는 클라이언트로부터 받는 변수가 없기 때문에 괄호 안이 비어있지만, insertUser() 경우 3개의 변수를 받기 때문에 이렇게 작성했다.
  • src/resolvers/user.js

MongoDB에 저장할 Schema 생성

  • src/model/User.js 생성
import { Schema, model } from "mongoose";

const UserSchema = new Schema(
  {
    email: {
      type: String,
      require: true,
      unique: true,
    },
    password: {
      type: String,
      require: true,
    },
    name: {
      type: String,
      required: true,
    },
  },
);

export default model("user", UserSchema);

서버쪽 설정은 잠시 멈추고 화면쪽 설정을 진행

  • 리액트를 이용해서 작업하려 한다.

이어서

https://velog.io/@mkh1213/React-GraphQL-Typescript-%EC%8B%9C%EC%9E%91%ED%95%98%EA%B8%B0-1

profile
기록하는 블로그

0개의 댓글