Hi here. I want to implement voting functionality ...
# orm-help
y
Hi here. I want to implement voting functionality in my app. A video can only have one vote per user. Is there a way to set this limitation in prisma datamodel? I mean so that a user can not vote a video multiple times. Or the only way to do this is to check if a video already has a vote by this user in
votePost
resolver? My current datamodel is the following:
Copy code
type Video {
  ...
  votes: [Vote!]! @relation(name: "VideoVotes")
  voteScore: Int! @default(value: 0)
}

type Vote {
  id: ID! @unique
  parent: Video! @relation(name: "VideoVotes")
  user: User! @relation(name: "UserVotes")
  type: VoteType!
}

type User {
  ...
  votes: [Vote!]! @relation(name: "UserVotes")
}

enum VoteType {
  UP
  DOWN
}
n
Do you need a Vote type?
How about:
Copy code
type Video {
  ...
  votes: [User!]!
  voteScore: Int! @default(value: 0)
}

type User {
  ...
  votes: [Video!]!
}
I'm not sure what the voteScore is for...
y
@nuno
Vote
type is needed, because it can be both upvote and downvote. I’ve updated the schema above to reflect it. Initially I omitted it for simplicity, didn’t think it’s important here.
voteScore
is an
Int
field reflecting total score of all upvotes and downvotes of a Video. In my opinion it is easier to calculate it once at server when a video is voted than calculating it every time at front end.
n
You could have upvotes and downvotes relations. That way you wouldn't need the
Vote
type and it would simplify the datamodel. But if you needed to add more data to votes (e.g. vote comments) it would be more difficult.
Anyway, you need to make sure a
User
only has a vote per
Video
in your mutation resolver.
And you could remove
voteScore
from the datamodel, and calculate it in your GraphQL server, by counting the
upVotes
and
downVotes
.