micrach/repositories/seeds.go
Yanislav Igonin db8a46cdf1
build: modernize Wave 1 baseline (#16)
* chore: add agents md

* docs: expand repository and setup guides

* docs: plan project modernization

* docs: add Wave 1 implementation plan

* test: characterize legacy behavior

* build: update Go and Fiber v2

* fix(gateway): preserve duplicate auth behavior

* refactor(db): migrate to pgx v5

* refactor: replace deprecated I/O APIs

* build: add local PostgreSQL compose

* build: add multi-stage image

* ci: replace legacy deployment workflow

* fix(deps): update vulnerable Go modules

* docs: document modern development workflow
2026-07-16 16:08:54 +09:00

117 lines
2.4 KiB
Go

package repositories
import (
"context"
"log"
"math/rand"
"time"
)
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
func randSeq(n int) string {
b := make([]rune, n)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}
func getFile(id, postId int, name string) File {
return File{
ID: id,
PostID: postId,
Name: name,
Ext: "image/jpeg",
Size: 10000,
CreatedAt: time.Now(),
}
}
// Creates post mock with mock files in it
//
// id - post ID, pid - parent post ID.
func getPost(id int, pid *int) Post {
var parentID int
if pid == nil {
parentID = 0
} else {
parentID = *pid
}
var isParent bool
if parentID == 0 {
isParent = true
} else {
isParent = false
}
return Post{
ID: id,
IsParent: isParent,
ParentID: &parentID,
IsDeleted: false,
Title: randSeq(rand.Intn(100)),
Text: randSeq(rand.Intn(100)),
IsSage: false,
// Maybe somewhen else I'll add url field for files
// Files: []File{
// getFile(2, id, "https://memepedia.ru/wp-content/uploads/2018/03/ebanyy-rot-etogo-kazino.png"),
// getFile(1, id, "https://memepedia.ru/wp-content/uploads/2018/03/ebanyy-rot-etogo-kazino.png"),
// },
Files: []File{},
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
}
func seedDb(ctx context.Context) {
// preparing seed data with parent posts with files
var parentPosts []Post
for i := 1; i < 10; i++ {
post := getPost(i, nil)
parentPosts = append(parentPosts, post)
}
for _, parentPost := range parentPosts {
// saving parent post in db
parentPostID, err := Posts.Create(ctx, parentPost)
if err != nil {
log.Panicln(err)
}
// saving parent post files
for _, file := range parentPost.Files {
file.PostID = parentPostID
err = Files.Create(ctx, file)
if err != nil {
log.Panicln(err)
}
}
// making child posts
for i := 0; i < 10; i++ {
// getting child post with files
childPost := getPost(0, &parentPostID)
childPostID, err := Posts.Create(ctx, childPost)
if err != nil {
log.Panicln(err)
}
// saving child post files
for _, file := range childPost.Files {
file.PostID = childPostID
err = Files.Create(ctx, file)
if err != nil {
log.Panicln(err)
}
}
}
}
}
func Seed(ctx context.Context) {
seedDb(ctx)
log.Println("seeds - online")
}