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 } */
2) กำหนด schema เริ่มต้น
schema.ts
import { GraphQLObjectType, GraphQLSchema } from 'graphql' import GetUser from '.......' export default new GraphQLSchema({ query: new GraphQLObjectType({ name: 'Query', fields: { // สามารถเพิ่มประเภทของการ Query ได้เรื่อย ๆ GetUser, . .. ... } }), })
3) กำหนด Query GetUser
import User from '.......' export default { type: User, resolve: async () => ({ id: "test_id", name: "test_name" }), }
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' } } }), })
Top comments (0)