본문 바로가기

GraphQL로 영화 API 만들기

#GraphQL로 영화 API 만들기

* type Query { } 는 필수값

 

terminal
npm init -y
npm i apollo-server graphql

npm i nodemon -D

new File : 
server.js

.gitignore -> node_modules/

그리고 새 git 레포지토리 초기화
git init .

package.json ->
 "scripts": {
    "dev": "nodemon server.js"
  },

"type": "module"
}

server.js ->
import {ApolloServer, gql} from "apollo-server";

terminal ->
npm run dev

 

* 터미널에서 새로운 폴더를 바로 만들고 싶을 때, bash사용해야 됨

 

If you want to use the touch command, use bash as your terminal. It will work then
터미널에서 touch(새로운 폴더 만들 때 사용하는 명령어)를 사용하려면, bash에서 사용해야함.

 

 

 

** type Query는 rest API에서 GET(실행하기)와 같음
** type Mutation(변화)은 rest API에서 POST(등록), PUT(업데이트) 등과 같이
   변화하는 것들은 저기 { } 안에다가 작성해줘야됨.

import {ApolloServer, gql} from "apollo-server";

const typeDefs = gql`
    type User {
        id: ID
        username: String
    }
    type Tweet {
        id: ID
        text: String
        author: User
    }

    type Query {
       allTweets: [Tweet]
       tweet(id:ID): Tweet
    }

    type Mutation {
        postTweet(text:String, userId: ID): Tweet
        deleteTweet(id:ID): Boolean
    }
`

const server = new ApolloServer({typeDefs})

server.listen().then(({url}) => {
    console.log(`Running on ${url}`)
})

 

* Array.prototype.find()

find() 메서드는 주어진 판별 함수를 만족하는 첫 번째 요소 을 반환합니다.

그런 요소가 없다면 undefined를 반환합니다.

= 가장 첫번째 요소의 값만 반환하기 때문에, 130이랑 44는 안됨.

 

* Array.prototype.filter()

filter() 메서드는 주어진 함수의 테스트를 통과하는 모든 요소를 모아 새로운 배열로 반환합니다.

 

음절이 6개 보다 많은 경우만 리턴함

 

* Documentation (Description 추가하기)

 

"""
여기 사이에 해당 코드에 대한 설명을 작성 할 수 있음
"""

const typeDefs = gql`
type User {
  id: ID!
  fullName: String!
  firstName: String!
"""
Is the sum of firstName + lastName as a String
"""
  lastName: String!
}`

 

""" """ 작성 후 나타나는 결과창(localhost:4000에서 실행 후)

 

* 최종(typeDefs, resolvers, Apolloserver)

 

import { ApolloServer, gql} from "apollo-server";

let tweets = [
  {
    id: "1",
    text: "first one",
    userId: "2"
  },
  {
    id: "2",
    text: "second one",
    userId: "1"
  }
]

let users = [{
  id:"1",
  firstName:"nico",
  lastName:"las"
},
{
  id: "2",
  firstName: "Elon",
  lastName: "Mask"
}]

const typeDefs = gql`
type User {
  id: ID!
  fullName: String!
  firstName: String!
"""
Is the sum of firstName + lastName as a String
"""
  lastName: String!
}
"""
Tweet object represents a resource for a Tweet
"""
 type Tweet {
  id: ID!
  text: String! 
  author: User
 }
 
 type Query {
    allUsers: [User!]!
    allTweets: [Tweet!]! 
    tweet(id: ID!): Tweet
  }
type Mutation {
  postTweet(text:String!, userId: ID!): Tweet!
"""
Deletes a Tweet if found, else returns false
"""
  deleteTweet(id: ID!): Boolean!
}
`
const resolvers = {
  Query: { 
    allTweets(){
      return tweets;
    },
    tweet(root, {id}){
      console.log(id)
    return tweets.find((tweet) => tweet.id === id)
    },
    allUsers(){
      console.log("allUsers called")
    return users;
    }
},
Mutation: {
  postTweet(_, {text, userId}){
    const newTweet = {
      id: tweets.length + 1,
      text
    }
    tweets.push(newTweet);
    return newTweet;
},
  deleteTweet(_, {id}){
  const tweet = tweets.find((tweet) => tweet.id === id)
  if(!tweet) return false;
  tweets = tweets.filter((tweet) => tweet.id !== id)
  return true;
},
},
 User: {
  fullName({firstName, lastName}){
    return `${firstName} ${lastName}`;
  },
},
  Tweet: {
     author({userId}){
      return users.find(user => user.id === userId);
     }
    }
  }



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

server.listen().then(({url})=> {
  console.log(`Running on ${url}`);
})