Skip to content
This repository has been archived by the owner on Jan 5, 2025. It is now read-only.

Commit

Permalink
keep going
Browse files Browse the repository at this point in the history
  • Loading branch information
threepointone committed Dec 9, 2024
1 parent f08769a commit baaf1b5
Show file tree
Hide file tree
Showing 5 changed files with 70 additions and 30 deletions.
22 changes: 20 additions & 2 deletions example/src/client/app.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useState } from "react";
import { useEffect, useState } from "react";

import { Task } from "../../../src";

Expand All @@ -9,12 +9,24 @@ interface ToDo {
completed: boolean;
}

function fetchTodos(callback: (todos: ToDo[]) => void) {
return fetch("/parties/to-dos/username/api/get-todos")
.then((res) => res.json())
.then((todos) => {
callback(todos as ToDo[]);
});
}

// const ROOM_ID = "username"; // TODO: this will read a username from auth later

export default function App() {
const [todos, setTodos] = useState<ToDo[]>([]);
const [inputText, setInputText] = useState("");

function addOrReplaceTodo(todo: ToDo) {
setTodos((prev) => [...prev.filter((t) => t.id !== todo.id), todo]);
}

const handleAddToDo = async (e: React.FormEvent) => {
e.preventDefault();
if (!inputText.trim()) return;
Expand All @@ -27,7 +39,7 @@ export default function App() {
completed: false,
};

setTodos((prev) => [...prev, newToDo]);
addOrReplaceTodo(newToDo);
// TODO: Schedule the task and update the task with the parsedTask

// let's first convert it to the object that the scheduler expects
Expand Down Expand Up @@ -58,6 +70,12 @@ export default function App() {
setTodos((prev) => prev.filter((todo) => todo.id !== todoId));
};

useEffect(() => {
fetchTodos((todos) => setTodos(todos)).catch((error) => {
console.error("Failed to fetch todos:", error);
});
}, []);

return (
<div className="min-h-screen bg-gray-100 py-8">
<div className="max-w-4xl mx-auto px-4">
Expand Down
44 changes: 18 additions & 26 deletions example/src/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { generateObject } from "ai";
import { Server, routePartykitRequest } from "partyserver";
import { z } from "zod";

import { Scheduler } from "../../../src";
import { Scheduler, type RawTask } from "../../../src";

export { Scheduler };

Expand Down Expand Up @@ -63,34 +63,25 @@ const taskSchema = z
// }

export class ToDos extends Server<Env> {
scheduler: DurableObjectStub<Scheduler<Env>>;
constructor(state: DurableObjectState, env: Env) {
super(state, env);
this.scheduler = env.Scheduler.get(state.id);
}
async fetch(request: Request) {
const url = new URL(request.url);

const route = `${request.method} ${url.pathname}`;
async onRequest(request: Request) {
const name = this.name;
const schedulerId = this.env.Scheduler.idFromName(name);
const scheduler = this.env.Scheduler.get(schedulerId);

switch (route) {
case "GET /api/":
return new Response("Hello, world!");

case "GET /api/tasks": {
const tasks = await this.scheduler.query();
return new Response(JSON.stringify(tasks));
}
const url = new URL(request.url);

case "POST /api/tasks": {
const task = taskSchema.parse(await request.json());
await this.scheduler.scheduleTask(task);
return new Response(JSON.stringify(task));
}
if (url.pathname.endsWith("/api/get-todos") && request.method === "GET") {
const todos = await scheduler.query();
return new Response(JSON.stringify(todos));
}

default:
return new Response("Not found", { status: 404 });
if (url.pathname.endsWith("/api/add-todo") && request.method === "POST") {
const todo = taskSchema.parse(await request.json()) satisfies RawTask;
const task = await scheduler.scheduleTask(todo);
return new Response(JSON.stringify(task));
}

return new Response("Not found", { status: 404 });
}
}

Expand All @@ -99,11 +90,12 @@ export default {
const url = new URL(request.url);

// reroute vite dev server requests to the client
if (!url.pathname.startsWith("/api/")) {
if (!url.pathname.startsWith("/api/") && !url.pathname.startsWith("/parties/")) {
return fetch(request.url.replace("http://localhost:8787", "http://localhost:5173"), request);
}

switch (`${request.method} ${url.pathname}`) {
// TODO: move this into the durable object
case "POST /api/string-to-schedule": {
const openai = createOpenAI({
apiKey: env.OPENAI_API_KEY,
Expand Down
4 changes: 2 additions & 2 deletions example/wrangler.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@ assets = { directory = "public" }


[[durable_objects.bindings]]
name = "SCHEDULER"
name = "Scheduler"
class_name = "Scheduler"

[[durable_objects.bindings]]
name = "TODOS"
name = "ToDos"
class_name = "ToDos"


Expand Down
29 changes: 29 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
"@tailwindcss/forms": "^0.5.9",
"@tailwindcss/typography": "^0.5.15",
"@tailwindcss/vite": "^4.0.0-beta.6",
"@tanstack/react-query": "^5.62.3",
"@types/bun": "^1.1.14",
"@types/react": "^19.0.1",
"@types/react-dom": "^19.0.1",
Expand Down

0 comments on commit baaf1b5

Please sign in to comment.