Skip to content

Seeding Data

Joist provides a seed helper for populating your local/test database with some initial data, using the same factories you use in your tests.

Import seed from joist-orm/pg and pass an async function that creates your data:

seed.ts
import { seed } from "joist-orm/pg";
import { newAuthor, newPublisher } from "./entities";
seed(async (em) => {
const p = newPublisher(em, { name: "Penguin" });
newAuthor(em, { firstName: "Jane", publisher: p });
});

Then run it with ts-node (or your runner of choice), with NODE_ENV set to local or test:

Terminal window
NODE_ENV=local ts-node seed.ts

The seed helper will:

  • Assert NODE_ENV is local or test (it refuses to run otherwise, because it resets the database)
  • Call flush_database() to reset the database (see Fast Database Resets)
  • Create an EntityManager backed by the PostgresDriver
  • Run your function and em.flush() the results

Connection settings are read from the environment via newPgConnectionConfig (i.e. DATABASE_URL, or the individual DB_HOST/DB_PORT/DB_USER/DB_PASSWORD/DB_DATABASE variables), so make sure your env is loaded before running the script.