Files
2025-11-08 18:44:51 +09:00

75 lines
2.4 KiB
JavaScript

import { StringCodec, connect } from 'nats';
import { secrets } from './secret-manager.js';
import fs from 'fs/promises';
export class NatsClient {
client = null;
stringCodec = StringCodec();
async connect() {
const endpoint = secrets?.['NATS_ENDPOINT'];
const user = secrets?.['NATS_USER'];
const password = secrets?.['NATS_PASS'];
if (!endpoint || !user || !password) {
throw new Error('Missing NATS credentials in secrets');
}
const cacert = (await fs.readFile('internal-service-ca.pem')).toString();
this.client = await connect({
name: 'image-derivatives-generation-service',
servers: [endpoint],
tls: {
ca: cacert,
},
maxReconnectAttempts: -1,
reconnectTimeWait: 500,
reconnect: true,
pingInterval: 20000,
timeout: 5000,
user: user,
pass: password,
});
console.log('✓ NATS connected');
}
async subscribe(subject, handler) {
if (!this.client) {
throw new Error('NATS client not connected');
}
const subscription = this.client.subscribe(subject);
(async () => {
for await (const msg of subscription) {
try {
const data = JSON.parse(this.stringCodec.decode(msg.data));
await handler(data);
}
catch (error) {
console.error(`Error processing message from ${subject}:`, error);
}
}
})();
console.log(`✓ Subscribed to ${subject}`);
return subscription;
}
async publish(subject, data) {
if (!this.client) {
throw new Error('NATS client not connected');
}
this.client.publish(subject, this.stringCodec.encode(JSON.stringify(data)));
await this.client.flush();
}
async close() {
if (!this.client)
return;
try {
const closed = this.client.closed();
await this.client.drain();
const err = await closed;
if (err)
console.error('NATS closed with error:', err);
}
catch (e) {
try {
await this.client.close();
}
catch { }
}
}
}
//# sourceMappingURL=nats.js.map