initial commit
This commit is contained in:
commit
e3da5d83b6
49 files changed
+10011
No files matched your search
@@ -0,0 +1 @@
|
||||
export const NATS_CLIENT = Symbol('NATS_CLIENT');
|
||||
@@ -0,0 +1,50 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import fs from 'fs/promises';
|
||||
import { connect } from 'nats';
|
||||
import type { NatsConnection } from 'nats';
|
||||
import { SecretModule } from '../secret/secret.module';
|
||||
import { SecretService } from '../secret/secret.service';
|
||||
import { NATS_CLIENT } from './nats.constants';
|
||||
import { NatsService } from './nats.service';
|
||||
|
||||
@Module({
|
||||
imports: [SecretModule],
|
||||
providers: [
|
||||
{
|
||||
provide: NATS_CLIENT,
|
||||
inject: [SecretService],
|
||||
useFactory: async (
|
||||
secretService: SecretService,
|
||||
): Promise<NatsConnection> => {
|
||||
await secretService.ready();
|
||||
|
||||
const [endpoint, user, password, serviceName, cacert] =
|
||||
await Promise.all([
|
||||
secretService.get<string>('NATS_ENDPOINT'),
|
||||
secretService.get<string>('NATS_USER'),
|
||||
secretService.get<string>('NATS_PASS'),
|
||||
secretService.get<string>('SERVICE_NAME'),
|
||||
fs.readFile('internal-service-ca.pem', 'utf8'),
|
||||
]);
|
||||
|
||||
return connect({
|
||||
name: serviceName,
|
||||
servers: [endpoint],
|
||||
tls: {
|
||||
ca: cacert,
|
||||
},
|
||||
maxReconnectAttempts: -1,
|
||||
reconnectTimeWait: 500,
|
||||
reconnect: true,
|
||||
pingInterval: 20000,
|
||||
timeout: 5000,
|
||||
user,
|
||||
pass: password,
|
||||
});
|
||||
},
|
||||
},
|
||||
NatsService,
|
||||
],
|
||||
exports: [NatsService, NATS_CLIENT],
|
||||
})
|
||||
export class NatsModule {}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { Inject, Injectable, OnModuleDestroy } from '@nestjs/common';
|
||||
import { StringCodec } from 'nats';
|
||||
import type { NatsConnection } from 'nats';
|
||||
import { NATS_CLIENT } from './nats.constants';
|
||||
|
||||
@Injectable()
|
||||
export class NatsService implements OnModuleDestroy {
|
||||
private readonly stringCodec = StringCodec();
|
||||
|
||||
constructor(
|
||||
@Inject(NATS_CLIENT) private readonly natsClient: NatsConnection,
|
||||
) {}
|
||||
|
||||
async onModuleDestroy() {
|
||||
try {
|
||||
// 안전 종료: drain -> closed 대기
|
||||
const closed = this.natsClient.closed();
|
||||
await this.natsClient.drain();
|
||||
const err = await closed;
|
||||
if (err) console.error('NATS closed with error:', err);
|
||||
} catch (e) {
|
||||
// drain 실패 시 강제 close
|
||||
try {
|
||||
await this.natsClient.close();
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
|
||||
public async publish<T = unknown>(subject: string, data: T): Promise<void> {
|
||||
this.natsClient.publish(
|
||||
subject,
|
||||
this.stringCodec.encode(JSON.stringify(data)),
|
||||
);
|
||||
await this.natsClient.flush();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user