HiDeoo / starlight-blog

Starlight plugin to add a blog to your documentation
https://starlight-blog-docs.vercel.app
MIT License
126 stars 17 forks source link

Feature: Set a prefix for the blog-post slug or allow schema to be extended for validation #33

Closed stavros-k closed 5 months ago

stavros-k commented 5 months ago

Is your feature request related to a problem?

Currently if I set the slug to my-post it will not get prefixed with blog/. Which generates "incorrect" url

Describe the solution you'd like

Either:

Describe alternatives you've considered

No response

Additional Context

No response

HiDeoo commented 5 months ago

Thanks for your report.

I am not sure to entirely understand the issue. Could you provide more details or share more context about the exact problem you are facing?

stavros-k commented 5 months ago

Hello!

Consider the following frontmatter.

---
slug: "blog/my-post"
title: "My title"
authors: [myself]
date: 2021-12-16
---

We use the slugs on news/blog posts, and currently I have to prefix with blog in order to have correct generated link.

Regarding the extended schema, I want to make sure that all new posts have some frontmatter fields or have a specific format. for example, if I could do this

slug: z.custom<`blog/${string}`>()

It would solve the above issue aswell, as this would force anyone adding a post to have the prefix.

HiDeoo commented 5 months ago

We use the slugs on news/blog posts, and currently I have to prefix with blog in order to have correct generated link.

Why do you have to? Why is the slug needed in your case?

stavros-k commented 5 months ago

We have dates in the filenames, (because docusaurus parsed them from there). And also keeps the files "in a predictable" sort order.

So in order to have cleaner slugs, I've had to manually add the slug.

But, yea thinking it again, have an autoprefix flag might not be the best thing. Being able to extend schema on the other hand is useful, in cases you want to make sure additional metadata are there, things like an image or a description.

HiDeoo commented 5 months ago

Thanks for the explanations. Indeed, auto-prefixing does not seem like a great solution and not sure I want to go down that path.

Regarding extending the schema, this is something supported on the Starlight level. I did not play with this but something close to this should be a pattern that a user could use to provide the custom validation they need:

export const collections = {
  docs: defineCollection({
    schema: docsSchema({
      extend: blogSchema().and(
        z
          .object({
            date: z.date().optional(),
            slug: z.string().optional(),
          })
          .refine((val) => (val.date ? val.slug && val.slug.startsWith('blog/') : true), {
            message: "Blog posts must provide a custom slug starting with 'blog/'",
          }),
      ),
    }),
  }),
}