All Projects → RobinCK → Typeorm Fixtures

RobinCK / Typeorm Fixtures

Licence: mit
💊 Fixtures loader for typeorm

Programming Languages

typescript
32286 projects

Projects that are alternatives of or similar to Typeorm Fixtures

mockingbird
🐦 Decorator Powered TypeScript Library for Creating Mocks
Stars: ✭ 70 (-78.79%)
Mutual labels:  fixtures, faker
Beanmother
A library for setting up Java objects as test data.
Stars: ✭ 102 (-69.09%)
Mutual labels:  faker, fixtures
Pytest Mimesis
Mimesis integration with the pytest test runner. This plugin provider useful fixtures based on providers from Mimesis.
Stars: ✭ 46 (-86.06%)
Mutual labels:  faker, fixtures
Foundry
A model factory library for creating expressive, auto-completable, on-demand dev/test fixtures with Symfony and Doctrine.
Stars: ✭ 216 (-34.55%)
Mutual labels:  faker, fixtures
Morphlingjs
A CLI to mock with meaningful data a REST API from a Swagger file
Stars: ✭ 148 (-55.15%)
Mutual labels:  cli, faker
Gf Cli
GoFrame Command Line Interface, which is your helpmate for building GoFrame application with convenience.
Stars: ✭ 143 (-56.67%)
Mutual labels:  cli, orm
Alice
Expressive fixtures generator
Stars: ✭ 2,289 (+593.64%)
Mutual labels:  faker, fixtures
Ronin
Ronin is a Ruby platform for vulnerability research and exploit development. Ronin allows for the rapid development and distribution of code, Exploits or Payloads, Scanners, etc, via Repositories.
Stars: ✭ 220 (-33.33%)
Mutual labels:  cli, orm
Mimesis
Mimesis is a high-performance fake data generator for Python, which provides data for a variety of purposes in a variety of languages.
Stars: ✭ 3,439 (+942.12%)
Mutual labels:  faker, fixtures
Doctrinejsonfunctions
Doctrine DQL functions for SQL JSON data type
Stars: ✭ 325 (-1.52%)
Mutual labels:  orm
Datafaker
Datafaker is a large-scale test data and flow test data generation tool. Datafaker fakes data and inserts to varied data sources. 测试数据生成工具
Stars: ✭ 327 (-0.91%)
Mutual labels:  faker
Teachcode
A tool to develop and improve a student’s programming skills by introducing the earliest lessons of coding.
Stars: ✭ 325 (-1.52%)
Mutual labels:  cli
Freezer
A simple & fluent Android ORM, how can it be easier ? RxJava2 compatible
Stars: ✭ 326 (-1.21%)
Mutual labels:  orm
Fako
Struct Faker for Go
Stars: ✭ 329 (-0.3%)
Mutual labels:  faker
Crecto
Database wrapper and ORM for Crystal, inspired by Ecto
Stars: ✭ 325 (-1.52%)
Mutual labels:  orm
Ack3
ack is a grep-like search tool optimized for source code.
Stars: ✭ 330 (+0%)
Mutual labels:  cli
Scala Activerecord
ActiveRecord-like ORM library for Scala
Stars: ✭ 324 (-1.82%)
Mutual labels:  orm
Graphback
Graphback - Out of the box GraphQL server and client
Stars: ✭ 323 (-2.12%)
Mutual labels:  cli
Create Dmg
Create a good-looking DMG for your macOS app in seconds
Stars: ✭ 3,494 (+958.79%)
Mutual labels:  cli
Nord Dircolors
An arctic, north-bluish clean and elegant dircolors theme.
Stars: ✭ 328 (-0.61%)
Mutual labels:  cli

TypeORM fixtures cli

CircleCI GitHub CI OpenCollective Coverage Status Version License Backers on Open Collective Sponsors on Open Collective

Relying on faker.js, typeorm-fixtures-cli allows you to create a ton of fixtures/fake data for use while developing or testing your project. It gives you a few essential tools to make it very easy to generate complex data with constraints in a readable and easy to edit way, so that everyone on your team can tweak the fixtures if needed.

Table of Contents

Install

NPM

npm install typeorm-fixtures-cli --save-dev

Yarn

