Mongo directories validation

This commit is contained in:
cyber-dream 2023-05-04 18:55:08 +03:00
parent bea6859457
commit 313be711a9

View File

@ -4,6 +4,7 @@ import (
"context"
"errors"
"net/http"
"strconv"
"strings"
"github.com/gin-gonic/gin"
@ -242,6 +243,80 @@ func (fs *WebFileSystem) Route(route *gin.RouterGroup) {
ctx.JSON(http.StatusOK, &file)
})
route.GET("validate", func(ctx *gin.Context) {
err := fs.Validate()
if err != nil {
ctx.Status(http.StatusInternalServerError)
return
}
ctx.Status(http.StatusOK)
})
}
func (fs *WebFileSystem) Validate() error {
filter := primitive.D{
{
Key: "type",
Value: "directory",
},
}
cur, err := fs.webfsCollection.Find(context.Background(), filter)
defer cur.Close(context.Background())
if err != nil {
return err
}
directories := []*WebFSFile{}
// err = cur.All(context.Background(), directories)
// if err != nil {
// fmt.Println(err.Error())
// }
for cur.Next(context.Background()) {
dir := &WebFSFile{}
err = cur.Decode(dir)
if err != nil {
println(err.Error())
return err
}
directories = append(directories, dir)
}
for _, d := range directories {
// println(d.Name)
fs.validateDir(d)
}
return nil
}
func (fs *WebFileSystem) validateDir(dir *WebFSFile) error {
kek := dir.Data.(primitive.D).Map()["children"].(primitive.A)
_ = kek
// FolderData
children := []primitive.ObjectID{}
counter := 0
for _, v := range kek {
// println(v.(primitive.ObjectID).String())
_, err := fs.ReadByObjectID(v.(primitive.ObjectID))
if err != nil {
counter++
} else {
children = append(children, v.(primitive.ObjectID))
}
}
if counter > 0 {
println(dir.Name + " broken iDs: " + strconv.Itoa(counter))
_, err := fs.webfsCollection.UpdateByID(context.Background(), dir.MongoId, bson.M{"$set": bson.M{"data.children": children}})
if err != nil {
println(err.Error())
return err
}
}
return nil
}
type WebFSFile struct {