This repository has been archived by the owner on Sep 14, 2021. It is now read-only.
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
a089e68
commit 8f6d41e
Showing
2 changed files
with
64 additions
and
98 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Original file line | Diff line number | Diff line change |
---|---|---|---|
@@ -0,0 +1,58 @@ | |||
package main | |||
|
|||
import ( | |||
"database/sql" | |||
"log" | |||
|
|||
"github.com/jmoiron/sqlx" | |||
) | |||
|
|||
var allCategories []Category | |||
var categoryByID map[int]Category | |||
var childCategories map[int][]int | |||
|
|||
func loadCategories() { | |||
err := dbx.Select(&allCategories, "SELECT * FROM categories") | |||
if err != nil { | |||
log.Fatal(err) | |||
} | |||
|
|||
categoryByID = make(map[int]Category, len(allCategories)) | |||
childCategories = make(map[int][]int) | |||
for _, c := range allCategories { | |||
categoryByID[c.ID] = c | |||
} | |||
|
|||
for _, c := range categoryByID { | |||
if c.ParentID > 0 { | |||
c.ParentCategoryName = categoryByID[c.ParentID].CategoryName | |||
} | |||
categoryByID[c.ID] = c | |||
|
|||
var children []int | |||
for _, child := range categoryByID { | |||
if child.ParentID == c.ID { | |||
children = append(children, child.ID) | |||
} | |||
} | |||
if len(children) > 0 { | |||
childCategories[c.ID] = children | |||
} | |||
} | |||
} | |||
|
|||
func getCategoryByID(_ sqlx.Queryer, id int) (Category, error) { | |||
c, ok := categoryByID[id] | |||
if !ok { | |||
return Category{}, sql.ErrNoRows | |||
} | |||
return c, nil | |||
} | |||
|
|||
func getChildCategories(parent int) []int { | |||
return childCategories[parent] | |||
} | |||
|
|||
func getAllCategories() []Category { | |||
return allCategories | |||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters