package mongodb import ( "context" "git.aiterp.net/rpdata/api/internal/generate" "git.aiterp.net/rpdata/api/models" "git.aiterp.net/rpdata/api/repositories" "github.com/globalsign/mgo" "github.com/globalsign/mgo/bson" ) type keyRepository struct { keys *mgo.Collection } func newKeyRepository(db *mgo.Database) (repositories.KeyRepository, error) { collection := db.C("auth.keys") err := collection.EnsureIndexKey("user") if err != nil { return nil, err } return &keyRepository{keys: collection}, nil } func (r *keyRepository) Find(ctx context.Context, id string) (*models.Key, error) { key := models.Key{} err := r.keys.FindId(id).One(&key) if err != nil { return nil, err } return &key, err } func (r *keyRepository) List(ctx context.Context, filter models.KeyFilter) ([]*models.Key, error) { query := bson.M{} if filter.UserID != nil { query["user"] = *filter.UserID } keys := make([]*models.Key, 0, 4) err := r.keys.Find(query).All(&keys) if err != nil { if err == mgo.ErrNotFound { return nil, nil } return nil, err } return keys, nil } func (r *keyRepository) Insert(ctx context.Context, key models.Key) (*models.Key, error) { key.ID = generate.KeyID() err := r.keys.Insert(&key) if err != nil { return nil, err } return &key, nil } func (r *keyRepository) Delete(ctx context.Context, key models.Key) error { return r.keys.RemoveId(key.ID) }