Building a Website Builder: Seed Database with Default Data

For my Coding with Callie website builder to function properly, an admin user (aka me), a home page, and a wild card page need to exist in my database πŸ‘©πŸ»β€πŸ’»

So, I wrote a Seed function that my Go API calls when it starts up to create everything automatically 🌱

βœ… It pulls my admin password from my environment variables, hashes that password using bcrypt, and then adds an admin user to the Users table.

βœ… Then, it creates a published home page so that end users have something to see immediately when they load β€˜www.coding-with-callie.com’.

βœ… Finally, it creates a wildcard page so that any other route an end user types into their browser shows a β€˜Page Not Found’ component.

A potential issue with this plan is that we only want the Seed function to add these items if they don’t already exist. I didn’t want to make extra database calls to check for an admin user, home page, or wildcard page before first; so, instead, I added a unique constraint on the username and email columns in the Users table and the menu_name and path columns in the Pages table πŸ™…πŸ»β€β™€οΈ

Then, I added β€˜ON CONFLICT (columns with unique constraints) DO NOTHING’ to my SQL commands. This way, my Seed function works as I intended and only adds the data I want to the database one time πŸ₯³

What do you think?! πŸ€”

You May Also Like