personal-website/webfs/webfs.go

132 lines
3.0 KiB
Go

package webfs
import (
"context"
"errors"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"log"
)
var mcli *mongo.Client
var filesTable *mongo.Collection
var filesData *mongo.Collection
//var ctx context.Context
//type File struct {
// ID primitive.ObjectID `json:"ID" bson:"_id"`
// Header FileHeader `json:"header" bson:"header"`
// Body interface{} `json:"body" bson:"body"`
//}
type FileHeader struct {
Name string `json:"name" bson:"name"`
DataID primitive.ObjectID `json:"dataID" bson:"data_id"`
Type string `json:"type" bson:"type"`
}
//type FileBody interface {
//}
func Init(ctx context.Context, mongoConnect string, mongoDatabaseString string, filesCollectionName string) (err error) {
//ctx = ctx
clientOptions := options.Client().ApplyURI(mongoConnect)
// Create mongo client for in package usage
mcli, err = mongo.Connect(ctx, clientOptions)
if err != nil {
return err
}
// Ping database for test new connection
err = mcli.Ping(ctx, nil)
if err != nil {
log.Fatal(err)
}
filesTable = mcli.Database(mongoDatabaseString).Collection("table-3")
filesData = mcli.Database(mongoDatabaseString).Collection("data-3")
return nil
}
func CreateFile(ctx context.Context, path string, fileHeader FileHeader, fileData interface{}) (id primitive.ObjectID, err error) {
//parentPath := GetParentPath(path)
res, err := filesData.InsertOne(ctx, fileData)
if err != nil {
return
}
splittedPath := SplitPath(path)
dataId := res.InsertedID.(primitive.ObjectID)
fileHeader.Name = splittedPath[len(splittedPath)-1]
fileHeader.DataID = dataId
res, err = filesTable.InsertOne(ctx, fileHeader)
if err != nil {
return
}
id = res.InsertedID.(primitive.ObjectID)
return
}
func CreateDir(ctx context.Context, path string) (id primitive.ObjectID, err error) {
if len(path) < 2 {
err = errors.New("TODO")
return //TODO
}
splittedPath := SplitPath(path)
parentPath := GetParentPath(path)
r := File{
Header: FileHeader{
Name: splittedPath[len(splittedPath)-1],
Type: "directory",
},
Body: Directory{Children: []primitive.ObjectID{}},
}
id, err = CreateFile(ctx, "", r)
return
}
func readFile[T interface{}](ctx context.Context, fileID primitive.ObjectID) (file File) {
filter := primitive.M{
"_id": fileID,
}
res, err := filesTable.FindOne(ctx, filter)
}
//func CreateRoot(ctx context.Context) (id primitive.ObjectID, err error) {
// r := File{
// Header: FileHeader{
// Name: "/",
// Type: "directory",
// },
// Body: Directory{Children: []primitive.ObjectID{}},
// }
//
// id, err = CreateFile(ctx, "", r)
// return
//}
//func (fs *WebFileSystem) Read(filePath string, fileData interface{}) (*FileHeader, error) {
// fileId, err := fs.FindFile(filePath)
// if err != nil {
// return nil, err
// }
//
// fileHeader, err := fs.ReadByObjectID(fileId, fileData)
// if err != nil {
// return nil, err
// }
//
// return fileHeader, nil
//}