Skip to content

Commit 6133fc9

Browse files
authored
Merge pull request #18 from reedsy/ttl-option
✨ Allow optional TTL on `deleted` field
2 parents 8393845 + c26194d commit 6133fc9

File tree

2 files changed

+11
-3
lines changed

2 files changed

+11
-3
lines changed

mongodb-queue.ts

+10-2
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
*
1111
**/
1212

13-
import {Collection, Db, Filter, FindOneAndUpdateOptions, ObjectId, Sort, UpdateFilter, WithId} from 'mongodb';
13+
import {Collection, CreateIndexesOptions, Db, Filter, FindOneAndUpdateOptions, ObjectId, Sort, UpdateFilter, WithId} from 'mongodb';
1414

1515
function now(): string {
1616
return (new Date()).toISOString();
@@ -25,6 +25,7 @@ export type QueueOptions = {
2525
delay?: number;
2626
deadQueue?: MongoDBQueue;
2727
maxRetries?: number;
28+
expireAfterSeconds?: number;
2829
};
2930

3031
export type AddOptions = {
@@ -64,6 +65,7 @@ export class MongoDBQueue<T = any> {
6465
private readonly delay: number;
6566
private readonly maxRetries: number;
6667
private readonly deadQueue: MongoDBQueue;
68+
private readonly expireAfterSeconds: number;
6769

6870
public constructor(db: Db, name: string, opts: QueueOptions = {}) {
6971
if (!db) {
@@ -76,6 +78,7 @@ export class MongoDBQueue<T = any> {
7678
this.col = db.collection(name);
7779
this.visibility = opts.visibility || 30;
7880
this.delay = opts.delay || 0;
81+
this.expireAfterSeconds = opts.expireAfterSeconds;
7982

8083
if (opts.deadQueue) {
8184
this.deadQueue = opts.deadQueue;
@@ -84,10 +87,15 @@ export class MongoDBQueue<T = any> {
8487
}
8588

8689
public async createIndexes(): Promise<void> {
90+
const deletedOptions: CreateIndexesOptions = {sparse: true};
91+
if (typeof this.expireAfterSeconds === 'number') {
92+
deletedOptions.expireAfterSeconds = this.expireAfterSeconds;
93+
}
94+
8795
await Promise.all([
8896
this.col.createIndex({visible: 1}, {sparse: true}),
8997
this.col.createIndex({ack: 1}, {unique: true, sparse: true}),
90-
this.col.createIndex({deleted: 1}, {sparse: true}),
98+
this.col.createIndex({deleted: 1}, deletedOptions),
9199

92100
// Index for efficient counts on in-flight
93101
this.col.createIndex({visible: 1, ack: 1}, {

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@reedsy/mongodb-queue",
3-
"version": "8.0.0",
3+
"version": "8.1.0",
44
"description": "Message queues which uses MongoDB.",
55
"main": "mongodb-queue.js",
66
"scripts": {

0 commit comments

Comments
 (0)