next.js 在Sanity中为String类型字段创建动态initialValue

pbpqsu0x  于 2023-04-11  发布在  其他
关注(0)|答案(1)|浏览(124)

我在Sanity中有一个文档。有三个字段- title(string),slug(slug)和path(string)。
如何在path字段上使用initialValue来显示基于slug值的自定义动态字符串?
例如,如果slug的值是my-new-path,我如何动态地将path字段上的intialValue设置为/blog/events/my-new-path

export default {
  name: "myPage",
  title: "My Page",
  type: "document",
  fields: [
    {
      name: "title",
      type: "string",
      title: "Page Title",
      validation: (Rule) => Rule.required(),
    },
    {
      name: "slug",
      type: "slug",
      title: "Slug",
      options: {
        source: "title",
        maxLength: 200, // will be ignored if slugify is set
        slugify: (input) =>
          input
            .slice(0, 200)
            .toLowerCase()
            //Remove spaces
            .replace(/\s+/g, "-")
            //Remove special characters
            .replace(/[&\/\\#,+()$~%.'`’":*?<>{}]/g, ""),
      },
      validation: (Rule) => Rule.required(),
    },
    {
      name: "path",
      type: "string",
      title: "URL Path",
      readOnly: true,
    },
  ]
}
yfwxisqw

yfwxisqw1#

我认为你可以做的是为你的slug使用一个异步slugifier,并在生成slug时使用客户端来修补文档。

import slugify from 'some-off-the-shelf-slugifier'

async function myAsyncSlugifier(input, schemaType, context) {
  const slug = slugify(input)
  const {document, getClient} = context
  const client = getClient({apiVersion: '2022-12-07'})
  try {
    const patch = await client
      .patch(document._id)
      .set({path: `/foo/bar/${slug}`})
      .commit()
  } catch(e) {
    console.log(e)
  }
 
  
  return slug
}

//…
// schema field
{
  title: 'Slug',
  name: 'slug',
  type: 'slug',
  options: {
    source: 'title',
    slugify: myAsyncSlugifier
  }
}

相关问题