Skip to content

MOCHI-inc-JAPAN/class-fixtures-factory

Repository files navigation

@mochi-inc-japan/class-fixtures-factory

This lightweight lib is a class factory to generate fixtures on the fly. However, contrarily to most (or rather all) libs out there, class-fixtures-factory generate fixtures from classes. This is handy when you already have classes as your source of truth and do not want to write custom schema to generate fixtures. Also, because the lib is based on emitted TypeScript's metadata, if you heavily use decorators in your classes (when working with class-validator, type-graphql, for example), the setup will be even easier.

If you aren't familiar about what fixtures are, they are simply randomly generated data and are often used for database seeding or for testing.

Features

  • Generate fixtures on the fly at runtime
  • Leverage @faker-js/faker.js for generating random values
  • Support relationships between classes
  • Customizable

Usage

General

Class Factory Usage

@Association(() => [Author, Biography])
class Book {
  @Fixture({ type: () => [Author] })
  authors!: Author[];
}

class Author {
  @Fixture({ type: () => [Book] })
  books!: Book[];
  @Fixture({ type: () => Biography })
  biography!: Biography;
}

class Biography {
  @Fixture('test')
  title!: string;
}

class BookFactory extends FactoryCreator(Book, { maxReflectionCallDepth: 3 }) {}
const bookFactory = new BookFactory();

const bookA = bookFactory.create();
const bookB = bookFactory.create({...(you can specify all initial values for properties)});

First you define class with the properties decorated by @Fixture. Second, you define the factory class by FactoryCreator. If your fixture has association, you specify @Association([Class] or () => [Class]). When you have circular dependencies, you must specify function returns a classes' array as @Association's argument.

Singleton Factory Usage

Because class-fixtures-factory relies on metadata, you'll have to:

  1. Register all the classes you're going to use
  2. Annotate properties with decorators Besides the decorators shipped with the lib, you can also use class-validator decorators.
import { FixtureFactory } from '@mochi-inc-japan/class-fixtures-factory';

const factory = new FixtureFactory();
factory.register([Author, Address, Book]);

// Generate a fixture
let author = factory.make(Author).one();
// Generate multiple fixtures
let authors = factory.make(Author).many(10);

// Ignore some properties at runtime
const partialAuthor = factory
  .make(Author)
  .ignore('address', 'age')
  .one(); // address and age are undefined

// Override properties at runtime
const agedAuthor = factory
  .make(Author)
  .with({
    age: 70,
    address: specialAddr, // any actual address entity object
  })
  .one();

Customization

As stated previously, you'll need to annotate your class properties somehow, because types metadata are used for generating fixtures. The lib exposes a Fixture decorator for that purpose and for further customization. If your properties are already annotated with decorators from class-validator, there's no need to use Fixture, mostly. However, there are some cases where the Fixture decorator is mandatory;

  • If the type is an array
  • If the type is an enum
class Author {
  // decorator from class-validator
  // no need to use Fixture
  @Length(5, 10)
  name: string;

  @Fixture()
  age: number;

  @Fixture({ type: () => [Book] })
  books: Book[];

  @Fixture({ enum: Mood })
  mood: Mood = Mood.HAPPY;
}

Futhermore, Fixture can be used for further customization, using faker.js, as stated:

export class Author extends BaseEntity {

  @Fixture(faker => faker.name.firstName())
  firstName: string;

  // RESTRICTION: This format doesn't allow `false` boolean and null value, use function style for them.
  @Fixture('FirstName')
  lastName: string;

  @Fixture(() => 24)
  age: number;

  @Fixture({ type: () => [Book] }, { min: 3, max: 5 })
  books: Book[];

  // same as not using @Fixture at all
  @Fixture({ ignore: true })
  address: Address;

  // get function also same function interface
  @Fixture((_, author) => author.books[0].title)
  favoriteBook: string;

  // get function also same function interface
  @Fixture({
    computed: false,
    get: (_, author, metadata) => randomUniqueName()
  })
  favoriteBook: string;
}

The second arg is @Fixture is fixture it self reference after initialized, so if you want computed dummy data. If you want to stop this feature and only get fix value initialized once, set computed flag false. The third arg is metadata from reflection. It's rare to use, but you can use this when you want to create generator depends on prop name, so on.

API

FixtureFactory

You can pass an options object to the FixtureFactory constructor:

import { FixtureFactory } from '@mochi-inc-japan/class-fixtures-factory';

const factory = new FixtureFactory({ /* options */});

The options parameter can take:

  • debug (boolean) Whether to print generated objects or no.

  • maxReflectionCallDepth (number) Nested input or object limit count to allow to call deeper association fixture generation. The default value is 5. ( Even if this limit is not set, this library stops direct circular references. Indirecly circular referenceds are not detected. Thus this value should set appropriately if you have indirect circular references. )

FactoryCreator

FactoryCreator can generate class instance like object values factory class with resolved associations. The same option of FixtureFactory can be specified. This can be extended by inheritance for association templates like trait. As default, FactoryCreator has base create(arg, count?) and createMany(...args) methods.

@Association(() => [Author, Biography])
class Book {
  @Fixture({ type: () => [Author] })
  authors!: Author[];
}

class Author {
  @Fixture({ type: () => [Book] })
  books!: Book[];
  @Fixture({ type: () => Biography })
  biography!: Biography;
}

class Biography {
  @Fixture('test')
  title!: string;
}

class BookFactory extends FactoryCreator(Book, { maxReflectionCallDepth: 3 }) {}
const bookFactory = new BookFactory();

const bookA = bookFactory.create();
const bookB = bookFactory.create({...(you can specify all initial values for properties)});

create(arg, count?)

For creating fixture instances. If you specify second argument, the result becomes array and the instances are initialized by first argument.

createMany(...arg)

For creating many fixture instances. The result becomes the array of instances are initialized by the arguments in order.

For Babel envrironement

You need setting basically three plugins with Babel.

module.exports = {
  "presets": [
     ...
  ],
  "plugins": [
    ["babel-plugin-transform-typescript-metadata"]
    ["@babel/plugin-proposal-decorators", { "legacy": true }],
    ["@babel/plugin-proposal-class-properties", {"loose": true}]
  ]
}

Some presets already includes some of them, For example, Expo using React Native babel config.

module.exports = {
    "plugins": [
      ["babel-plugin-transform-typescript-metadata"],
    ],
    presets: ['babel-preset-expo'],
}

Thanks to

Oringinal author's repository is https://github.com/CyriacBr/class-fixtures-factory.

About

This is class-fixtures-factory maintained repository. Original author's repository is https://github.com/CyriacBr/class-fixtures-factory.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 4

  •  
  •  
  •  
  •