Skip to content

Commit

Permalink
Update seeder to make idempotent (to rework)
Browse files Browse the repository at this point in the history
  • Loading branch information
leomorpho committed Sep 17, 2024
1 parent 6ebae52 commit 9145bae
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 5 deletions.
14 changes: 9 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,15 @@ This started as a fork of [pagoda](https://github.com/mikestefanello/pagoda), fo

To get up and running with GoShip:
```bash
make up
make seed

# NOTE: the static assets (JS/CSS) are only generated on first run, so if you go to `localhost:8000` after only
# running `make watch`, you will
# The below command will:
# - set up the postgres/redis/mailer containers
# - build the JS/CSS assets
# - seed the DB with test users
# - start the project in watch mode
make init

# Running init will fully scrap your state and start with fresh new containers.
# After running `make init` the first time, just use the below for everyday work.
make watch
```

Expand Down
19 changes: 19 additions & 0 deletions seeder/seeder.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (

"github.com/mikestefanello/pagoda/config"
"github.com/mikestefanello/pagoda/ent"
"github.com/mikestefanello/pagoda/ent/user"
"github.com/mikestefanello/pagoda/pkg/domain"
"github.com/mikestefanello/pagoda/pkg/repos/emailsmanager"
"github.com/mikestefanello/pagoda/pkg/repos/notifierrepo"
Expand Down Expand Up @@ -65,6 +66,17 @@ func SeedUsers(cfg *config.Config, client *ent.Client, useS3 bool) error {

// Wrapper function to create a user and ignore if exists
createUser := func(name, email, password string) *ent.User {
// Check if the user already exists
_, err := client.User.
Query().
Where(user.EmailEQ(email)).
Only(ctx)

if err == nil {
// User already exists
log.Printf("User with email %s already exists. Skipping.", email)
return nil
}

user, err := client.User.
Create().
Expand Down Expand Up @@ -125,6 +137,13 @@ func SeedUsers(cfg *config.Config, client *ent.Client, useS3 bool) error {
// TODO: for prod, use passwords set in env var
// Create users
alice := createUser("Alice Bonjovi", "[email protected]", hashPassword("password"))
if alice == nil {
// createUser returns nil if user already exists
// NOTE: to clean up later, but right now it's the mechanism to make this seeder idempotent (yes, it's ugly, to rework)

return nil
}

bob := createUser("Bob Lupin", "[email protected]", hashPassword("password"))
sandrine := createUser("Sandrine Bonnaire", "[email protected]", hashPassword("password"))
luca := createUser("Luca George", "[email protected]", hashPassword("password"))
Expand Down

0 comments on commit 9145bae

Please sign in to comment.