feat(api): add shared infrastructure

This commit is contained in:
dahyeon committed 2026-04-06 23:48:00 +09:00
1 parent f24674b12c
commit 2e311d9cbf
10 files changed
+1088

No files matched your search

@@ -0,0 +1 @@
export const NATS_CLIENT = Symbol('NATS_CLIENT');
@@ -0,0 +1,45 @@
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] = await Promise.all([
secretService.get<string>('NATS_ENDPOINT'),
secretService.get<string>('NATS_USER'),
secretService.get<string>('NATS_PASS'),
secretService.get<string>('SERVICE_NAME'),
]);
return connect({
name: serviceName,
servers: [endpoint],
maxReconnectAttempts: -1,
reconnectTimeWait: 500,
reconnect: true,
pingInterval: 20000,
timeout: 5000,
user,
pass: password,
});
},
},
NatsService,
],
exports: [NatsService, NATS_CLIENT],
})
export class NatsModule {}
@@ -0,0 +1,117 @@
import {
Inject,
Injectable,
Logger,
OnModuleDestroy,
} from '@nestjs/common';
import { StringCodec } from 'nats';
import type { Msg, NatsConnection, Subscription } from 'nats';
import { NATS_CLIENT } from './nats.constants';
export type NatsMessageHandler<T = unknown> = (
data: T,
msg: Msg,
) => Promise<void> | void;
@Injectable()
export class NatsService implements OnModuleDestroy {
private readonly logger = new Logger(NatsService.name);
private readonly stringCodec = StringCodec();
private readonly subscriptions = new Set<Subscription>();
constructor(
@Inject(NATS_CLIENT) private readonly natsClient: NatsConnection,
) {}
async onModuleDestroy() {
for (const sub of this.subscriptions) {
try {
sub.unsubscribe();
} catch {
// ignore
}
}
this.subscriptions.clear();
try {
const closed = this.natsClient.closed();
await this.natsClient.drain();
const err = await closed;
if (err) this.logger.error(`NATS closed with error: ${err}`);
} catch {
try {
await this.natsClient.close();
} catch {
// ignore
}
}
}
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();
}
public subscribe<T = unknown>(
subject: string,
handler: NatsMessageHandler<T>,
options?: { queue?: string },
): Subscription {
const sub = this.natsClient.subscribe(subject, {
queue: options?.queue,
});
this.subscriptions.add(sub);
void this.consumeSubscription(sub, handler);
return sub;
}
private async consumeSubscription<T>(
sub: Subscription,
handler: NatsMessageHandler<T>,
): Promise<void> {
try {
for await (const msg of sub) {
await this.dispatch(msg, handler);
}
} catch (err) {
this.logger.error(
`NATS subscription on subject="${sub.getSubject()}" terminated: ${
(err as Error)?.message ?? err
}`,
);
} finally {
this.subscriptions.delete(sub);
}
}
private async dispatch<T>(
msg: Msg,
handler: NatsMessageHandler<T>,
): Promise<void> {
let data: T;
try {
const decoded = this.stringCodec.decode(msg.data);
data = JSON.parse(decoded) as T;
} catch (err) {
this.logger.warn(
`Failed to decode NATS message on subject="${msg.subject}": ${
(err as Error)?.message ?? err
}`,
);
return;
}
try {
await handler(data, msg);
} catch (err) {
this.logger.error(
`Handler error on subject="${msg.subject}": ${
(err as Error)?.stack ?? err
}`,
);
}
}
}