Skip to content

Add an extend method #170

@LandonSchropp

Description

@LandonSchropp

Is your feature request related to a problem? Please describe.

I'm working on my personal website that presents a few different types of content:

  • Article
  • TodayILearned
  • Note

In order to avoid duplicating functionality, both in my code and in my Zod schema, I've added a base Content type that the other types extend.

Extending factories for these is a bit of a pain. For example, here's what my content factory currently looks like:

export class ContentFactory extends Factory<Content> {
  idea() {
    return this.params({ status: IDEA_STATUS });
  }

  draft() {
    return this.params({ status: DRAFT_STATUS });
  }

  published() {
    return this.params({ status: PUBLISHED_STATUS });
  }

  willNotPublish() {
    return this.params({ status: WILL_NOT_PUBLISH_STATUS });
  }
}

export const ContentFactory = ContentFactory.define<Content>(
  ({ sequence }) => ({
    title: `Test Content ${sequence}`,
    date: "2024-01-15",
    status: PUBLISHED_STATUS,
    markdown: "This is test markdown content.",
    filePath: `/test/content-${sequence}.md`,
  }),
);

I haven't found a simple method of extending this factory to inherit the default properties in define and include the traits in a child factory (as well as adding others). I tried something like this:

Describe the solution you'd like

My proposal is similar to #169. I'd really like an extend method capable of extending an existing factory with a new type.

const articleFactory = conentFactory.extend<Article>((sequence) => {
  url: `http://example.com/${sequence}`
  description: `An external article ${sequence}.`,
})

This could then work with the trait method proposed in #169, which would inherit the traits provided in the parent factory.

Describe alternatives you've considered

  • I could use factory builder functions. This is doable, but not quite as clean as simply being able to extend the factory.
  • I could try to find a way to inherit parent factory classes. However, I didn't see a simple way of extending the generator function in the factory, and this felt overly complicated.
  • I could live without reusing trait functions from the parent class, which is probably what I'm going to do.

Additional context

Thanks!

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions