Redningsselskapet / nestjs-plugins

Plugins for NestJS framework
ISC License
27 stars 22 forks source link

Add Parameter to Configure Custom Codec #61

Open arinanto opened 5 months ago

arinanto commented 5 months ago

Add configuration option to use custom codec by implementing NATS codec interface.

Example usage:

// ...other imports omitted

// Custom codec (in this case CBOR based)
import CBOR from "cbor";
import { Codec } from "nats";

class CborCodec implements Codec<unknown> {
  encode(d: unknown): Uint8Array {
    return CBOR.encodeOne(d, { highWaterMark: 1049000 });
  }

  decode(a: Uint8Array): unknown {
    return CBOR.decodeFirstSync(a, { highWaterMark: 1049000 }) as unknown;
  }
}

// Module declaration
@Global()
@Module({
  imports: [
    NatsJetStreamTransport.registerAsync({
      inject: [ConfigService],
      useFactory: (configService: ConfigService) => {
        return {
          connectionOptions: {
            servers: "nats://broker.example.com:4222",
            codec: new CborCodec(),
          },
        };
      },
    }),
  ],
  providers: [NatsService],
  exports: [NatsService],
})
export class NatsGlobalModule {}