saksh-task-manager
Version:
A Node.js module for managing tasks with caching and event handling capabilities.
75 lines (66 loc) • 2.34 kB
JavaScript
const NodeCache = require('node-cache');
const EventEmitter = require('events');
const Task = require('./taskModel');
// Set up NodeCache for caching
const myCache = new NodeCache();
class SakshTaskController extends EventEmitter {
constructor(userId) {
super();
this.userId = userId;
}
// Get all tasks with caching
async sakshGetTasks() {
try {
const cachedTasks = myCache.get(`tasks_${this.userId}`);
if (cachedTasks) {
this.emit('tasksRetrieved', cachedTasks);
return cachedTasks;
} else {
const tasks = await Task.find({ userId: this.userId });
myCache.set(`tasks_${this.userId}`, tasks, 3600); // Cache for 1 hour
this.emit('tasksRetrieved', tasks);
return tasks;
}
} catch (error) {
this.emit('error', error);
throw error;
}
}
// Create a new task
async sakshCreateTask(taskData) {
try {
const task = await Task.create({ ...taskData, userId: this.userId });
myCache.del(`tasks_${this.userId}`); // Invalidate cache
this.emit('taskCreated', task);
return task;
} catch (error) {
this.emit('error', error);
throw error;
}
}
// Update a task
async sakshUpdateTask(id, taskData) {
try {
const task = await Task.findOneAndUpdate({ _id: id, userId: this.userId }, taskData, { new: true });
myCache.del(`tasks_${this.userId}`); // Invalidate cache
this.emit('taskUpdated', task);
return task;
} catch (error) {
this.emit('error', error);
throw error;
}
}
// Delete a task
async sakshDeleteTask(id) {
try {
const task = await Task.findOneAndDelete({ _id: id, userId: this.userId });
myCache.del(`tasks_${this.userId}`); // Invalidate cache
this.emit('taskDeleted', task);
return { message: 'Task deleted' };
} catch (error) {
this.emit('error', error);
throw error;
}
}
}
module.exports = SakshTaskController;