godocdb/document/document.go

53 lines
1.3 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package document
import (
"fmt"
"go.mongodb.org/mongo-driver/bson"
"git.pyer.club/kingecg/godocdb/storage"
)
// DocumentStore 管理文档的存储和检索
type DocumentStore struct {
storage *storage.LevelDBStorage
}
// NewDocumentStore 创建新的文档存储实例
func NewDocumentStore(path string) (*DocumentStore, error) {
storage, err := storage.NewLevelDBStorage(path)
if err != nil {
return nil, err
}
return &DocumentStore{storage: storage}, nil
}
// StoreDocument 存储文档
func (ds *DocumentStore) StoreDocument(id string, doc interface{}) error {
// 使用BSON序列化文档
data, err := bson.Marshal(doc)
if err != nil {
return fmt.Errorf("failed to marshal document: %v", err)
}
// 存储文档(格式: collection:id → BSON数据
key := []byte(fmt.Sprintf("documents:%s", id))
return ds.storage.Put(key, data)
}
// GetDocument 获取文档
func (ds *DocumentStore) GetDocument(id string, result interface{}) error {
key := []byte(fmt.Sprintf("documents:%s", id))
data, err := ds.storage.Get(key)
if err != nil {
return fmt.Errorf("document not found: %v", err)
}
// 使用BSON反序列化文档
return bson.Unmarshal(data, result)
}
// DeleteDocument 删除文档
func (ds *DocumentStore) DeleteDocument(id string) error {
key := []byte(fmt.Sprintf("documents:%s", id))
return ds.storage.Delete(key)
}