Core Concepts

Arrays

Managing one-to-many relationships and array fields

So far, we have covered basic fields and simple relationships. This section shows how to work with one‑to‑many relationships and arrays.

Defining a one‑to‑many relationship

Wrap the target entity in an array inside @FactoryType.

class ProductImage {
  @FactoryValue(faker => faker.system.fileName())
  filename: string;
 
  @FactoryValue(faker => faker.image.url())
  url: string;
}
 
class OrderItem {
  @FactoryValue(faker => faker.commerce.productName())
  productName: string;
 
  @FactoryValue(faker => faker.number.int())
  quantity: number;
 
  @FactoryType(() => [ProductImage])
  productImages: ProductImage[];
}
 
class Order {
  @FactoryValue(faker => faker.number.int())
  id: number;
 
  @FactoryType(() => [OrderItem])
  items: OrderItem[];
}

Use .with(amount, path) to opt‑in and specify the number of children.

import { Factory } from 'decorated-factory';
import { faker } from '@faker-js/faker';
 
const factory = new Factory(faker);
const order = factory.one(Order).with(5, 'items').make();
 
console.log(order.items.length); // 5

Nested relationships

Use dot paths to configure nested relations.

const order = factory
  .one(Order)
  .with(2, 'items')
  .with(3, 'items.productImages')
  .make();
 
// One order with two items, each with three images
order.items.forEach(item => {
  console.log(item.productName);
  console.log(item.productImages.length); // 3
});

Overriding elements

Override fields with .set() using array paths.

const order = factory
  .one(Order)
  .with(3, 'items')
  .set('items.0.productName', 'Limited Edition')
  .set('items.0.quantity', 1)
  .make();
 
console.log(order.items[0].productName); // 'Limited Edition'

Custom key binding (using key and inverseKey) applies to both one‑to‑one (1:1) and one‑to‑many (1:N) relationships.

Generating multiple root instances

Use Factory.many(Type).make(n) to generate multiple roots.

const products = factory.many(Product).make(5);
console.log(products.length); // 5

On this page