LoginSignup
1

More than 1 year has passed since last update.

Axios で ApolloServer からデータ取得する

Last updated at Posted at 2022-03-14

簡単な内容だが、備忘録。

Apollo Server とは?

GraphQL サーバーを簡単に作れる技術。
簡単なデータの読み取りと書き込みは、

index.ts
import {ApolloServer} from "apollo-server"
import {IResolvers} from "@graphql-tools/utils"

let hello = [ {text: "Hello world!"} ]

const typeDefs = gql`
  type Hello {
    text: String
  }
  type Query {
    hellos: [Hello!]!
  }
  type Mutation {
    addHello(text: String!): Hello!
  }
`

const resolvers: IResolvers = {
  Query: { 
    hellos: () => {
      return hello
    }
  },
  Mutation: {
    addHello: (root, args) => {
      const h = {text: args.text}
      hello = [...hello, h]
      return h
    }
  }
}

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

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

みたいな感じで、スキーマとリソルバを定義することで 作れる。

Axios でデータ取得

上のサーバーから、Axios でのデータ取得は、

index.js
import axios from "axios"

// データ取得
const result = axios({
  url: "http://localhost:4000/graphql",
  method: "POST",
  data: {
    query: `
    query {
      hellos {
        text
      }
    }
`
  }
})

result.then((r) => {console.log(r.data.data.hellos)})

Axios でのデータ書き込みは、

index.js
import axios from "axios"

const result = axios({
  url: "http://localhost:4000/graphql",
  method: "POST",
  data: {
    query: `
      mutation addHello($text: String) {
        addHello(text: $text) {
          text
        }
      }
`,
    variables: {text: "hello"}
  }
})

と、query と query の $text に挿入される variables を定義することで、できる。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1