47 lines
1.5 KiB
TypeScript
47 lines
1.5 KiB
TypeScript
import { INestApplicationContext } from '@nestjs/common';
|
|
import { IoAdapter } from '@nestjs/platform-socket.io';
|
|
import { createAdapter } from '@socket.io/redis-adapter';
|
|
import type { ServerOptions } from 'socket.io';
|
|
import {
|
|
AuctionRedisService,
|
|
type AuctionRedisClient,
|
|
} from './modules/auction/redis/auction-redis.service';
|
|
|
|
type RedisAdapterConstructor = ReturnType<typeof createAdapter>;
|
|
type DuplicatedRedisClient = ReturnType<AuctionRedisClient['duplicate']>;
|
|
|
|
export class RedisIoAdapter extends IoAdapter {
|
|
private adapterConstructor?: RedisAdapterConstructor;
|
|
private subClient?: DuplicatedRedisClient;
|
|
|
|
constructor(private readonly app: INestApplicationContext) {
|
|
super(app);
|
|
}
|
|
|
|
public async connectToRedis(): Promise<void> {
|
|
const auctionRedisService = this.app.get(AuctionRedisService);
|
|
const pubClient = auctionRedisService.raw();
|
|
this.subClient = pubClient.duplicate();
|
|
await this.subClient.connect();
|
|
this.adapterConstructor = createAdapter(pubClient, this.subClient);
|
|
}
|
|
|
|
override createIOServer(port: number, options?: ServerOptions) {
|
|
const server = super.createIOServer(port, options);
|
|
if (this.adapterConstructor) {
|
|
server.adapter(this.adapterConstructor);
|
|
}
|
|
return server;
|
|
}
|
|
|
|
override close(server: unknown) {
|
|
const closeResult = super.close(server as never);
|
|
if (this.subClient) {
|
|
void this.subClient.quit().catch(() => {
|
|
this.subClient?.destroy();
|
|
});
|
|
}
|
|
return closeResult;
|
|
}
|
|
}
|