diff --git a/src/queue.ts b/src/queue.ts index 5ccb4e0..e674f14 100644 --- a/src/queue.ts +++ b/src/queue.ts @@ -92,13 +92,13 @@ export class Queue< protected stats: QueueStats; /** Wrap the payload in a JSON encoding */ - static encodePayload(p: unknown) { + static encodePayload(this: void, p: unknown) { return JSON.stringify({ _: p }); } /** Decode the payload, stripping away the outer JSON encoding */ - static decodePayload(s: string | null) { - return JSON.parse(s ?? "{}")._ as T; + static decodePayload(this: void, s: string | null | unknown) { + return JSON.parse((s as string) ?? "{}")._ as T; } constructor(driver: Driver, name: string, options?: QueueOptions) { @@ -117,6 +117,12 @@ export class Queue< }, statInterval: options?.statInterval === 0 ? 0 : options?.statInterval ?? 5, + decodePayload: + options?.decodePayload ?? + (this.constructor as typeof Queue).decodePayload, + encodePayload: + options?.encodePayload ?? + (this.constructor as typeof Queue).encodePayload, }; // initialize stats @@ -242,7 +248,7 @@ export class Queue< ref: v.ref ?? v4(), ack: null, visible: begin, - payload: Queue.encodePayload(v.payload), + payload: this.opts.encodePayload(v.payload), attempts: { tries: 0, max: v.retries === 0 ? 0 : v.retries ?? 5, @@ -422,7 +428,7 @@ export class Queue< driver: this.driver, name: this.name, doc, - payload: Queue.decodePayload(doc.payload), + payload: this.opts.decodePayload(doc.payload), handler, emitter: this.events, visibility, diff --git a/src/types.ts b/src/types.ts index 831c395..29155c3 100644 --- a/src/types.ts +++ b/src/types.ts @@ -22,6 +22,8 @@ export interface QueueOptions { * seconds. Defaults to `5` */ statInterval?: number; + decodePayload: (payload: unknown) => T; + encodePayload: (payload: unknown) => unknown; } export interface ProcessorConfig { @@ -131,7 +133,7 @@ export interface QueueDoc { /** If a job is marked dead, this will contain the error information */ error?: string; /** The job's payload. If an object or object-like value is passed, it will be passed through JSON.stringify */ - payload: string | null; + payload: string | null | unknown; /** Information on the number of attempts and max allowed */ attempts: { /** The current attempt number */