diff --git a/backend/database/src/index.ts b/backend/database/src/index.ts index 0d2721f..15056e8 100644 --- a/backend/database/src/index.ts +++ b/backend/database/src/index.ts @@ -110,12 +110,17 @@ export default { const body = await request.json() const { type, name, userId, visibility } = initSchema.parse(body) - const allSandboxes = await db.select().from(sandbox).all() - if (allSandboxes.length >= 8) { - return new Response("You reached the maximum # of sandboxes.", { - status: 400, - }) - } + const userSandboxes = await db + .select() + .from(sandbox) + .where(eq(sandbox.userId, userId)) + .all(); + + if (userSandboxes.length >= 8) { + return new Response("You reached the maximum # of sandboxes.", { + status: 400, + }); + } const sb = await db .insert(sandbox) @@ -123,6 +128,12 @@ export default { .returning() .get() + // Create a new association record in the users_to_sandboxes table + await db + .insert(usersToSandboxes) + .values({ userId, sandboxId: sb.id, sharedOn: new Date() }) + .get(); + const initStorageRequest = new Request( `${env.STORAGE_WORKER_URL}/api/init`, { diff --git a/backend/database/src/schema.ts b/backend/database/src/schema.ts index 4403b96..4451e0f 100644 --- a/backend/database/src/schema.ts +++ b/backend/database/src/schema.ts @@ -31,8 +31,8 @@ export const sandbox = sqliteTable("sandbox", { createdAt: integer("createdAt", { mode: "timestamp_ms" }), userId: text("user_id") .notNull() - .references(() => user.id), -}); + .references(() => user.id, { onDelete: "cascade" }), + }); export type Sandbox = typeof sandbox.$inferSelect;