Below are the content of the files:
schema.ts
`import { defineSchema, defineTable } from "convex/server";
import { v } from "convex/values";
// Data model for a single-user Todo app
export default defineSchema({
todos: defineTable({
text: v.string(),
completed: v.boolean(),
}).index("by_completed", ["completed"]), // for clearing completed
});`
todo.ts
`import { mutation, query } from "./_generated/server";
import { v } from "convex/values";
export const list = query({
args: {},
handler: async (ctx) => {
const todos = await ctx.db.query("todos").order("asc").collect();
return todos;
},
});
export const add = mutation({
args: { text: v.string() },
handler: async (ctx, args) => {
const text = args.text.trim();
if (text.length === 0) {
throw new Error("Text is required");
}
const id = await ctx.db.insert("todos", {
text,
completed: false,
});
return id;
},
});
export const toggle = mutation({
args: { id: v.id("todos"), completed: v.boolean() },
handler: async (ctx, args) => {
await ctx.db.patch(args.id, { completed: args.completed });
},
});
export const clearCompleted = mutation({
args: {},
handler: async (ctx) => {
const completed = await ctx.db
.query("todos")
// .withIndex("by_completed", (q) => q.eq("completed", true))
.collect();
for (const todo of completed) {
await ctx.db.delete(todo._id);
}
return completed;
},
});`