yarn add typeorm-fixtures-cli --dev

Development Setup

# install dependencies
npm install

# build dist files
npm run build

Example

fixtures/Comment.yml

entity: Comment
items:
  comment{1..10}:
    fullName: '{{name.firstName}} {{name.lastName}}'
    email: '{{internet.email}}'
    text: '{{lorem.paragraphs}}'
    post: '@post*'

fixtures/Post.yml

entity: Post
items:
  post1:
    title: '{{name.title}}'
    description: '{{lorem.paragraphs}}'
    user: '@user($current)'
  post2:
    title: '{{name.title}}'
    description: '{{lorem.paragraphs}}'
    user: '@user($current)'

fixtures/User.yml

entity: User
items:
  user1:
    firstName: '{{name.firstName}}'
    lastName: '{{name.lastName}}'
    email: '{{internet.email}}'
    profile: '@profile1'
    __call:
      setPassword:
        - foo
  user2:
    firstName: '{{name.firstName}}'
    lastName: '{{name.lastName}}'
    email: '{{internet.email}}'
    profile: '@profile2'
    __call:
      setPassword:
        - foo

fixtures/Profile.yml

entity: Profile
items:
  profile1:
    aboutMe: <%= ['about string', 'about string 2', 'about string 3'].join(", ") %>
    skype: skype-account>
    language: english
  profile2:
    aboutMe: <%= ['about string', 'about string 2', 'about string 3'].join(", ") %>
    skype: skype-account
    language: english

Creating Fixtures

The most basic functionality of this library is to turn flat yaml files into objects

entity: User
items:
  user0:
    username: bob
    fullname: Bob
    birthDate: 1980-10-10
    email: [email protected]
    favoriteNumber: 42

  user1:
    username: alice
    fullname: Alice
    birthDate: 1978-07-12
    email: [email protected]
    favoriteNumber: 27

Fixture Ranges

The first step is to let create many copies of an object for you to remove duplication from the yaml file.

You can do that by defining a range in the fixture name:

entity: User
items:
  user{1..10}:
    username: bob
    fullname: Bob
    birthDate: 1980-10-10
    email: [email protected]
    favoriteNumber: 42

Now it will generate ten users, with IDs user1 to user10. Pretty good but we only have 10 bobs with the same name, username and email, which is not so fancy yet.

Fixture Reference

You can also specify a reference to a previously created list of fixtures:

entity: Post
items:
  post1:
    title: 'Post title'
    description: 'Post description'
    user: '@user1'

Fixture Lists

You can also specify a list of values instead of a range:

entity: Post
items:
  post{1..10}:
    title: 'Post title'
    description: 'Post description'
    user: '@user($current)'

In the case of a range (e.g. user{1..10}), ($current) will return 1 for user1, 2 for user2 etc.

The current iteration can be used as a string value:

entity: Post
items:
  post{1..10}:
    title: 'Post($current)'
    description: 'Post description'

Post($current) will return Post1 for post1, Post2 for post2 etc.

You can mutate this output by using basic math operators:

entity: Post
items:
  post{1..10}:
    title: 'Post($current*100)'
    description: 'Post description'

Post($current*100) will return Post100 for post1, Post200 for post2 etc.

Calling Sync and Async Methods

Sometimes though you need to call a method to initialize some more data, you can do this just like with properties but instead using the method name and giving it an array of arguments.

entity: User
items:
  user{1..10}:
    username: bob
    fullname: Bob
    birthDate: 1980-10-10
    email: [email protected]
    favoriteNumber: 42
    __call:
      setPassword:
        - foo

Handling Relations

entity: User
items:
  user1:
    # ...

entity: Group
items:
  group1:
    name: '<{names.admin}>'
    owner: '@user1'
    members:
      - '@user2'
      - '@user3'

If you want to create ten users and ten groups and have each user own one group, you can use ($current) which is replaced with the current ID of each iteration when using fixture ranges:

entity: User
items:
  user1:
    # ...

entity: Group
items:
  group{1..10}:
    name: 'name'
    owner: '@user($current)'
    members:
      - '@user2'
      - '@user3'

If you would like a random user instead of a fixed one, you can define a reference with a wildcard:

entity: User
items:
  user1:
    # ...

