Skip to content

Commit 8cb2e4e

Browse files
committed
feat: Refactor payload encoding/decoding for extensibility
1 parent 4ed13a7 commit 8cb2e4e

2 files changed

Lines changed: 9 additions & 5 deletions

File tree

src/queue.ts

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -97,8 +97,8 @@ export class Queue<
9797
}
9898

9999
/** Decode the payload, stripping away the outer JSON encoding */
100-
static decodePayload<T>(s: string | null) {
101-
return JSON.parse(s ?? "{}")._ as T;
100+
static decodePayload<T>(s: string | null | unknown) {
101+
return JSON.parse((s as string) ?? "{}")._ as T;
102102
}
103103

104104
constructor(driver: Driver, name: string, options?: QueueOptions) {
@@ -117,6 +117,8 @@ export class Queue<
117117
},
118118
statInterval:
119119
options?.statInterval === 0 ? 0 : options?.statInterval ?? 5,
120+
decodePayload: options?.decodePayload ?? this.constructor.decodePayload,
121+
encodePayload: options?.encodePayload ?? this.constructor.encodePayload,
120122
};
121123

122124
// initialize stats
@@ -242,7 +244,7 @@ export class Queue<
242244
ref: v.ref ?? v4(),
243245
ack: null,
244246
visible: begin,
245-
payload: Queue.encodePayload(v.payload),
247+
payload: this.opts.encodePayload(v.payload),
246248
attempts: {
247249
tries: 0,
248250
max: v.retries === 0 ? 0 : v.retries ?? 5,
@@ -422,7 +424,7 @@ export class Queue<
422424
driver: this.driver,
423425
name: this.name,
424426
doc,
425-
payload: Queue.decodePayload<TData>(doc.payload),
427+
payload: this.opts.decodePayload<TData>(doc.payload),
426428
handler,
427429
emitter: this.events,
428430
visibility,

src/types.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@ export interface QueueOptions {
2222
* seconds. Defaults to `5`
2323
*/
2424
statInterval?: number;
25+
decodePayload: <T>(payload: unknown) => T;
26+
encodePayload: (payload: unknown) => unknown;
2527
}
2628

2729
export interface ProcessorConfig<C> {
@@ -131,7 +133,7 @@ export interface QueueDoc {
131133
/** If a job is marked dead, this will contain the error information */
132134
error?: string;
133135
/** The job's payload. If an object or object-like value is passed, it will be passed through JSON.stringify */
134-
payload: string | null;
136+
payload: string | null | unknown;
135137
/** Information on the number of attempts and max allowed */
136138
attempts: {
137139
/** The current attempt number */

0 commit comments

Comments
 (0)