爲了學習nestjs graphql grpc 微服務方面的知識,具體grpc和graphql的語法再以後在作詳細分析git
npm i -g @nestjs/cli nest new project-name
建立graphql-config.service.ts文件,用於graphql的配置及編寫過濾器的邏輯github
@Injectable() export class GraphQLConfigService implements GqlOptionsFactory { constructor() {} createGqlOptions(): GqlModuleOptions { return { typePaths: [join(process.cwd(), "./graphqls/*.graphql")], // 配置的graphql文件地址 installSubscriptionHandlers: true, definitions: { path: join(process.cwd(), "src/graphql.schema.ts"), // 解析以後的文件地址 outputAs: "class" }, context: async ({ req }) => { // 過濾器 let user = Jwt.verifyToken(req.headers.authorization); // 業務邏輯 return { user }; } }; } }
添加進app.module.ts裏npm
@Module({ imports: [ GraphQLModule.forRootAsync({ imports: [ApplicationModule], useClass: GraphQLConfigService }), ], }) export class ApplicationModule {}
建立文件xxx.resolvers.tsbootstrap
@Query('getUser') async getUser() { return {}; }
首先,建立一個子項目xxxapi
子項目
建立grpc.options.ts文件,用於init鏈接的配置app
export const grpcClientOptions: ClientOptions = { transport: Transport.GRPC, options: { url: 「localhost:50051」, // 服務地址 package: 「xxx」, protoPath: join(__dirname, './xxx.proto'), }, };
建立接口, 注意這裏的首字母會被自動裝爲大寫async
@GrpcMethod("UserService") async addUser(data: User): Promise<any> { return data }
在main.ts引入微服務
import { grpcClientOptions } from './grpc.options'; async function bootstrap() { const app = await NestFactory.create(AppModule); app.connectMicroservice(grpcClientOptions); await app.startAllMicroservicesAsync(); } bootstrap();
其餘微服務或是apigateway調用是建立一個學習
const grpcClientOptions: ClientOptions = { transport: Transport.GRPC, options: { url: grpcServe.user.url, package: grpcServe.user.package, protoPath: join(__dirname, '../../common/proto/user.proto'), }, }; @Injectable() export class ClentServe { constructor() {} @Client(grpcClientOptions) public readonly client: ClientGrpc; }
demo地址url