Skip to content

Todo functions

Course: Prisma - chapter 11

Write a function that let’s you put a todo in the database.

Starter code -

import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
async function createTodo(userId: number, title: string, description: string) {
}
createTodo(1, "go to gym", "go to gym and do 10 pushups");
Solution
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
async function createTodo(userId: number, title: string, description: string) {
const todo = await prisma.todo.create({
data: {
title,
description,
userId
},
});
console.log(todo);
}
getUser(1, "go to gym", "go to gym and do 10 pushups");

Write a function to get all the todos for a user. Starter code

import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
async function getTodos(userId: number, ) {
}
getTodos(1);
Solution
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
async function getTodos(userId: number, ) {
const todos = await prisma.todo.findMany({
where: {
userId: userId,
},
});
console.log(todos);
}
getTodos(1);

3. getTodosAndUserDetails (Does/should it use joins?)

Section titled “3. getTodosAndUserDetails (Does/should it use joins?)”

Write a function that gives you the todo details of a user along with the user details

Starter Code

import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
async function getTodosAndUserDetails(userId: number, ) {
}
getTodosAndUserDetails(1);
Bad solution (2 queries)
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
async function getTodosAndUserDetails(userId: number) {
const user = await prisma.user.findUnique({
where: {
id: userId
}
});
const todos = await prisma.todo.findMany({
where: {
userId: userId,
}
});
console.log(todos);
console.log(user)
}
getTodosAndUserDetails(1);
Good Solution (using joins)
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
async function getTodosAndUserDetails(userId: number, ) {
const todos = await prisma.todo.findMany({
where: {
userId: userId,
},
select: {
user: true,
title: true,
description: true
}
});
console.log(todos);
}
getTodosAndUserDetails(1);

💡 See https://github.com/prisma/prisma/issues/5026 to log the actual SQL queries