DEV Community

Perm Chao
Perm Chao

Posted on

1

หัดใช้งาน GraphQL ด้วย Apollo Server

1) เริ่มต้นการทำงานของ Apollo Server ด้วย Koa

app.ts

/*
import Koa from 'koa'
import Router from 'koa-router'
*/
// จาก lib `apollo-server-koa`
import { ApolloServer } from 'apollo-server-koa'

// ไฟล์นี้สร้างในข้อสอง
import graphqlSchema from './graphqlSchema'

/*
async function createApp(): Promise<Koa> {

 const application = new Koa()
 const router = new Router()
 */


 const graphqlServer = new ApolloServer({
  introspection: true,
  schema: graphqlSchema,
  context: ({ ctx }) => ctx
 })

 await graphqlServer.start()

 router.post("/graphql", graphqlServer.getMiddleware())
 router.get("/graphql", graphqlServer.getMiddleware())

 /*
 application.use(router.routes())
 return application

}
*/
Enter fullscreen mode Exit fullscreen mode

2) กำหนด schema เริ่มต้น

schema.ts

import { GraphQLObjectType, GraphQLSchema } from 'graphql'
import GetUser from '.......'

export default new GraphQLSchema({
  query: new GraphQLObjectType({
    name: 'Query',
    fields: {
      // สามารถเพิ่มประเภทของการ Query ได้เรื่อย ๆ
      GetUser,
      .
      ..
      ...
    }
  }),
})
Enter fullscreen mode Exit fullscreen mode

3) กำหนด Query GetUser

import User from '.......'

export default {
  type: User,
  resolve: async () => ({
    id: "test_id",
    name: "test_name"
  }),
}
Enter fullscreen mode Exit fullscreen mode

4) กำหนด Schema User

import { GraphQLObjectType, GraphQLID, GraphQLString } from "graphql"

export const User = new GraphQLObjectType({
  name: 'User',
  fields: () => ({
    id: {
      type: GraphQLID,
    },
    name: {
      type: GraphQLString,
      resolve: async args => {
        // args จะเป็น resolve ของ query สามารถเอาไปใช้งานต่อได้
        console.log(args) // { id: 'test_id', name: 'test_name' }
        return 'finish'
      }
    }
  }),
})

Enter fullscreen mode Exit fullscreen mode

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay