Unique Constraints
๐จโ๐ผ We have a
@unique
constraint on several fields. The id
is fine because
that's either generated by the database or hard-coded. But the username
and
email
fields are generated by faker
which can technically generate the same
values twice in a row. Here's how we're doing it currently:export function createUser() {
const firstName = faker.person.firstName()
const lastName = faker.person.lastName()
const username = faker.internet.userName({
firstName: firstName.toLowerCase(),
lastName: lastName.toLowerCase(),
})
return {
username,
name: `${firstName} ${lastName}`,
email: `${username}@example.com`,
}
}
If faker generated the same first and last name then we'd be in trouble. Our
seed script would fail to create a user.
So let's fix that with
enforce-unique
. Here's an
example of how to use this:const uniqueEmailEnforcer = new UniqueEnforcer()
const email = uniqueEmailEnforcer.enforce(() => faker.internet.email())
On top of that, it's possible the username is too long or the wrong case. We're
going to want to limit usernames in our app to be lower case, only 20
characters, and alphanumeric. So we'll want to do something about that as well.
Can you deal with these things? The emoji should help guide you through this.
๐จ When you're ready to go, run the seed script:
npx prisma db seed
๐จ And then open up the Prisma Studio to see your generated data:
npx prisma studio