Skip to content

Commit

Permalink
added examples and renames file from key-value to tasks-db
Browse files Browse the repository at this point in the history
  • Loading branch information
salisshuaibu11 committed Jan 25, 2025
1 parent 8e86d6b commit fd06f96
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 5 deletions.
50 changes: 50 additions & 0 deletions examples/example-tasks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import {KeyValueDB} from "../packages/core/src/core/tasks-db";
import chalk from "chalk";

async function main() {

const taskDb = new KeyValueDB(
"mongodb://localhost:27017",
"myApp",
);

await taskDb.connect();

// // Store a task
await taskDb.createTask('task_001',{
_id: "task_001",
type: "ongoing",
scheduledFor: new Date(Date.now() + 1000 * 60 * 60 * 24), // 24 hours from now,
metadata: { description: "Sample task" },
});

// Fetch and execute pending scheduled tasks
const tasks = await taskDb.fetchTasks("scheduled", "pending");
for (const task of tasks) {
await taskDb.executeTask(task._id);
}

// Store a message thread
await taskDb.storeMessageThread("thread_001", "user_123", [
{
messageId: "msg_001",
content: "Hello!",
timestamp: new Date(),
},
{
messageId: "msg_002",
content: "How can I help?",
timestamp: new Date(),
},
]);

// Fetch a message thread
const thread = await taskDb.fetchMessageThread("thread_001");
console.log("Fetched thread:", thread);
}

// Run the example
main().catch((error) => {
console.error(chalk.red("Fatal error:"), error);
process.exit(1);
});
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export class KeyValueDB {
private threadsCollection!: Collection<MessageThread>;
private cache: Map<string, Task>; // In-memory cache

constructor(private uri: string, private dbName: string) {
constructor(private uri: string, private dbName: string = "myApp") {
this.client = new MongoClient(uri);
this.cache = new Map<string, Task>();
}
Expand All @@ -40,8 +40,11 @@ export class KeyValueDB {
* 1. tasks collection.
* 2. threads collection
*/
async connect(): Promise<void> {
await this.client.connect();
public async connect(): Promise<void> {
if (!this.client.listenerCount("connect")) {
await this.client.connect();
}

const db = this.client.db(this.dbName);
this.tasksCollection = db.collection<Task>("tasks");
this.threadsCollection = db.collection<MessageThread>("message_threads");
Expand Down Expand Up @@ -120,11 +123,11 @@ export class KeyValueDB {
async executeTask(taskId: string): Promise<void> {
const task = await this.fetchTaskFromCacheOrDB(taskId);
if (!task) {
throw new Error("Task with ID ${taskId} not found");
throw new Error(`Task with ID ${taskId} not found`);
}

// Simulate task execution
console.log("Executing task:, task");
console.log(`Executing task:, ${task}`);

// Update task status
const now = new Date();
Expand Down

0 comments on commit fd06f96

Please sign in to comment.