midwayjs / midway

🍔 A Node.js Serverless Framework for front-end/full-stack developers. Build the application for next decade. Works on AWS, Alibaba Cloud, Tencent Cloud and traditional VM/Container. Super easy integrate with React and Vue. 🌈
https://www.midwayjs.org/
MIT License
7.34k stars 573 forks source link

请问midway2使用graphql有没有实例可以参考? #794

Closed exment closed 3 years ago

exment commented 3 years ago

midway2使用graphql总是不成功。

exment commented 3 years ago
import * as path from 'path';
import { Context, async, Middleware } from '@ali/midway';
import { ApolloServer, ServerRegistration } from 'apollo-server-koa';
import { buildSchemaSync } from 'type-graphql';

export default (options: ServerRegistration, ctx: Context) => {
  const server = new ApolloServer({
    schema: buildSchemaSync({
      resolvers: [path.resolve(ctx.baseDir, 'resolver/*.ts')],
      container: ctx.applicationContext
    })
  });
  return server.getMiddleware(options);
};

midway1原来的graphql中间件可以这样写

czy88840616 commented 3 years ago

没有本质差异,但是 egg 的函数式中间件得写到 src/app/middleware 下。https://www.yuque.com/midwayjs/midway_v2/eggjs#ML31g

exment commented 3 years ago

请问如果在src/middleware下如何实现?

czy88840616 commented 3 years ago

那要写成 class,一样的,本质是 server.getMiddleware 返回了一个中间件。


@Provide()
export class ReportMiddleware implements IWebMiddleware {

  @Inject()
  baseDir: string;

  @App()
  app;

  resolve() {
    const server = new ApolloServer({
      schema: buildSchemaSync({
        resolvers: [path.resolve(this.baseDir, 'resolver/*.ts')],
        container: app.getApplicationContext()
      })
    });
    return server.getMiddleware(options);
  }

}
exment commented 3 years ago

非常感谢!