koa2 + apollo-server-koa + mongoose 接口

2022-04-25 16:35:34 浏览数 (1)

koa2 apollo-server-koa mongoose 接口

代码语言:javascript复制
yarn add koa koa-router koa-body apollo-server-koa@rc

app.js

代码语言:javascript复制
// app.js
const { ApolloServer, gql } = require('apollo-server-koa');
const Koa = require('koa');
const Router = require('koa-router');
const body = require('koa-body');
const app = new Koa();
const router = new Router();

router.get('/', ctx => {
    ctx.body = 'hello';
});

const books = [{
    title: 'Harry Potter and the Chamber of Secrets',
    author: 'J.K. Rowling',
}, {
    title: 'Jurassic Park',
    author: 'Michael Crichton',
}];


const typeDefs = gql`
  # 模型
  type Book {
    title: String
    author: String
  }

  # 查询
  type Query {
    books: [Book]
  }
`;

// 解析器(决定查询,突变)返回什么数据
const resolvers = {
    Query: {
        books: () => books,
    },
};

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

// 这里把 server 绑定到 koa 路由里
server.applyMiddleware({ app });

app.use(body()).use(router.routes());
app.listen(3010, () => {
    console.log(`


	

0 人点赞