Nodejs Nestjs GraphQL订阅插件nestjs-mercurius的使用

Nodejs Nestjs GraphQL订阅插件nestjs-mercurius的使用
@nestjs/mercurius 是一个用于 NestJS 的 GraphQL 订阅插件。Mercurius 是一个基于 Apollo Server 和 GraphQL 的 Node.js 服务器库,支持 GraphQL 和 GraphQL Subscriptions。

以下是使用 @nestjs/mercurius 的基本步骤:

安装依赖

首先,你需要安装必要的依赖包:

npm install @nestjs/mercurius graphql apollo-server

配置模块

在你的 NestJS 应用中创建一个 GraphQL 模块,并配置 Mercurius:

import { Module } from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';
import { MercuriusFactory, MercuriusModule } from '@nestjs/mercurius';

@Module({
  imports: [
    GraphQLModule.forRoot({
      autoSchemaFile: 'schema.gql',
      context: ({ req }) => ({ req }),
    }),
    MercuriusModule.forRootAsync({
      useFactory: (factory: MercuriusFactory) => ({
        schema: factory.schema,
        graphiql: true,
        subscriptions: {
          'graphql-ws': true,
        },
      }),
      inject: [MercuriusFactory],
    }),
  ],
})
export class AppModule {}

创建 GraphQL 模型和类型

定义你的 GraphQL 模型和类型:

import { ObjectType, Field } from '@nestjs/graphql';

@ObjectType()
export class Message {
  @Field()
  content: string;

  @Field()
  createdAt: Date;
}

创建订阅

创建一个订阅来发布和订阅消息:

import { Resolver, Subscription } from '@nestjs/graphql';
import { PubSub } from 'graphql-subscriptions';

const pubSub = new PubSub();

@Resolver(() => Message)
export class MessageResolver {
  @Subscription(() => Message)
  messageCreated() {
    return pubSub.asyncIterator('messageCreated');
  }
}

发布消息

你可以通过调用 pubSub.publish 来发布消息:

pubSub.publish('messageCreated', { messageCreated: { content: 'Hello World!', createdAt: new Date() } });

订阅消息

客户端可以通过以下方式订阅消息:

subscription {
  messageCreated {
    content
    createdAt
  }
}

以上就是使用 @nestjs/mercurius 进行 GraphQL 订阅的基本步骤。你可以根据具体需求进一步扩展和定制。


3 回复

当然,让我用一点幽默来帮你搞定这个!

首先,确保你已经安装了@nestjs/mercurius。如果你还没安装,可以试试这个魔法命令:

npm install @nestjs/mercurius --save

接下来,你需要在你的模块中导入MercuriusModule。你可以这样干:

import { MercuriusModule } from '@nestjs/mercurius';

@Module({
  imports: [
    MercuriusModule.forRoot({
      // 这里是你的配置,比如GraphQL的端点、订阅选项等
    }),
  ],
})
export class AppModule {}

然后,在你的服务中定义你的订阅。想象一下,你正在召唤一个神秘的力量:

@Injectable()
export class CatsService {
  @Subscription(() => Cat)
  catAdded() {
    return this.catSubject.asObservable();
  }
}

最后,别忘了启动你的应用,让它像火箭一样飞起来!现在,去泡杯咖啡,享受你的订阅吧!

希望这能帮到你,如果还有问题,欢迎再来找我,我会带着更多的笑话和解决方案回来!


nestjs-mercurius 是一个用于 NestJS 的 GraphQL 订阅插件,基于 graphql-subscriptions。下面我将介绍如何在你的 NestJS 项目中使用 nestjs-mercurius 来实现 GraphQL 订阅。

安装依赖

首先,你需要安装必要的包:

npm install @nestjs/core @nestjs/graphql graphql apollo-server-express subscriptions-transport-ws nestjs-mercurius

配置 WebSocket 服务器

安装 subscriptions-transport-ws 以便客户端可以通过 WebSocket 连接到服务器。

// main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { WebSocketServer } from 'ws';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  const server = app.getHttpAdapter().getInstance();
  const webSocketServer = new WebSocket.Server({ server });
  
  app.useWebSocketAdapter(new MercuriusWsAdapter(webSocketServer));

  await app.listen(3000);
}
bootstrap();

创建 GraphQL 模式

接下来,创建一个简单的 GraphQL 模式并添加订阅。

// schema.graphql
type Subscription {
    newMessage: Message!
}

type Message {
    id: ID!
    content: String!
}

实现订阅

// message.resolver.ts
import { Resolver, ResolveProperty, Parent } from '@nestjs/graphql';
import { PubSub } from 'graphql-subscriptions';

const pubSub = new PubSub();

@Resolver('Message')
export class MessageResolver {

  messages = [
    { id: '1', content: 'Hello' },
    { id: '2', content: 'World' }
  ];

  @ResolveProperty('newMessage')
  newMessage() {
    return this.messages[0];
  }

  sendMessage(content: string) {
    const message = { id: (this.messages.length + 1).toString(), content };
    this.messages.push(message);
    pubSub.publish('newMessage', { newMessage: message });
    return message;
  }
}

启动服务器

现在你可以启动你的 NestJS 服务器,并且应该能够在客户端通过 WebSocket 订阅 newMessage 事件。

客户端连接

客户端可以使用像 subscriptions-transport-ws 的库来订阅这些消息。

const WebSocket = require('ws');
const ws = new WebSocket('ws://localhost:3000/graphql');

ws.on('open', () => {
  ws.subscribe('newMessage');
});

ws.on('message', (data) => {
  console.log(data); // 新消息的数据
});

这只是一个基本的示例,你可以根据自己的需求进行调整和扩展。

NestJS GraphQL结合@nestjs/mercurius可以实现强大的GraphQL订阅功能。首先安装@nestjs/mercurius和其他必要依赖。然后,在模块中配置Mercurius模块,并定义你的GraphQL模式包括订阅类型。在服务层,你可以使用Mercurius提供的上下文访问WebSocket连接。最后,在你的订阅解析器中,使用pubSub实例发布和监听事件。确保WebSocket服务器正确启动以支持实时更新。

回到顶部