Data Seeding Library
Relevant source files
The following files were used as context for generating this wiki page:- packages/libraries/seed/src/index.ts
- packages/libraries/seed/src/dataset.ts
- packages/libraries/seed/src/helpers/organizations.ts
- packages/libraries/seed/README.md
- packages/cli/src/commands/seed/index.ts
- packages/cli/testing/seed.ts
- packages/libraries/seed/package.json
- packages/libraries/seed/src/helpers/api-keys.ts
The @better-auth-kit/seed library is a powerful tool designed to populate a Better-Auth database with deterministic, yet realistic, fake data. It is primarily intended for development and testing environments, enabling developers to work with a consistent and populated dataset. The library is executed through the @better-auth-kit/cli and relies on a user-defined seed script to specify which tables to seed and how to generate the data for each row.
The core functionality revolves around defining data structures for database models and using a rich set of data generators to create varied and plausible values for fields. This includes everything from simple names and emails to complex relationships using foreign keys.
Sources: packages/libraries/seed/README.md, packages/libraries/seed/package.json
Core Concepts
The seeding process is orchestrated by a few key functions that define the structure and data for the seeding operation.
Sources: packages/libraries/seed/src/index.ts
Seed() Function
The Seed() function is the main entry point for defining a seed script. It accepts a schema object, which maps model names to table definitions. It can also accept an asynchronous function that resolves to a schema object, allowing for dynamic data generation that might depend on previously generated values. This function returns an object with an execute method that the CLI invokes.
// packages/cli/testing/seed.ts:23-27
export const seed = Seed({
...users(),
...organizations(),
...apiKeys(),
});
Sources: packages/libraries/seed/src/index.ts:20-27, packages/cli/testing/seed.ts:23-27
table() Function
The table() function defines the data generation logic for a single database model. It takes two arguments:
- An object where keys are the column names and values are data generator functions from the
dataset(aliased as$). - An optional
optionsobject to specify themodelNameand the number of rows to generate (count).
It returns an asynchronous function that, when executed, generates the specified number of data rows.
Sources: packages/libraries/seed/src/index.ts:153-198
SeedConfig
Configuration for the seed script can be provided by exporting a config object of type SeedConfig. This allows for customizing the seeding behavior.
| Option | Type | Description |
|---|---|---|
deleteRowsBeforeSeeding | { enabled: boolean; models: string[] } | If enabled, it will delete all rows from the specified models before running the seed script. It prompts for confirmation in the CLI. |
rows | number | The default number of rows to generate for each table if not specified in the table() options. Defaults to 100. |
Sources: packages/libraries/seed/src/index.ts:14-15,29-31, packages/cli/testing/seed.ts:9-21
Execution Flow
The data seeding process is initiated from the command line and involves several steps, from loading configuration to executing the seed script against the database adapter.
This diagram illustrates the high-level flow when a user runs the seed command.
The CLI command seed is responsible for locating the auth configuration and the seed script(s). It supports a single seed.ts file or a seed directory containing multiple files. If a directory is found, it can run all scripts or prompt the user to select specific ones.
Sources: packages/cli/src/commands/seed/index.ts:18-119
Data Generation ($)
The library provides a comprehensive set of data generators, accessible via the exported dataset object, which is conventionally aliased as $. These generators can produce various types of realistic data.
Sources: packages/libraries/seed/src/dataset.ts
Available Generators
| Function | Description |
|---|---|
firstname() | Generates a random first name. |
lastname() | Generates a random last name. |
uuid() | Generates a random UUID. |
email() | Generates a unique email address. |
password() | Generates a hashed password string. |
randomNumber() | Generates a random number within a specified range. |
randomDate() | Generates a random date (past, future, or any). |
randomBoolean() | Generates a boolean with a given probability. |
randomCharacters() | Generates a random string of a given length. |
image() | Generates a URL for a placeholder image. |
ip() | Generates a realistic IPv4 address. |
userAgent() | Generates a random user agent string. |
foreignKey() | Fetches a value from another table to establish a relationship. |
custom() | Allows for custom data generation logic via a callback function. |
randomChoice() | Randomly picks one of the provided generator functions to execute. |
nullValue() | Returns null. |
Foreign Keys
The foreignKey generator is crucial for creating relationships between tables. It fetches records from a specified model and returns the value of a given field. It includes a local cache to minimize database queries.
// packages/libraries/seed/src/dataset.ts:133-142
const foreignKey = <FieldType extends SeedPrimitiveValue = any>({
model,
field,
unique = false,
}: {
model: string;
field: string;
unique?: boolean;
}): SeedGenerator<FieldType> => {
It will throw an error if the target model or any records within it cannot be found, ensuring data integrity during the seeding process.
Sources: packages/libraries/seed/src/dataset.ts:133-191
Helper Functions
To streamline the process of seeding common, interconnected data structures (like users, organizations, and API keys), the library provides helper functions. These helpers are pre-configured sets of table definitions.
organizations() Helper
The organizations() helper is a prime example. It can generate data for organization, member, team, and invitation models simultaneously, ensuring that relationships (e.g., a member belonging to an organization) are correctly established.
This diagram shows the models generated by the organizations helper.
The helper accepts arguments to customize field data, model names, and whether to create related entities like teams or invitations.
// packages/libraries/seed/src/helpers/organizations.ts:32-70
export function organizations<
/* ... type definitions ... */
>(
fields?: {
organization?: Partial<ConvertToSeedGenerator<TableTypes["Organization"]>>;
member?: Partial<ConvertToSeedGenerator<TableTypes["Member"]>>;
invitation?: Partial<ConvertToSeedGenerator<TableTypes["Invitation"]>>;
team?: Partial<ConvertToSeedGenerator<TableTypes["Team"]>>;
},
options?: {
modelNames?: {
organization: OrganizationModel;
member: MemberModel;
invitation: InvitationModel;
team: TeamModel;
};
count?: number;
createInvitations?: ShouldCreateInvitations;
createTeams?: ShouldCreateTeams;
createMembers?: ShouldCreateMembers;
},
) { /* ... implementation ... */ }
Other available helpers include users() and apiKeys().
Sources: packages/libraries/seed/src/helpers/organizations.ts, packages/libraries/seed/src/helpers/api-keys.ts, packages/cli/testing/seed.ts:24-26
Conclusion
The Data Seeding Library is an essential utility within the better-auth-kit ecosystem for creating robust and realistic development environments. By combining a flexible CLI, powerful data generators, and convenient helper functions, it allows developers to quickly and easily populate their database, leading to more efficient testing and development cycles. Its design, which leverages the core better-auth adapter, ensures compatibility and seamless integration.