### Install FactoryJS with pnpm, npm, or yarn Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/get-started.mdx Installs the FactoryJS library as a development dependency using different package managers. ```sh pnpm add -D @factory-js/factory ``` ```sh npm i --save-dev @factory-js/factory ``` ```sh yarn add -D @factory-js/factory ``` -------------------------------- ### Install Factory.js with pnpm Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/other-orms/get-started.mdx Installs the Factory.js package as a development dependency using the pnpm package manager. ```sh pnpm add -D @factory-js/factory ``` -------------------------------- ### Install Factory.js with npm Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/other-orms/get-started.mdx Installs the Factory.js package as a development dependency using the npm package manager. ```sh npm i --save-dev @factory-js/factory ``` -------------------------------- ### Install Factory.js with yarn Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/other-orms/get-started.mdx Installs the Factory.js package as a development dependency using the yarn package manager. ```sh yarn add -D @factory-js/factory ``` -------------------------------- ### Install FactoryJS Prisma Packages Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/prisma-plugin/get-started.mdx Installs the necessary FactoryJS packages for Prisma integration using pnpm, npm, or yarn. ```sh pnpm add -D @factory-js/factory @factory-js/prisma-factory ``` ```sh npm i --save-dev @factory-js/factory @factory-js/prisma-factory ``` ```sh yarn add -D @factory-js/factory @factory-js/prisma-factory ``` -------------------------------- ### Create User with Prisma using FactoryJS Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/get-started.mdx Demonstrates creating a user object and saving it to the database using the Prisma-integrated factory. It uses the `.create()` method, which executes the persistence callback defined in the factory. ```ts import { expect, it, describe } from "vitest"; import { userFactory } from "../factories/user-factory"; import { isAdmin } from "./is-admin"; describe("when a user is admin", () => { it("returns true", async () => { // `.create` returns the object saved to the database const user = await userFactory.props({ role: () => "admin" }).create(); expect(isAdmin(user)).toBe(true); }); }); ``` -------------------------------- ### Generate Factories with Prisma CLI Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/prisma-plugin/get-started.mdx Executes the Prisma generate command to create factory files based on the schema configuration. ```bash prisma generate ``` -------------------------------- ### Define User Factory with Prisma Integration Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/get-started.mdx Defines a user factory that integrates with Prisma to save generated user data to the database. It includes a callback function as the second argument to `.define` which uses `db.user.create` to persist the data. ```ts import { factory } from "@factory-js/factory"; import { faker } from "@faker-js/faker"; // `db` assumes an instance of `PrismaClient` import { db } from "../db"; const userFactory = factory.define( { props: { firstName: () => faker.person.firstName(), lastName: () => faker.person.lastName(), role: () => "employee", }, vars: {}, }, async (user) => { // Receive the generated object as `user` and save it to the database return db.user.create({ data: user }); }, ); ``` -------------------------------- ### Test isAdmin Function with FactoryJS Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/get-started.mdx Tests the `isAdmin` function by creating user objects with different roles ('admin' and 'guest') using the `userFactory`. It demonstrates overriding default properties using `.props()` and building objects with `.build()`. ```ts // Function to be tested export const isAdmin = (user: User) => { return user.role === "admin"; }; import { expect, it, describe } from "vitest"; import { userFactory } from "../factories/user-factory"; import { isAdmin } from "./is-admin"; describe("when a user is admin", () => { it("returns true", async () => { const user = await userFactory(db) .props({ role: () => "admin" }) // Overwrite role to admin .build(); expect(isAdmin(user)).toBe(true); }); }); describe("when a user is guest", () => { it("returns false", async () => { const user = await userFactory(db) .props({ role: () => "guest" }) // Overwrite role to guest .build(); expect(isAdmin(user)).toBe(false); }); }); ``` -------------------------------- ### Define a User Factory with Faker Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/get-started.mdx Defines a factory for user objects using Faker to generate first name, last name, and a default role. This factory can be used to create mock user data for testing. ```ts import { factory } from "@factory-js/factory"; import { faker } from "@faker-js/faker"; const userFactory = factory.define({ props: { firstName: () => faker.person.firstName(), lastName: () => faker.person.lastName(), role: () => "employee", }, vars: {}, }); ``` -------------------------------- ### Configure Prisma Schema for FactoryJS Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/prisma-plugin/get-started.mdx Adds the 'factory' generator to the Prisma schema file to enable automatic factory generation. ```prisma generator factory { provider = "prisma-factory" } ``` -------------------------------- ### Create User and Profile with Linked IDs Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/other-orms/get-started.mdx Demonstrates creating a user and then a profile linked to that user's ID using Factory.js. It utilizes the `props` method on the profile factory to set the `userId` before creating the profile. ```typescript import { expect, it, describe } from "vitest"; import { userFactory, profileFactory } from "../factories"; import { getProfile } from "./get-profile"; describe("when a user exists", () => { it("returns the user profile", async () => { const user = await userFactory.create(); const profile = await profileFactory .props({ userId: () => user.id }) .create(); await expect(getProfile(user.id)).resolves.toStrictEqual({ name: user.name, bio: profile.bio, }); }); }); ``` -------------------------------- ### Enable and Install pnpm Source: https://github.com/factory-js/factory-js.github.io/blob/main/CONTRIBUTING.md Enables the pnpm package manager using Corepack and installs project dependencies. pnpm is used for managing packages in this project. ```sh corepack enable pnpm pnpm install ``` -------------------------------- ### Use Generated Factories in TypeScript Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/prisma-plugin/get-started.mdx Demonstrates how to import and use generated factories to create objects with specific properties using the `.create` method. ```typescript import { defineUserFactory } from "./generated/factories"; import { PrismaClient } from "@prisma/client"; const db = new PrismaClient(); const userFactory = await defineUserFactory(db); it("returns an admin user", async () => { const user = userFactory.props({ role: () => "ADMIN" }).create(); expect(user.role).toBe("ADMIN"); }); ``` -------------------------------- ### Define a User Factory with Faker Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/other-orms/get-started.mdx Defines a Factory.js factory for a User model, using Faker.js to generate realistic data for name, email, and role. It includes a function to create users via a Drizzle API. ```typescript import { factory } from "@factory-js/factory"; import { faker } from "@faker-js/faker"; // `create` is a function that calls the Drizzle API to save data to the database import { create } from "./utils/create"; export const userFactory = factory.define( { props: { name: () => faker.string.alphanumeric(40), email: () => faker.internet.exampleEmail(), role: () => faker.helpers.arrayElement(["guest", "admin"] as const), }, vars: {}, }, // The second argument is a function to save the model (props) => create(users, props), ); ``` -------------------------------- ### Clone Repository Source: https://github.com/factory-js/factory-js.github.io/blob/main/CONTRIBUTING.md Clones the FactoryJS documentation repository from GitHub. This is the first step in contributing. ```sh git clone git@github.com:/factory-js.github.io.git cd factory-js.github.io ``` -------------------------------- ### Define User and Profile Factories with Variables Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/other-orms/get-started.mdx Defines a user factory and a profile factory using Factory.js. The profile factory uses a variable to store a default user created by the user factory, simplifying profile creation by automatically associating it with a user. ```typescript import { factory } from "@factory-js/factory"; import { faker } from "@faker-js/faker"; import { create } from "./utils/create"; const userFactory = factory.define( { props: { name: () => faker.string.alphanumeric(40), email: () => faker.internet.exampleEmail(), role: () => faker.helpers.arrayElement(["guest", "admin"] as const), }, vars: {}, }, (props) => create(users, props), ); const profileFactory = factory .define( { props: { userId: later(), bio: () => faker.string.alphanumeric(40), }, vars: { // Store the default user in a variable user: () => userFactory.create(), }, }, (props) => create(profiles, props), ) .props({ // Use the variable to get the user's ID and set it to `userId` userId: async ({ vars }) => (await vars.user).id, }); ``` -------------------------------- ### Manage Relationships with FactoryJS Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/prisma-plugin/get-started.mdx Shows how to use the `.vars` method to override or define relationships when creating objects with factories, such as linking a profile to a user. ```typescript const userFactory = await defineUserFactory(db); const profileFactory = await defineProfileFactory(db); it("create an admin profile", async () => { const user = userFactory.props({ role: () => "ADMIN" }).create(); const profile = profileFactory.vars({ user: () => user }).create(); expect(profile.userId).toBe(user.id); }); ``` -------------------------------- ### Define User and Profile Factories Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/other-orms/get-started.mdx Defines factories for User and Profile models. The User factory uses Faker for data generation. The Profile factory uses `later()` for the `userId` to ensure it's set when creating a profile linked to a user. ```typescript import { factory } from "@factory-js/factory"; import { faker } from "@faker-js/faker"; import { create } from "./utils/create"; // Define the user factory export const userFactory = factory.define( { props: { name: () => faker.string.alphanumeric(40), email: () => faker.internet.exampleEmail(), role: () => faker.helpers.arrayElement(["guest", "admin"] as const), }, vars: {}, }, (props) => create(users, props), ); // Define the profile factory export const profileFactory = factory.define( { props: { // By using `later`, an exception will be thrown // if `.props` to set `userId` later is forgotten userId: later(), bio: () => faker.string.alphanumeric(40), }, vars: {}, }, (props) => create(profiles, props), ); ``` -------------------------------- ### Test Profile Creation with Default User Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/other-orms/get-started.mdx Tests the creation of a profile using the profile factory. It asserts that the created profile is valid when using the default user relationship established via variables in the factory definition. ```typescript import { expect, it, describe } from "vitest"; import { userFactory, profileFactory } from "../factories"; import { isValidProfile } from "./is-valid-profile"; describe("when a profile is valid", () => { it("returns true", async () => { // Create a profile using the default user const profile = await profileFactory.create(); await expect(isValidProfile(profile)).resolves.toBe(true); }); }); ``` -------------------------------- ### Test User Admin Status with Factory.js Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/other-orms/get-started.mdx Tests a function that checks if a user is an admin using a Factory.js user factory. It creates an admin user by setting the 'role' prop and asserts the function returns true. ```typescript import { expect, it, describe } from "vitest"; import { userFactory } from "../factories/user-factory"; import { isAdmin } from "./is-admin"; describe("when a user is admin", () => { it("returns true", async () => { // To create an admin user, set the `role` to `admin` with `.props` const user = await userFactory.props({ role: () => "admin" }).create(); expect(isAdmin(user)).toBe(true); }); }); ``` -------------------------------- ### Run Linters Source: https://github.com/factory-js/factory-js.github.io/blob/main/CONTRIBUTING.md Executes various linters and type-checking tools to ensure code quality and consistency before pushing. Includes secretlint, type-check, lint, and format. ```sh pnpm run secretlint pnpm run type-check pnpm run lint pnpm run format ``` -------------------------------- ### Push Changes and Create PR Source: https://github.com/factory-js/factory-js.github.io/blob/main/CONTRIBUTING.md Pushes your local branch to the remote repository and prepares for opening a pull request. The `-u` flag sets the upstream for future pushes. ```sh git push -u origin your-branch-name ``` -------------------------------- ### Create and Checkout Branch Source: https://github.com/factory-js/factory-js.github.io/blob/main/CONTRIBUTING.md Creates a new Git branch for your contributions and checks it out. This isolates your changes from the main codebase. ```sh git switch -c your-new-branch-name ``` -------------------------------- ### Override User Variable for Admin Profile Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/other-orms/get-started.mdx Demonstrates how to override the default user variable in the profile factory to create a profile associated with an admin user. This allows for creating specific relationships by providing a custom user object. ```typescript describe("when a user is admin", () => { it("returns true", async () => { const user = await userFactory.props({ role: () => "admin" }).create(); const profile = await profileFactory.vars({ user: () => user }).create(); await expect(isAdminProfile(user.id)).resolves.toBe(true); }); }); ``` -------------------------------- ### Test Book Creation with STI Factory (TypeScript) Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/other-orms/recipes.mdx Provides a unit test example using Vitest to verify the functionality of the product factory for 'book' types. It demonstrates how to use the `.use` method to specify a trait and then create a book instance, asserting that the correct data is returned. ```ts import { describe, expect, it } from "vitest"; import { productFactory } from "../factories/product-factory"; import { getProduct } from "./sti"; describe("when a product type is book", () => { it("returns the book", async () => { const book = await productFactory.use((t) => t.book).create(); await expect(getProduct(book.id)).resolves.toStrictEqual({ author: book.author, name: book.name, }); }); }); ``` -------------------------------- ### Generate Sequential Values with `seq` Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/guide/sequence.mdx Demonstrates the basic usage of `seq` to generate sequential numeric and string values. The first argument is the starting value, and the second is a function that defines the sequence logic. ```typescript import { factory, seq } from "@factory-js/factory"; const userFactory = factory.define({ props: { id: seq(1, (n) => n), name: seq(1, (n) => `user-${n}`), // Can generate non-numeric values as well }, vars: {}, }); // 👇 [{ id: 1, name: "user-1" }, { id: 2, name: "user-2" }] console.log(await userFactory.buildList(2)); ``` -------------------------------- ### Define Factory with Save Function (Prisma Example) Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/guide/defining-factory.mdx Illustrates defining a factory with a second argument, a function that handles saving the generated object, shown here with a Prisma ORM example. ```typescript import { factory } from "@factory-js/factory"; import { faker } from "@faker-js/faker"; // `db` assumes an instance of `PrismaClient` import { db } from "../db"; const userFactory = factory.define( { props: { firstName: () => "John", lastName: () => "Doe", }, vars: {}, }, async (user) => { return db.user.create({ data: user }); }, ); ``` -------------------------------- ### Define and Use a Single Trait in Factory.js Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/guide/trait.mdx Demonstrates how to define a factory with initial properties and variables, and then add a 'admin' trait. The trait modifies properties and variables, and includes an 'after' hook. The example shows how to apply this trait using `.use()` and build the factory instance. ```typescript const userFactory = factory .define({ props: { role: () => "guest", isAdmin: () => false, }, vars: { greeting: () => "Hi", }, }) .traits({ admin: { props: { role: () => "admin", isAdmin: () => true, }, vars: { greeting: () => "Hello", }, after: () => { console.log("Admin created"); }, }, }); // To use a trait, specify the key with `use` await userFactory.use((t) => t.admin).build(); ``` -------------------------------- ### Commit Changes Source: https://github.com/factory-js/factory-js.github.io/blob/main/CONTRIBUTING.md Commits staged changes to the current branch with a descriptive message. This records your work. ```sh git commit -m 'add a new feature' ``` -------------------------------- ### Use Custom User Factory in Tests Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/prisma-plugin/best-practice.mdx This example demonstrates how to use a custom user factory within a test file using Vitest. It creates a user with a specific role ('admin') and asserts the result of an isAdmin function. ```typescript import { expect, it, describe } from "vitest"; import { userFactory } from "../factories/user-factory"; import { isAdmin } from "./is-admin"; describe("when a user is admin", () => { it("returns true", async () => { const user = await userFactory.props({ role: () => "admin" }).create(); expect(isAdmin(user)).toBe(true); }); }); ``` -------------------------------- ### Apply Multiple Traits Sequentially in Factory.js Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/guide/trait.mdx Shows how to apply multiple traits ('employee', 'admin', 'maskedName') to a factory instance in sequence using chained `.use()` calls. The example highlights that the last applied trait takes precedence, demonstrating the order of application and the final resulting object. ```typescript await userFactory .use((t) => t.employee) .use((t) => t.admin) .use((t) => t.maskedName) .build(); // 👉 { name: "***", role: "admin", isAdmin: true } ``` -------------------------------- ### FactoryJS Caching Example Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/guide/variable.mdx Demonstrates FactoryJS's caching mechanism where a variable (`id`) is calculated only once and reused, ensuring idempotency. Properties like `cardId` and `roomId` reference this cached `id`. ```ts let count = 1; const userFactory = factory .define({ props: { id: later(), cardId: later(), roomId: later(), }, vars: { // It seems `count` would increment each time, // but it is cached and calculated only once id: () => count++, }, }) .props({ id: async ({ vars }) => await vars.id, cardId: async ({ vars }) => `card:${await vars.id}`, roomId: async ({ vars }) => `room:${await vars.id}`, }); console.log(await userFactory.build()); // 👉 { id: 1, cardId: 'card:1', roomId: 'room:1' } console.log(await userFactory.build()); // 👉 { id: 2, cardId: 'card:2', roomId: 'room:2' } ``` -------------------------------- ### Chaining .props for Property Overwrites Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/guide/property.mdx Illustrates the behavior of chaining multiple `.props` calls in Factory.js. The example shows that the last property overwrite in the chain takes precedence. ```typescript const user = await userFactory .props({ firstName: () => "Alice", lastName: () => "Smith" }) .props({ firstName: () => "Bob" }) .props({ firstName: () => "Tom" }) .build(); console.log(user); // 👉 { firstName: "Tom", lastName: "Smith" } ``` -------------------------------- ### Specify Custom Random Module Path Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/prisma-plugin/options.mdx Configures the Prisma generator to use a custom module for random value generation. This example sets the 'randModule' option to './rands', enabling the use of custom random generators defined in that file. ```prisma generator factory { provider = "prisma-factory" randModule = "./rands" } ``` -------------------------------- ### Demonstrate .def Behavior with Overwritten Properties Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/guide/extending-factory.mdx This example illustrates the behavior of the `.def` method when properties are overwritten in a method chain. It shows that `.def` only captures the initial properties defined in `.define` and does not include subsequent modifications made using `.props`. The output confirms that the extended factory uses the original property value. ```TypeScript import { factory } from "@factory-js/factory"; const userFactory = await factory .define({ props: { name: () => "John", }, vars: {}, }) // Here, `name` is overwritten to "Tom", but this is not reflected in the `.def` result .props({ name: () => "Tom", }); // The `props.name` returned here is "John", not "Tom" const { props } = userFactory.def; const employeeFactory = await factory.define({ props: { ...props, role: () => "admin", }, vars: {}, }); console.log(await employeeFactory.build()); // 👉 { name: "John", role: "admin" } ``` -------------------------------- ### Build Object from Factory Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/guide/defining-factory.mdx Shows how to use the `.build()` method on a previously defined factory to create an instance of the object. ```typescript const user = await userFactory.build(); console.log(user); // 👉 { "firstName": "John", "lastName": "Doe", "age": 20 } ``` -------------------------------- ### Generate Multiple Objects with buildList Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/guide/defining-factory.mdx Illustrates how to generate an array of objects using the `.buildList()` method, specifying the number of objects to create. ```typescript await userFactory.buildList(2); // 👉 [{ "firstName": "John", "lastName": "Doe" }, {...}] ``` -------------------------------- ### Test Folder Tree Creation with Self-Relation Factory (TypeScript) Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/other-orms/recipes.mdx Demonstrates a unit test using Vitest to validate the folder factory's ability to create hierarchical data. It shows how to create a root folder and then two child folders by passing the parent to the factory's variables, asserting the correct structure of the returned data. ```ts import { describe, expect, it } from "vitest"; import { folderFactory } from "../factories/folder-factory"; import { getChildFolders } from "./self-relation"; describe("when a folder has children", () => { it("returns the folder tree", async () => { // Create a root folder const parent = await folderFactory.create(); // Create two child folders const children = await folderFactory .vars({ parent: () => parent }) .createList(2); await expect(getChildFolders(parent.id)).resolves.toStrictEqual([ { name: children[0]?.name, children: [] }, { name: children[1]?.name, children: [] }, ]); }); }); ``` -------------------------------- ### Create and CreateList Objects Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/guide/defining-factory.mdx Shows how to use `.create()` to invoke the save function defined in the factory and `.createList()` to save multiple objects. ```typescript await userFactory.create(); // Calls the function set as the second argument and returns the result await userFactory.createList(2); ``` -------------------------------- ### Update Dependent Property with Overwritten Value Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/guide/property.mdx Demonstrates how changing a property value in Factory.js automatically updates dependent properties. The example shows 'fullName' being updated when 'firstName' is changed. ```typescript const userFactory = factory .define({ props: { firstName: () => "John", lastName: () => "Doe", fullName: "", }, vars: {}, }) .props({ fullName: async ({ props }) => `${await props.firstName} ${await props.lastName}`, }); const user = await userFactory.props({ firstName: () => "Tom" }).build(); // 👇 { fullName: "Tom Doe", firstName: "Tom", lastName: "Doe" } console.log(await userFactory.build()); ``` -------------------------------- ### Define Factory with Explicit Types for Properties, Create, and Vars Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/guide/defining-factory.mdx Demonstrates explicitly defining types for properties, the return type of the create function, and variables using TypeScript generics. ```typescript import { factory } from "@factory-js/factory"; type User = { firstName: string; lastName: string }; // Property type type SavedUser = { firstName: string; lastName: string; isSaved: true }; // Return type of `.create` type Vars = { title: string }; // Variable type const userFactory = factory.define( { props: { firstName: () => "John", lastName: () => "Doe", }, vars: { title: () => "Mr.", }, }, async (props) => { return { ...props, isSaved: true }; }, ); ``` -------------------------------- ### Overwrite Factory Property Value Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/guide/property.mdx Demonstrates how to overwrite a property value ('firstName') in a Factory.js factory using the `.props` method. The example shows changing the value from 'John' to 'Alice'. ```typescript import { factory } from "@factory-js/factory"; const userFactory = factory.define({ props: { firstName: () => "John", lastName: () => "Doe", }, vars: {}, }); const user = await userFactory.props({ firstName: () => "Alice" }).build(); console.log(user); // 👉 { "firstName": "Alice", "lastName": "Doe" } ``` -------------------------------- ### Build Item Factory with `type` Set Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/guide/placeholder.mdx Demonstrates successfully building an `itemFactory` object by providing the `type` property using `.props()`, avoiding the exception that occurs when `type` is not set. ```typescript import { expect, it, describe } from "vitest"; import { itemFactory } from "../factories/item-factory"; import { isFood } from "./is-food"; describe("when the type is food", () => { it("returns true", async () => { // ✅ No exception is thrown because `type` is set const item = await itemFactory.props({ type: () => "food" }).build(); expect(isFood(item)).toBe(true); }); }); describe("when the type is book", () => { it("returns false", async () => { // ❌ Throws an exception because `type` is not set const item = await itemFactory.build(); expect(isFood(item)).toBe(false); }); }); ``` -------------------------------- ### Define Factory with Properties and Promises Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/guide/defining-factory.mdx Demonstrates how to define a factory with properties, including asynchronous values wrapped in Promises. The `.build()` method is used to generate an object from the factory. ```typescript import { factory } from "@factory-js/factory"; const userFactory = factory.define({ props: { firstName: () => "John", lastName: () => "Doe", age: () => Promise.resolve(20), // Promise can also be used }, vars: {}, }); console.log(await userFactory.build()); ``` -------------------------------- ### Define Multiple Traits in Factory.js Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/guide/trait.mdx Illustrates defining multiple traits ('employee', 'admin', 'maskedName') for a factory. The traits modify properties like 'role' and 'name'. This example shows how to chain multiple `.traits()` calls to add different sets of traits to the factory. ```typescript const userFactory = factory .define({ props: { name: () => "John", role: () => "guest", isAdmin: () => false, }, vars: {}, }) .traits({ employee: { props: { role: () => "employee", isAdmin: () => false, }, }, admin: { props: { role: () => "admin", isAdmin: () => true, }, }, }) .traits({ maskedName: { props: { name: () => "***", }, }, }); ``` -------------------------------- ### Define New Employee Factory from User Factory Properties Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/guide/extending-factory.mdx This snippet demonstrates how to define a new `employeeFactory` by inheriting properties and variables from an existing `userFactory` using the `.def` method. It shows how to spread the properties and variables from the base factory into the new one, adding specific properties for the employee. ```TypeScript import { factory } from "@factory-js/factory"; const userFactory = await factory.define({ props: { name: () => "John", age: () => 20, }, vars: { title: () => "Mr.", }, }); // Use `.def` to get the properties and variables from `userFactory` const { props, vars } = userFactory.def; const employeeFactory = await factory.define({ props: { ...props, role: () => "admin", }, vars: { ...vars, greeting: () => "Hello", }, }); ``` -------------------------------- ### Customize Random Value Generation Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/prisma-plugin/options.mdx Allows customization of random value generation for different field types. This example shows how to override the default String type generation to use UUIDs by spreading the original random module and redefining the String generator. ```typescript import { rands as originalRands } from "@factory-js/prisma-factory"; import { faker } from "@faker-js/faker"; export const rands = { ...originalRands, String: () => faker.string.uuid(), }; ``` -------------------------------- ### Define Custom User Factory Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/prisma-plugin/best-practice.mdx This snippet shows how to define a custom user factory using Factory.js, Prisma, and Faker.js. It sets a specific format for the email field using faker.internet.exampleEmail(). ```typescript import { db } from "../db"; import { faker } from "@faker-js/faker"; export const userFactory = await defineUserFactory(db).props({ // Set a valid email address format as the default value email: () => faker.internet.exampleEmail(), }); ``` -------------------------------- ### Configure Prisma Generator Output Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/prisma-plugin/options.mdx Specifies the output directory for the generated factories. The default is './generated'. This configuration is part of the Prisma schema file. ```prisma generator factory { provider = "prisma-factory" output = "./generated" randModule = "./rand" prismaClientModule = "./dist" } ``` -------------------------------- ### Generate Random Objects Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/guide/defining-factory.mdx Shows how calling `.build()` multiple times on a factory configured with Faker results in different random values for each generated object. ```typescript console.log(userFactory.build()); // 👉 { "firstName": "John", "lastName": "Doe" } console.log(userFactory.build()); // 👉 { "firstName": "Tom", "lastName": "Smith" } ``` -------------------------------- ### Reference Properties and Variables in `seq` Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/guide/sequence.mdx Shows how to use `seq` to generate values that depend on other factory properties and variables. The sequence function receives access to `props` and `vars` for dynamic value generation. ```typescript import { factory, seq } from "@factory-js/factory"; const userFactory = factory .define({ props: { key: later(), name: () => "John", }, vars: { role: () => "admin", }, }) .props({ key: seq( 1, async (n, { props, vars }) => `${await props.name}:${await vars.role}:${n}`, ), }); // 👇 [{ id: 1, name: "John:admin:1" }, { id: 2, name: "John:admin:2" }] console.log(await userFactory.buildList(2)); ``` -------------------------------- ### Define Factory with Faker for Random Values Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/guide/defining-factory.mdx Demonstrates using the Faker library within a factory definition to generate random values for properties like first and last names. ```typescript import { factory } from "@factory-js/factory"; import { faker } from "@faker-js/faker"; const userFactory = factory.define({ props: { firstName: () => faker.person.firstName(), lastName: () => faker.person.lastName(), }, vars: {}, }); ``` -------------------------------- ### Specify Prisma Client Module Path Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/prisma-plugin/options.mdx Sets the import path for PrismaClient. This is useful when PrismaClient's output location has been changed using the 'output' option in Prisma. The default path is '@prisma/client'. ```prisma generator factory { provider = "prisma-factory" prismaClientModule = "./dist" } ``` -------------------------------- ### Define Factory with Variables Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/guide/defining-factory.mdx Demonstrates defining variables within the `vars` property of a factory, similar to how `props` are defined, including support for Promises. ```typescript import { factory } from "@factory-js/factory"; import { faker } from "@faker-js/faker"; const userFactory = factory.define({ props: { firstName: () => "John", lastName: () => "Doe", }, vars: { title: () => "Mr.", greeting: () => Promise.resolve("Hello"), // Promise can also be used }, }); ``` -------------------------------- ### Factory Build Without Setting `later` Property Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/guide/placeholder.mdx Illustrates the consequence of building a factory object when a property defined with `later` has not been assigned a value, resulting in an exception. ```typescript import { factory, later } from "@factory-js/factory"; const userFactory = factory.define({ props: { firstName: () => "John", lastName: () => "Doe", fullName: later(), }, vars: {}, }); userFactory.build(); // ❌ Throws an exception because `fullName` is not set ``` -------------------------------- ### Define Property Without Default Value using `later` Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/guide/placeholder.mdx Shows how to use `later<"book" | "food">()` to define the `type` property for an `itemFactory`, ensuring that the `type` must be explicitly set when building an item. ```typescript import { factory, later } from "@factory-js/factory"; export const itemFactory = factory.define({ props: { type: later<"book" | "food">(), price: () => 0, }, vars: {}, }); ``` -------------------------------- ### Define Factory with Explicit Property Types Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/guide/defining-factory.mdx Shows how to explicitly define the types for factory properties using TypeScript generics. ```typescript import { factory } from "@factory-js/factory"; type User = { firstName: string; lastName: string }; const userFactory = factory.define({ props: { firstName: () => "John", lastName: () => "Doe", }, vars: {}, }); ``` -------------------------------- ### Chain Multiple After Hooks Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/guide/after-hook.mdx Illustrates how to chain multiple .after hooks in Factory.js. Each hook will execute sequentially after the object creation, allowing for a series of post-creation operations. ```typescript await userFactory .after(() => console.log(1)) .after(() => console.log(2)) .after(() => console.log(3)) .create(); // 👉 Logs 1 2 3 to the console ``` -------------------------------- ### Define Factory for Self-Referencing Folders (TypeScript) Source: https://github.com/factory-js/factory-js.github.io/blob/main/pages/other-orms/recipes.mdx Illustrates how to define a factory for a self-referencing model, such as a folder structure, using Factory.js and TypeScript. It shows how to manage the `parentId` property and use variables to define relationships, preventing infinite loops when creating nested structures. ```ts import { factory, later } from "@factory-js/factory"; import { faker } from "@faker-js/faker"; import { folders } from "../schema"; import { create } from "./utils/create"; // Use Drizzle's `$inferSelect` to get the type of the Folder model type Folder = (typeof folders)["$inferSelect"]; export const folderFactory = factory .define( { props: { name: () => faker.string.alphanumeric(40), parentId: later(), }, vars: { // To avoid infinite loops, the default is a root folder without a parent parent: (): Folder | undefined => undefined, }, }, (props) => create(folders, props), ) .props({ parentId: async ({ vars }) => (await vars.parent)?.id ?? null, }); ```