micrach/repositories/seeds.go

116 lines
2.3 KiB
Go
Raw Permalink Normal View History

2021-08-30 12:09:27 +03:00
package repositories
2021-08-31 19:18:27 +03:00
import (
2021-08-31 22:10:24 +03:00
"log"
2021-08-31 19:18:27 +03:00
"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)
}
2021-08-30 12:09:27 +03:00
func getFile(id, postId int, name string) File {
return File{
ID: id,
PostID: postId,
Name: name,
Ext: "image/jpeg",
Size: 10000,
CreatedAt: time.Now(),
}
}
2021-09-01 18:51:15 +03:00
// Creates post mock with mock files in it
//
// id - post ID, pid - parent post ID.
2021-08-31 22:10:24 +03:00
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
}
2021-08-30 12:09:27 +03:00
return Post{
2021-08-31 19:48:02 +03:00
ID: id,
2021-08-31 22:10:24 +03:00
IsParent: isParent,
2022-02-03 18:22:46 +03:00
ParentID: &parentID,
2021-08-31 19:48:02 +03:00
IsDeleted: false,
Title: randSeq(rand.Intn(100)),
Text: randSeq(rand.Intn(100)),
IsSage: false,
2021-10-16 14:17:15 +03:00
// 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{},
2021-08-30 12:09:27 +03:00
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
}
2021-09-01 15:48:39 +03:00
func seedDb() {
2021-09-01 18:51:15 +03:00
// preparing seed data with parent posts with files
var parentPosts []Post
2021-09-04 21:46:56 +03:00
for i := 1; i < 10; i++ {
2021-08-31 22:10:24 +03:00
post := getPost(i, nil)
2021-09-01 18:51:15 +03:00
parentPosts = append(parentPosts, post)
2021-08-31 22:10:24 +03:00
}
2021-09-01 18:51:15 +03:00
for _, parentPost := range parentPosts {
// saving parent post in db
parentPostID, err := Posts.Create(parentPost)
2021-08-31 22:51:31 +03:00
if err != nil {
log.Panicln(err)
}
2021-09-01 18:51:15 +03:00
// saving parent post files
for _, file := range parentPost.Files {
file.PostID = parentPostID
err = Files.Create(file)
if err != nil {
log.Panicln(err)
}
}
// making child posts
2021-09-04 21:46:56 +03:00
for i := 0; i < 10; i++ {
2021-09-01 18:51:15 +03:00
// getting child post with files
childPost := getPost(0, &parentPostID)
childPostID, err := Posts.Create(childPost)
if err != nil {
log.Panicln(err)
}
// saving child post files
for _, file := range childPost.Files {
file.PostID = childPostID
err = Files.Create(file)
if err != nil {
log.Panicln(err)
}
}
}
2021-08-31 22:10:24 +03:00
}
}
2021-09-01 15:48:39 +03:00
func Seed() {
2021-09-08 15:39:09 +03:00
seedDb()
2021-08-31 22:10:24 +03:00
log.Println("mocks - online")
2021-08-30 12:09:27 +03:00
}