|
| 1 | +import { MutationError, ErrorCodeEnum } from './MutationError'; |
| 2 | +import { getBullConnection } from './getBullConnection'; |
| 3 | +import { Options } from '../definitions'; |
| 4 | + |
| 5 | +type Record = { |
| 6 | + id: string; |
| 7 | + nextTimestamp: string; |
| 8 | +}; |
| 9 | + |
| 10 | +type Result = { |
| 11 | + first: Record; |
| 12 | + last: Record; |
| 13 | + fixLast: Record; |
| 14 | +}; |
| 15 | + |
| 16 | +export async function addFixRecordToDelayStream( |
| 17 | + prefix: string, |
| 18 | + queueName: string, |
| 19 | + opts: Options, |
| 20 | + checkExistence: boolean = true |
| 21 | +): Promise<Result> { |
| 22 | + const redis = getBullConnection(opts); |
| 23 | + |
| 24 | + const fullQueueName = [prefix, queueName].join(':'); |
| 25 | + |
| 26 | + if (checkExistence) { |
| 27 | + const queueExists = await redis.exists([fullQueueName, 'meta'].join(':')); |
| 28 | + |
| 29 | + if (!queueExists) { |
| 30 | + throw new MutationError('Queue not found!', ErrorCodeEnum.QUEUE_NOT_FOUND); |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + const streamName = fullQueueName + ':delay'; |
| 35 | + |
| 36 | + const first = await redis.xrange(streamName, '-', '+', 'count', 1); |
| 37 | + const last = await redis.xrevrange(streamName, '+', '-', 'count', 1); |
| 38 | + const defaultRec = { |
| 39 | + id: '0-0', |
| 40 | + nextTimestamp: '', |
| 41 | + }; |
| 42 | + const fixLastNextTimestamp = `${Date.now()}`; |
| 43 | + const fixLastId = await redis.xadd(streamName, '*', 'nextTimestamp', fixLastNextTimestamp); |
| 44 | + |
| 45 | + function readRecords(records: [string, string[]][]): Record { |
| 46 | + if (records.length > 0) { |
| 47 | + return { |
| 48 | + id: records[0][0], |
| 49 | + nextTimestamp: records[0][1][1], |
| 50 | + }; |
| 51 | + } else { |
| 52 | + return defaultRec; |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + return { |
| 57 | + first: readRecords(first), |
| 58 | + last: readRecords(last), |
| 59 | + fixLast: { |
| 60 | + id: fixLastId, |
| 61 | + nextTimestamp: fixLastNextTimestamp, |
| 62 | + }, |
| 63 | + }; |
| 64 | +} |
0 commit comments