entity: Group
items:
  group{1..10}:
    name: 'name'
    owner: '@user*'
    members:
      - '@user2'
      - '@user3'

or

entity: User
items:
  user1:
    # ...

entity: Group
items:
  group{1..10}:
    name: 'name'
    owner: '@user{1..2}' # @user1 or @user2
    members:
      - '@user2'
      - '@user3'

Advanced Guide

Parameters

You can set global parameters that will be inserted everywhere those values are used to help with readability. For example:

entity: Group
parameters:
  names:
    admin: Admin
items:
  group1:
    name: '<{names.admin}>' # <--- set Admin
    owner: '@user1'
    members:
      - '@user2'
      - '@user3'

Faker Data

This library integrates with the faker.js library. Using {{foo}} you can call Faker data providers to generate random data.

Let's turn our static bob user into a randomized entry:

entity: User
items:
  user{1..10}:
    username: '{{internet.userName}}'
    fullname: '{{name.firstName}} {{name.lastName}}'
    birthDate: '{{date.past}}'
    email: '{{internet.email}}'
    favoriteNumber: '{{random.number}}'
    __call:
      setPassword:
        - foo

EJS templating

This library integrates with the EJS

entity: Profile
items:
  profile1:
    aboutMe: <%= ['about string', 'about string 2', 'about string 3'].join(", ") %>
    skype: skype-account>
    language: english

Load Processor

Processors allow you to process objects before and/or after they are persisted. Processors must implement the: IProcessor

import { IProcessor } from 'typeorm-fixtures-cli';

Here is an example:

processor/UserProcessor.ts

import { IProcessor } from 'typeorm-fixtures-cli';
import { User } from '../entity/User';

export default class UserProcessor implements IProcessor<User> {
  preProcess(name: string, object: any): any {
    return { ...object, firstName: 'foo' };
  }

  postProcess(name: string, object: { [key: string]: any }): void {
    object.name = `${object.firstName} ${object.lastName}`;
  }
}

fixture config fixtures/user.yml

entity: User
processor: ../processor/UserProcessor
items:
  user1:
    firstName: '{{name.firstName}}'
    lastName: '{{name.lastName}}'
    email: '{{internet.email}}'

Usage

Usage: fixtures [options] <path> Fixtures folder/file path

Options:
  -v, --version              output the version number
  -c, --config <path>        TypeORM config path (default: "ormconfig.yml")
  --require                  A list of additional modules. e.g. ts-node/register
  -cn, --connection [value]  TypeORM connection name (default: "default")
  -s --sync                  Database schema sync
  -d --debug                 Enable debug
  -h, --help                 output usage information
  --no-color                 Disable color
Require multiple additional modules

If you're using multiple modules at once (e.g. ts-node and tsconfig-paths) you have the ability to require these modules with multiple require flags. For example:

fixtures ./fixtures --config ./typeorm.config.ts --sync --require=ts-node/register --require=tsconfig-paths/register

Programmatically loading fixtures

Although typeorm-fixtures-cli is intended to use as a CLI, you can still load fixtures via APIs in your program.

For example, the below code snippet will load all fixtures exist in ./fixtures directory:

import * as path from 'path';
import { Builder, fixturesIterator, Loader, Parser, Resolver } from 'typeorm-fixtures-cli/dist';
import { createConnection, getRepository } from 'typeorm';

const loadFixtures = async (fixturesPath: string) => {
  let connection;

  try {
    connection = await createConnection();
    await connection.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());

    for (const fixture of fixturesIterator(fixtures)) {
      const entity = await builder.build(fixture);
      await getRepository(entity.constructor.name).save(entity);
    }
  } catch (err) {
    throw err;
  } finally {
    if (connection) {
      await connection.close();
    }
  }
};

loadFixtures('./fixtures')
  .then(() => {
    console.log('Fixtures are successfully loaded.');
  })
  .catch(err => console.log(err));

Samples

Contributors

Code Contributors

This project exists thanks to all the people who contribute. [Contribute].

Financial Contributors

Become a financial contributor and help us sustain our community. [Contribute]

Individuals

Organizations

Support this project with your organization. Your logo will show up here with a link to your website. [Contribute]

MIT © Igor Ognichenko

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].