94 lines
2.0 KiB
Go
94 lines
2.0 KiB
Go
package dal
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
"go.mongodb.org/mongo-driver/bson"
|
|
"go.mongodb.org/mongo-driver/mongo"
|
|
"go.mongodb.org/mongo-driver/mongo/options"
|
|
)
|
|
|
|
type Quote struct {
|
|
ID string `bson:"_id" json:"currency"` // Currency As ID
|
|
Date time.Time `bson:"Date" json:"date"` // Date in cbr.ru
|
|
IDCb string `bson:"IDCb" json:"id-cb"`
|
|
NumCode int `bson:"NumCode" json:"num-code"`
|
|
Nominal int `bson:"Nominal" json:"nominal"`
|
|
Name string `bson:"Name" json:"name"` // Name in cbr.ru e.g. «Евро»
|
|
Value float64 `bson:"Value" json:"value"`
|
|
UpdatedAt time.Time `bson:"UpdatedAt" json:"updated-at"`
|
|
}
|
|
|
|
const (
|
|
DefaultCurrency = "RUB"
|
|
)
|
|
|
|
// UpdateQuote with upsert option
|
|
func (mc *MongoConnection) UpdateQuote(ctx context.Context, record *Quote) error {
|
|
filter := bson.M{"_id": record.ID}
|
|
now := time.Now()
|
|
|
|
if record.ID == "" {
|
|
err := errors.New("got empty id")
|
|
mc.hl.Emit(ErrorInsertQuote{err})
|
|
return err
|
|
}
|
|
|
|
record.UpdatedAt = now
|
|
opts := options.Update().SetUpsert(true)
|
|
|
|
update := bson.M{"$set": record}
|
|
_, err := mc.coll["quote"].UpdateOne(ctx, filter, update, opts)
|
|
|
|
if err != nil {
|
|
fmt.Println(record.ID)
|
|
mc.hl.Emit(ErrorUpdateQuote{err})
|
|
} else {
|
|
mc.hl.Emit(InfoUpdateQuote{})
|
|
}
|
|
|
|
return err
|
|
}
|
|
|
|
func (mc *MongoConnection) GetQuote(ctx context.Context, id string) (*Quote, error) {
|
|
filter := bson.M{"_id": id}
|
|
|
|
var result Quote
|
|
|
|
err := mc.coll["quote"].FindOne(ctx, filter).Decode(&result)
|
|
|
|
if err == mongo.ErrNoDocuments {
|
|
return nil, nil
|
|
} else {
|
|
if err != nil {
|
|
mc.hl.Emit(ErrorGetQuote{err})
|
|
}
|
|
}
|
|
|
|
return &result, nil
|
|
}
|
|
|
|
func (mc *MongoConnection) GetQuoteList(ctx context.Context) ([]Quote, error) {
|
|
cursor, err := mc.coll["quote"].Find(ctx, bson.M{})
|
|
|
|
if err != nil {
|
|
mc.hl.Emit(ErrorGetQuoteList{err})
|
|
return nil, err
|
|
}
|
|
|
|
var result []Quote
|
|
err = cursor.All(ctx, &result)
|
|
|
|
if err != nil {
|
|
mc.hl.Emit(ErrorGetQuoteList{err})
|
|
return nil, err
|
|
}
|
|
|
|
mc.hl.Emit(InfoGetQuoteList{})
|
|
|
|
return result, nil
|
|
}
|