typeorm-fixtures-cli

repository·master·Indexed 20 days ago

https://github.com/robinck/typeorm-fixtures

A tool for generating fake and test data for TypeORM entities using YAML configuration files, Faker.js, and EJS templating. It features a CLI for loading fixtures into databases, support for fixture ranges, relationship referencing, and custom Load Processors via the IProcessor interface to modify objects during the build lifecycle. It includes built-in loaders for JSON, YAML, and TypeScript files.

Tokens
5.2K
Snippets
21
Records
26
Agent score
70%

What's inside typeorm-fixtures-cli

  1. Use Fixture Ranges to reduce duplication

    master

    Use curly braces in the item key to define a range. This generates multiple copies of an object with incrementing IDs.

    Example: user{1..10} generates 10 users with IDs user1 through user10.

    entity: User
    items:
      user{1..10}:
        username: bob
        fullname: Bob
  2. Use the `($current)` variable in fixture lists

    master

    When using ranges, ($current) acts as a dynamic placeholder for the current iteration index (1, 2, 3, etc.). You can use it as a string value or perform basic math on it.

    • Post($current) -> Post1, Post2...
    • Post($current*100) -> Post100, Post200...
    entity: Post
    items:
      post{1..10}:
        title: 'Post($current*100)'
        description: 'Post description'
  3. Reference existing fixtures

    master

    Use the @ prefix followed by an item name to create a relationship to a previously defined fixture.

    Example: user: '@user1' links the current item to the fixture named user1.

    entity: Post
    items:
      post1:
        title: 'Post title'
        user: '@user1'
  4. Handle relations with wildcards

    master

    When defining relations, you can use wildcards or specific ranges to pick from existing fixtures:

    • @user*: Picks a random user from the available user fixtures.
    • @user{1..2}: Picks either @user1 or @user2.
    entity: Group
    items:
      group{1..10}:
        owner: '@user*'
        members:
          - '@user2'
          - '@user3'
  5. Create basic fixtures with YAML

    master

    Define fixtures in YAML files by specifying the entity and a map of items. Each item represents a single record with its properties.

    entity: User
    items:
      user0:
        username: bob
        fullname: Bob
        birthDate: 1980-10-10
        email: bob@example.org
        favoriteNumber: 42
    
      user1:
        username: alice
        fullname: Alice
        birthDate: 1978-07-12
        email: alice@example.org
        favoriteNumber: 27
  6. Execute methods on entities using the __call property

    master

    You can trigger specific methods on your TypeORM entities during the fixture building process by using the __call property in your fixture data. This is useful for setting up complex state that cannot be achieved through simple property assignment (e.g., calling a method that calculates a value or sets up relationships).

    Requirements:

    • The __call property must be an object where keys correspond to method names on the entity.
    • The values associated with these keys can be single values or arrays of values (which will be passed as arguments to the method).
    • The method must exist on the entity instance.

    Warning: The __call property must be an object. If it is an array or a non-object type, the builder will throw an error: invalid "__call" parameter format.

    # Example fixture data structure for __call
    my_fixture:
      entity: User
      data:
        username: "jdoe"
        __call:
          setProfile: ["bio content", "avatar_url"]
          activate: []
  7. Extend fixture building with Processors

    master

    Processors allow you to inject custom logic into the fixture building lifecycle. A processor is a class that implements the IProcessor interface and can be referenced in a fixture via a file path.

    Lifecycle Hooks:

    • preProcess(fixtureName: string, data: any): Promise<any>: Transform the raw data before the entity is instantiated.
    • postProcess(fixtureName: string, entity: any): Promise<void>: Perform actions on the instantiated entity after it has been built.

    How to reference a processor: In your fixture definition, provide the path to the processor file. The Builder will attempt to load the .default export from the specified path (supporting .ts or .js files).

  8. Load fixtures programmatically

    master

    You can use the internal API to load fixtures within your own application code. This involves using Loader, Resolver, Builder, and fixturesIterator from the typeorm-fixtures-cli/dist package.

    import * as path from 'path';
    import { Builder, fixturesIterator, Loader, Parser, Resolver } from 'typeorm-fixtures-cli/dist';
    import { createConnection, getRepository } from 'typeorm';
    import { CommandUtils } from 'typeorm/commands/CommandUtils';
    
    const loadFixtures = async (fixturesPath: string) => {
      let dataSource: DataSource | undefined = undefined;
    
      try {
        dataSource = await CommandUtils.loadDataSource(dataSourcePath);
        await dataSource.initialize();
        await dataSource.synchronize(true);
    
        const loader = new Loader();
        loader.load(path.resolve(fixturesPath));
    
        const resolver = new Resolver();
        const fixtures = resolver.resolve(loader.fixtureConfigs);
        const builder = new Builder(connection, new Parser(), false);
    
        for (const fixture of fixturesIterator(fixtures)) {
          const entity: any = await builder.build(fixture);
          await dataSource.getRepository(fixture.entity).save(entity);
        }
      } catch (err) {
        throw err;
      } finally {
        if (dataSource) {
          await dataSource.destroy();
        }
      }
    };
    
    loadFixtures('./fixtures');