๐ Links
- github: andriishupta/strapi-generate-seed-data
- Strapi's video with a general idea of how to "Generate dummy data"
๐ฐ Also published on
๐ค Motivation
Strapi is powerful open-source headless CMS that helps projects control code customization with extensibility and, at the same time, don't worry about implementing a full-blown Content Management System on their own.
So, after you have set up your Strapi, you want to build Front-End on top of it. You hire front-end developers who are stuck: "Ye, I can query for data via REST and GraphQL, but what data should I see? Could I have an example?"
๐ฌ
To avoid this, we would generate example data upfront.
๐ฑ How to seed data?
"Generate dummy data"
There is the video in Strapi's Video-library that gave me a direction on how to do it.
The idea is simple:
- use
bootstrap
function - use Entity Service API for interactions
- generate dummy data with @faker-js/faker
Tip
Your case ๐ฏ would be more complicated, so don't forget that you could take almost everything from Strapi's source code.
The flow:
- find a place on Strapi Admin you want to copy
- check URL and Network(in developer's inspection) to understand what is called
- find code(start with controller) that corresponds to that calls
- enjoy
๐งโ๐ป Code
We have a simple Todo application(duh) with a Todo collection and a Todo List as a page(single type) that we want to send to the front-end. Also, our Todos has media functionality, so we upload some.
In the bootstrap function, we check for the development environment and decide if we should run seeding or not. Seeding would automatically run on the very first application run(valid when a developer clones an existing repository) and could be re-run with yarn seed
to force seed, which clears old and creates new data - FORCE_APP_BOOTSTRAP_ONLY
.
๐source code
Collection Type
To create a todo using Entity Service API, we need to call the create
method with data that matches our entity. In the current example and during seeding, I have used "bulk promises" to run requests in parallel cause they are not dependent on each other.
๐ source code
And using faker, we fill a todo like this:
Single Type
Fulfilling the "Todo List page" is the same as Collection, but keep in mind that it could be only one entry all the time. Also, it contains a Todo relation, so we get five todos to fill it.
๐ source code
Media Upload
To attach media on a todo, we first need to upload that media and then link its id to the entity. Code has been copied from Strapi's source code, modified, and I just created a helper function.
๐ source code
Example in Todo:
โ Results
After opening the Admin panel, you will see generated data.
โจ
Initially, I implemented this for Developer DAO's website developerdao.com. Original code is located here(archived and moved to monorepo).
Thanks for reading!