personal-website/webfilesystem/mongo.go
2023-05-06 01:50:57 +03:00

95 lines
1.8 KiB
Go

package webfilesystem
import (
"context"
"errors"
"go.mongodb.org/mongo-driver/bson/primitive"
)
type ReadStruct struct {
File interface{}
Filter interface{}
}
func (fs *WebFileSystem) ReadMongo(read ReadStruct) (*interface{}, error) {
err := fs.webfsCollection.FindOne(fs.ctx, read.Filter).Decode(read.File)
if err != nil {
return nil, err
}
return &read.File, nil
}
func (fs *WebFileSystem) writeMongo(file WebFSFile, parentPath string) (primitive.ObjectID, error) {
//TODO Check file existance
parentDir, err := fs.NewRead(parentPath)
if err != nil {
return primitive.NilObjectID, err
}
res, err := fs.webfsCollection.InsertOne(context.Background(), &file)
if err != nil {
return primitive.NilObjectID, err
}
fileId := fs.castInsertId(res)
fs.insertFileToDirectory(fileId, parentDir.MongoId)
return fileId, nil
}
func (fs *WebFileSystem) removeMongo(filePath string) error {
file, err := fs.NewRead(filePath)
if err != nil {
return err
}
if file.MongoId == primitive.NilObjectID {
return errors.New("TODO") //TODO
}
filter := primitive.M{
"_id": file.MongoId,
}
res, err := fs.webfsCollection.DeleteOne(fs.ctx, filter)
if err != nil {
return err
}
if res.DeletedCount < 1 {
return errors.New("no file removed")
}
return nil
}
func (fs *WebFileSystem) Validate() error {
filter := primitive.D{
{
Key: "type",
Value: "directory",
},
}
cur, err := fs.webfsCollection.Find(context.Background(), filter)
if err != nil {
return err
}
defer cur.Close(context.Background())
directories := []*WebFSFile{}
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 {
fs.validateDir(d)
}
return nil
}