Skip to content
This repository has been archived by the owner on May 22, 2024. It is now read-only.

egomobile/node-queue-mongo

Repository files navigation

npm last build PRs Welcome

@egomobile/queue-mongo

Queue storage for @egomobile/queue, using MongoDB as backend.

Install

Execute the following command from your project folder, where your package.json file is stored:

npm install --save @egomobile/queue-mongo

Usage

import { Queue } from "@egomobile/queue";
import {
  IMongoQueueStorageOptions,
  MongoQueueStorage,
} from "@egomobile/queue-mongo";
import { MongoClient } from "mongodb";

let queue!: Queue;

async function main() {
  const url = process.env.MONGO_URL?.trim() || "mongodb://localhost:27017";
  const mongoClient = new MongoClient(url);
  const db = mongoClient.db("my_database");

  const storageOptions: IMongoQueueStorageOptions = {
    getDb: () => {
      return db;
    },
  };

  queue = new Queue({
    storageClass: MongoQueueStorage,
    storageClassArgs: [storageOptions],
  });

  // register 2 tasks at once
  queue.register({
    // 1st
    myTask1: async (context) => {
      console.log("This is task 1 with following data:", context.data);
    },

    // 2nd
    myTask2: async (context) => {
      console.log("This is task 2 with following data:", context.data);
    },
  });

  // anything is prepared, lets start the queue
  await queue.start();

  // first enqueue 2nd task
  await queue.enqueue("myTask2", {
    data: {
      buzz: 5979,
    },
  });
  // then 1st one
  await queue.enqueue("myTask1", {
    data: {
      foo: "bar",
    },
  });
}

main().catch(console.error);

Documentation

The API documentation can be found here.