Hey, a question :slightly_smiling_face: What is yo...
# orm-help
m
Hey, a question 🙂 What is your prefered strategy for validating Mutation inputs with Prisma + Apollo-server? I seen some middleware using Yup, but I am new to this, so someone who has a proven strategy would help me (just point me to it, I;ll research it) 🙂 eg. string length must be 8 or more… (I want to avoid going into resolvers and typing if (length < 8 ) return error… :)
r
One way that could be done is be creating yup schemas for your inputs and in your resolvers, running
schema.validate()
. This will automatically throw the error which will be sent in the GraphQL response. I don’t currently have any example but I could create one.
p
@Ryan Example! 😄
m
Thank you Ryan, I know what to do :)
r
@Philip 👋 My schema:
Copy code
model User {
  id        Int      @id @default(autoincrement())
  name      String?
  email     String   @unique
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}
And this is my yup vaildator:
Copy code
const validators = {
  createUser: yup.object().shape({
    name: yup.string(),
    email: yup.string().email(),
  }),
}
Finally my resolver to create a user:
Copy code
t.field('createUser', {
      type: 'User',
      args: {
        name: ns.stringArg(),
        email: ns.stringArg({ required: true }),
      },
      async resolve(_root, args, ctx) {
        await validators.createUser.validate(args)
        return ctx.prisma.user.create({ data: args })
      },
    })
This will validate and send the error as follow if I type an incorrect email:
🤩 1