Seed Data with Custom CLI Script

In this chapter, you'll learn how to seed data using a custom CLI script.

How to Seed Data#

To seed dummy data for development or demo purposes, use a custom CLI script.

In the CLI script, use your custom workflows or Medusa's existing workflows, which you can browse in this reference, to seed data.

Example: Seed Dummy Products#

In this section, you'll follow an example of creating a custom CLI script that seeds fifty dummy products.

First, install the Faker library to generate random data in your script:

Then, create the file src/scripts/demo-products.ts with the following content:

src/scripts/demo-products.ts
11} from "@medusajs/medusa/core-flows"12
13export default async function seedDummyProducts({14  container,15}: ExecArgs) {16  const salesChannelModuleService = container.resolve(17    Modules.SALES_CHANNEL18  )19  const logger = container.resolve(20    ContainerRegistrationKeys.LOGGER21  )22  const query = container.resolve(23    ContainerRegistrationKeys.QUERY24  )25
26  const defaultSalesChannel = await salesChannelModuleService27    .listSalesChannels({28      name: "Default Sales Channel",29    })30
31  const sizeOptions = ["S", "M", "L", "XL"]32  const colorOptions = ["Black", "White"]33  const currency_code = "eur"34  const productsNum = 5035
36  // TODO seed products37}

So far, in the script, you:

  • Resolve the Sales Channel Module's main service to retrieve the application's default sales channel. This is the sales channel the dummy products will be available in.
  • Resolve the Logger to log messages in the terminal, and Query to later retrieve data useful for the seeded products.
  • Initialize some default data to use when seeding the products next.

Next, replace the TODO with the following:

src/scripts/demo-products.ts
1const productsData = new Array(productsNum).fill(0).map((_, index) => {2  const title = faker.commerce.product() + "_" + index3  return {4    title,5    is_giftcard: true,6    description: faker.commerce.productDescription(),7    status: ProductStatus.PUBLISHED,8    options: [9      {10        title: "Size",11        values: sizeOptions,12      },13      {14        title: "Color",15        values: colorOptions,16      },17    ],18    images: [19      {20        url: faker.image.urlPlaceholder({21          text: title,22        }),23      },24      {25        url: faker.image.urlPlaceholder({26          text: title,27        }),28      },29    ],30    variants: new Array(10).fill(0).map((_, variantIndex) => ({31      title: `${title} ${variantIndex}`,32      sku: `variant-${variantIndex}${index}`,33      prices: new Array(10).fill(0).map((_, priceIndex) => ({34        currency_code,35        amount: 10 * priceIndex,36      })),37      options: {38        Size: sizeOptions[Math.floor(Math.random() * 3)],39      },40    })),41    sales_channels: [42      {43        id: defaultSalesChannel[0].id,44      },45    ],46  }47})48
49// TODO seed products

You generate fifty products using the sales channel and variables you initialized, and using Faker for random data, such as the product's title or images.

Then, replace the new TODO with the following:

src/scripts/demo-products.ts
1const { result: products } = await createProductsWorkflow(container).run({2  input: {3    products: productsData,4  },5})6
7logger.info(`Seeded ${products.length} products.`)8
9// TODO add inventory levels

You create the generated products using the createProductsWorkflow imported previously from @medusajs/medusa/core-flows. It accepts the product data as input, and returns the created products.

Only thing left is to create inventory levels for the products. So, replace the last TODO with the following:

src/scripts/demo-products.ts
1logger.info("Seeding inventory levels.")2
3const { data: stockLocations } = await query.graph({4  entity: "stock_location",5  fields: ["id"],6})7
8const { data: inventoryItems } = await query.graph({9  entity: "inventory_item",10  fields: ["id"],11})12
13const inventoryLevels = inventoryItems.map((inventoryItem) => ({14  location_id: stockLocations[0].id,15  stocked_quantity: 1000000,16  inventory_item_id: inventoryItem.id,17}))18
19await createInventoryLevelsWorkflow(container).run({20  input: {21    inventory_levels: inventoryLevels,22  },23})24
25logger.info("Finished seeding inventory levels data.")

You use Query to retrieve the stock location, to use the first location in the application, and the inventory items.

Then, you generate inventory levels for each inventory item, associating it with the first stock location.

Finally, you use the createInventoryLevelsWorkflow imported from @medusajs/medusa/core-flows to create the inventory levels.

Test Script#

To test out the script, run the following command in your project's directory:

Terminal
npx medusa exec ./src/scripts/demo-products.ts

This seeds the products to your database. If you run your Medusa application and view the products in the dashboard, you'll find fifty new products.

Was this chapter helpful?
Edit this page