queue-manager-pro
Version:
A flexible, TypeScript-first queue/task manager with pluggable backends ,dynamic persistence storage and event hooks.
69 lines • 2.51 kB
JavaScript
import fs from 'fs/promises';
import path from 'path';
import { BaseQueueRepository } from './base.repository.js';
import { FileRepositoryLoadError, FileRepositoryReadError, FileRepositoryTypeMismatchError } from '../util/errors.js';
export class FileQueueRepository extends BaseQueueRepository {
filePath;
constructor(filePath, maxRetries, maxProcessingTime) {
super(maxRetries, maxProcessingTime);
this.filePath = filePath;
}
async deleteTask(id, hardDelete) {
const tasks = await this.loadTasks();
const index = tasks.findIndex(task => task.id === id);
if (index === -1)
return undefined;
const deletedTask = tasks[index];
if (hardDelete) {
tasks.splice(index, 1);
}
else if (deletedTask) {
deletedTask.status = 'deleted';
}
await this.saveTasks(tasks);
return deletedTask;
}
// Load tasks from file, optionally filter by status
async loadTasks(status) {
try {
if (path.extname(this.filePath) !== '.json') {
throw new FileRepositoryTypeMismatchError();
}
const data = await fs.readFile(this.filePath, 'utf-8');
const tasks = JSON.parse(data || '[]');
if (status) {
return tasks.filter(t => t.status === status);
}
return tasks;
}
catch (err) {
const error = err;
if (error.code === 'ENOENT') {
throw new FileRepositoryLoadError(this.filePath, error.path ?? 'unknown');
}
throw new FileRepositoryReadError(this.filePath, error.message);
}
}
// Save all tasks to file (ignore status param for file)
async saveTasks(tasks, _status) {
try {
const tmpPath = this.filePath + '.tmp';
const dir = path.dirname(tmpPath);
await fs.mkdir(dir, { recursive: true });
await fs.writeFile(tmpPath, JSON.stringify(tasks, null, 2));
await fs.rename(tmpPath, this.filePath); // Atomic swap
return tasks;
}
catch (error) {
console.error('Error saving tasks to file:', error);
throw error;
}
}
// Add a new task to the file
async enqueue(task) {
const tasks = await this.loadTasks();
tasks.push(task);
await this.saveTasks(tasks);
}
}
//# sourceMappingURL=file.repository.js.map