tutorial hell unhandle runtime error

Can anyone help with this? not sure if it is Prisma model problem or how I require prisma went wrong. here is my error message
Unhandled Runtime Error
TRPCClientError:
Invalid `prisma.like.create()` invocation:


Unique constraint failed on the fields: (`tweetId`,`userId`)
Unhandled Runtime Error
TRPCClientError:
Invalid `prisma.like.create()` invocation:


Unique constraint failed on the fields: (`tweetId`,`userId`)
and my prisma model is
model Like {
id String @id @default(cuid())
tweet Tweet @relation(fields: [tweetId], references: [id])
tweetId String
user User @relation(fields: [userId], references: [id])
userId String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@unique ([tweetId, userId])
}
model Like {
id String @id @default(cuid())
tweet Tweet @relation(fields: [tweetId], references: [id])
tweetId String
user User @relation(fields: [userId], references: [id])
userId String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@unique ([tweetId, userId])
}
and my router code within server/router/tweets/ts looks like
import { z } from "zod";
import { protectedProcedure, publicProcedure, router } from "../trpc";
import { tweetSchema } from "../../../components/CreateTweet";

export const tweetRouter = router({
...
like: protectedProcedure
.input(
z.object({
tweetId: z.string(),
})
)
.mutation(async ({ ctx, input }) => {
const { prisma } = ctx;

const userId = ctx.session.user.id;

return prisma.like.create({
data: {
tweet: {
connect: {
id: input.tweetId,
},
},
user: {
connect: {
id: userId,
},
},
},
});
}),
import { z } from "zod";
import { protectedProcedure, publicProcedure, router } from "../trpc";
import { tweetSchema } from "../../../components/CreateTweet";

export const tweetRouter = router({
...
like: protectedProcedure
.input(
z.object({
tweetId: z.string(),
})
)
.mutation(async ({ ctx, input }) => {
const { prisma } = ctx;

const userId = ctx.session.user.id;

return prisma.like.create({
data: {
tweet: {
connect: {
id: input.tweetId,
},
},
user: {
connect: {
id: userId,
},
},
},
});
}),
while on the front end it looks like
function Tweet({
tweet,
}: {
tweet: RouterOutputs["tweet"]["timeline"]["tweets"][number];
}) {
const likeMutation = trpc.tweet.like.useMutation().mutateAsync;
....
return(
<div className="flex-grid ml-2 flex gap-3">
<AiFillHeart
color="grey"
size="1rem"
className="mt-0.5"
onClick={() => {
likeMutation({ tweetId: tweet.id });
}}
/>
</div>
)
function Tweet({
tweet,
}: {
tweet: RouterOutputs["tweet"]["timeline"]["tweets"][number];
}) {
const likeMutation = trpc.tweet.like.useMutation().mutateAsync;
....
return(
<div className="flex-grid ml-2 flex gap-3">
<AiFillHeart
color="grey"
size="1rem"
className="mt-0.5"
onClick={() => {
likeMutation({ tweetId: tweet.id });
}}
/>
</div>
)
not sure what went wrong
17 Replies
Lois
LoisOP•2y ago
@rithulkamesh
Unknown User
Unknown User•2y ago
Message Not Public
Sign In & Join Server To View
Lois
LoisOP•2y ago
yeah I am trying to see if I can get a fix so I added
import { Prisma, PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();
import { Prisma, PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();
still the same error 🥲 start to worry if tRPC is too new to use Could it be a prisma model problem? @rithulkamesh
nexxel
nexxel•2y ago
no bad advice we put it in context for you for a reason the code is correct there @Lois you have @@unique for tweetId and userId but you're not passing those when you create it
Lois
LoisOP•2y ago
I need to be dumber on this: how should I pass them? @nexxel
nexxel
nexxel•2y ago
instead of referencing the tweet and user model through connect just pass the userid and tweet id as userid and tweetid directly
Lois
LoisOP•2y ago
do you want to jump in a voice channel?
nexxel
nexxel•2y ago
return prisma.like.create({
data: {
userId: userId,
tweetId: input.tweetId
},
});
return prisma.like.create({
data: {
userId: userId,
tweetId: input.tweetId
},
});
no
Lois
LoisOP•2y ago
ohh sick, let me try it still got the same error, wondering if it is a frontend problem where I useMutation
nexxel
nexxel•2y ago
nah its a prisma error maybe the id you're passing is not unique anyways google the error idk
Unknown User
Unknown User•2y ago
Message Not Public
Sign In & Join Server To View
nexxel
nexxel•2y ago
what are you saying lol ct3a already creates a client and puts it in trpc context so that you don't have to import it from server/db
Lois
LoisOP•2y ago
I did google it and didn't find much relevant answers also posted on the original vlogger's repo issue and see if anyone knows why and now
const existingLike = await prisma.like.findMany({
where: {
tweetId: input.tweetId,
userId: userId,
},
});
if (!existingLike) {
return prisma.like.create({
data: {
tweet: {
connect: {
id: input.tweetId,
},
},
user: {
connect: {
id: userId,
},
},
},
});
}
const existingLike = await prisma.like.findMany({
where: {
tweetId: input.tweetId,
userId: userId,
},
});
if (!existingLike) {
return prisma.like.create({
data: {
tweet: {
connect: {
id: input.tweetId,
},
},
user: {
connect: {
id: userId,
},
},
},
});
}
tried to validate it before add a new record, but then it is not updating the like record..
adiguno
adiguno•2y ago
If the error message is still the same, “unique constraint”, clean up your db or use different tweetid and usrId
Keef
Keef•2y ago
You can see what parameters you have available for the type on the where clause if you do some control clicking Usually stuff like this is from your prisma schema being out of sync with the database or with the ts server lagging behind I’d start by doing ctrl-p and restarting the ts server in VSCode. If that doesn’t fix it just doing some control clicking and finding the type it should be something like Prisma.TweetWhereInputs or Args That’ll be the generated type Using the account model that comes with next auth we have this type for the WhereUnique Input:
export type AccountWhereUniqueInput = {
id?: string
provider_providerAccountId?: AccountProviderProviderAccountIdCompoundUniqueInput
}
export type AccountWhereUniqueInput = {
id?: string
provider_providerAccountId?: AccountProviderProviderAccountIdCompoundUniqueInput
}
The compound key on the second line is basically what you are trying to do because of @@unique ([tweetId, userId])
prisma.account.findUnique({
where:{
provider_providerAccountId: {
providerAccountId: something,
provider: something2
}
}
})
prisma.account.findUnique({
where:{
provider_providerAccountId: {
providerAccountId: something,
provider: something2
}
}
})
Its slightly different but you can use the same process for understanding what can be passed in. Heres the find many input just to compare
export type AccountWhereInput = {
AND?: Enumerable<AccountWhereInput>
OR?: Enumerable<AccountWhereInput>
NOT?: Enumerable<AccountWhereInput>
id?: StringFilter | string
userId?: StringFilter | string
type?: StringFilter | string
provider?: StringFilter | string
providerAccountId?: StringFilter | string
refresh_token?: StringNullableFilter | string | null
access_token?: StringNullableFilter | string | null
expires_at?: IntNullableFilter | number | null
token_type?: StringNullableFilter | string | null
scope?: StringNullableFilter | string | null
id_token?: StringNullableFilter | string | null
session_state?: StringNullableFilter | string | null
user?: XOR<UserRelationFilter, UserWhereInput>
}
export type AccountWhereInput = {
AND?: Enumerable<AccountWhereInput>
OR?: Enumerable<AccountWhereInput>
NOT?: Enumerable<AccountWhereInput>
id?: StringFilter | string
userId?: StringFilter | string
type?: StringFilter | string
provider?: StringFilter | string
providerAccountId?: StringFilter | string
refresh_token?: StringNullableFilter | string | null
access_token?: StringNullableFilter | string | null
expires_at?: IntNullableFilter | number | null
token_type?: StringNullableFilter | string | null
scope?: StringNullableFilter | string | null
id_token?: StringNullableFilter | string | null
session_state?: StringNullableFilter | string | null
user?: XOR<UserRelationFilter, UserWhereInput>
}
prisma.account.findMany({
where:{
providerAccountId: something,
provider: something2
}
})
prisma.account.findMany({
where:{
providerAccountId: something,
provider: something2
}
})
Lois
LoisOP•2y ago
thanks for the answer I will have a look when I am not brain dead🥲 clean up my db, restarted my laptop and new errors appears when I try to seeded prisma and haven't reached the previous error occured. Will try to fix it myself first -- will keep you posted! And happy new year!
Unknown User
Unknown User•2y ago
Message Not Public
Sign In & Join Server To View
Want results from more Discord servers?
Add your server