feat(api): add shared infrastructure
This commit is contained in:
1 parent
f24674b12c
commit
2e311d9cbf
10 files changed
+1088
No files matched your search
@@ -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
|
||||
}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user