Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Duplicate attributes for DocumentType when using computed Fields to add defaults for normal fields #76

Open
marcofranssen opened this issue Dec 17, 2021 · 1 comment
Labels
bug Something isn't working meta: never-stale

Comments

@marcofranssen
Copy link

marcofranssen commented Dec 17, 2021

Hi, I'm currently using computed fields to add defaults for optional fields. This results in duplicate attributes in the generated document type classes. Is there another way of defining defaults, or should I approach this differently? If not you might consider adding a bugfix to support this scenario of using computed fields to define defaults.

const computedFields = {
  slug: {
    type: "string",
    resolve: (doc) => doc._raw.sourceFileName.replace(/\.md$/, ""),
  },
  excerpt: {
    type: "string",
    resolve: async (doc) => {
      if (doc.excerpt) {
        return doc.excerpt;
      }

      const stripped = await remark()
        .use(strip)
        .process(doc.body.raw.replace(/(<([^>]+)>)/gi, ""));

      const excerpt = stripped.toString().slice(0, 500).trim();

      return `${excerpt}…`;
    },
  },
};

export const Post = defineDocumentType(() => ({
  name: "Post",
  filePathPattern: `posts/*.md`,
  fields: {
    title: { type: "string", required: true },
    publishedAt: { type: "date", required: true },
    excerpt: { type: "string", required: false },
  },
  computedFields,
}));

This results in the following:

export type Post = {
  /** File path relative to `contentDirPath` */
  _id: string
  _raw: Local.RawDocumentData
  type: 'Post'
  title: string
  publishedAt: string
  excerpt: string | undefined
  /** Markdown file body */
  body: Markdown
  slug: string
  excerpt: string
}  

Despite it works you do see excerpt is twice in the Post type. Once as string and once as string | undefined. The generated JSON itself has the field only once as I would expect.

I should probably mention in my project I'm using this from Javascript. That is probably why all still works. In TypeScript this might give some more issues.

@schickling schickling added the bug Something isn't working label Jan 3, 2022
@stale
Copy link

stale bot commented Mar 4, 2022

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working meta: never-stale
Projects
None yet
Development

No branches or pull requests

2 participants