In this lesson, we see how we can create initial data in our database. Our keystone
instance has an async onConnect
method that will run when a successful connection has been made to the database. We hook into that and create new items with keystone.createItems()
.
Instructor: [00:00] I have an instance of Keystone here with a single list, a list of cats. If I start my server and then go to the admin UI, we can see that we currently have zero cats. Typically, you'd start creating cats like this -- cat one, cat two, cat three. But there might be a scenario where you would want to have some initial data in your app to get you going.
[00:25] Our Keystone instance has an a-sync on connect method that will run when a successful connection has been made to the database. What we want to do here is to create some initial data.
[00:37] We can create items with Keystone that create items which expect some data that matches our schema. In our case, we define the cat list. We'll have a key of cats and pass an array of objects.
[00:50] We only have a field called name. Let's create name, Felix, name, Pixel, and name, Chubby. Let's also log a message in the console, creating initial data and add three cat emojis.
[01:08] Let's stop and restart our dev server. You can see the log here just after connecting to the database. If I refresh the admin UI, we can see our three cats have been added. Nice. We now have six cats in our database.
[01:23] Hang on a minute. If I restart my server again, if I refresh the admin UI, I now have nine cats. Whoops, our three initial data cats have been duplicated. That's probably not what we want. What we need is to create initial data only if there are no cats in the database.
[01:40] Here's a way you can achieve that. It works for this demo, but I would not recommend using this in production. I'm going to get a list of existing cats like so. Await Keystone that lists that cat that adapter that finds all. Now I can write a block that checks if the number of cats is zero, and wraps the code in there to only run it under that condition.
[02:04] Let's move that comments inside that div block too. I'll restart the server once again. You'll notice that our initial data message is gone now. Our admin UI still has nine items. Good. Let's delete them all and restart again.
[02:22] The message is here as we hoped. We have our three initial data cats. Just to triple-check, let's delete two of them and keep Chubby. Restart the server. No new cats are created. Sweet.