Custom field defaults in mutations

Does anyone know of a good way to generate custom defaults for fields when creating/updating model instances?

A good example is a slug for a blogpost model: many services will auto-generate the slug based on the title of the post, which avoids requiring the user to type out both the title and a unique slug. I’ve used the AutoSlugField in Django Extensions to do it for Django projects, but can’t come up with a good way to accomplish the same thing with GraphQL/Prisma.

I could probably do it on the frontend before submitting the API request, but then if there’s a collision the frontend would have to handle it, and make more network requests to resolve it.

Ideally there would be a way to specify a custom function for Prisma to call to generate a default value, but I can’t find anything resembling this.

This may be more of a question for Prisma, but since a viable solution might be possible at different levels of the backend I thought I’d ask here.

Could you add something to your service?

export const createBlogPost = ({ input }) => {
  return db.blogpost.create({
    data: {
      slug: generateSlug(input),
      ...input,
    }
  })
}

Yup, I was thinking the same thing.

I would also be sure to:

  • @unique on the slug
  • wrap db.blogpost.create in a while loop/try/catch while the record is not created so that generateSlug can generate something distinct when/if the value of slug collides

or

generateSlug could check if a record with the candidate slug exists and if so, generate an alternative … and repeat until !exists.

Thank you both for these suggestions. These will definitely work for the user-facing version of my site (which uses Redwood for both the web and api sides).

Where I’m really stuck though is on the Admin version of the site. I’m using React Admin with the ra-data-prisma dataprovider/backend. Since ra-data-prisma generates the GraphQL endpoints automatically (using some Nexus magic), I’m bypassing the Redwood API for this version of the backend. Based on looking through the source for this package, I’m thinking I’ll either need to submit a PR to ra-data-prisma to add the ability to specify custom resolvers passed to Nexus, or ask the folks over at Prisma if there is any way to specify defaults on fields other than cuid(), now(), etc.

I figured it was a long shot, but since React Admin seems to be one of the most popular admin packages I was hoping maybe someone had done something similar!

Thanks again!