edge/pkg/storage/document_store.go

75 lines
1.5 KiB
Go
Raw Permalink Normal View History

2023-02-09 12:16:36 +01:00
package storage
import (
"context"
"errors"
"time"
"forge.cadoles.com/arcad/edge/pkg/storage/filter"
"github.com/oklog/ulid/v2"
)
var ErrDocumentNotFound = errors.New("document not found")
type DocumentID string
const (
DocumentAttrID = "_id"
DocumentAttrCreatedAt = "_createdAt"
DocumentAttrUpdatedAt = "_updatedAt"
)
func NewDocumentID() DocumentID {
return DocumentID(ulid.Make().String())
}
type Document map[string]interface{}
func (d Document) ID() (DocumentID, bool) {
rawID, exists := d[DocumentAttrID]
if !exists {
return "", false
}
strID, ok := rawID.(string)
2023-02-09 12:16:36 +01:00
if ok {
return DocumentID(strID), true
2023-02-09 12:16:36 +01:00
}
docID, ok := rawID.(DocumentID)
if ok {
return docID, true
}
return "", false
2023-02-09 12:16:36 +01:00
}
func (d Document) CreatedAt() (time.Time, bool) {
return d.timeAttr(DocumentAttrCreatedAt)
}
func (d Document) UpdatedAt() (time.Time, bool) {
return d.timeAttr(DocumentAttrUpdatedAt)
}
func (d Document) timeAttr(attr string) (time.Time, bool) {
rawTime, exists := d[attr]
if !exists {
return time.Time{}, false
}
t, ok := rawTime.(time.Time)
if !ok {
2023-02-09 12:16:36 +01:00
return time.Time{}, false
}
return t, true
}
type DocumentStore interface {
Get(ctx context.Context, collection string, id DocumentID) (Document, error)
Query(ctx context.Context, collection string, filter *filter.Filter, funcs ...QueryOptionFunc) ([]Document, error)
Upsert(ctx context.Context, collection string, document Document) (Document, error)
Delete(ctx context.Context, collection string, id DocumentID) error
}