2019-10-07 08:14:47 -06:00
|
|
|
// Copyright (c) Mainflux
|
2018-08-26 13:15:48 +02:00
|
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
|
|
|
2018-06-01 15:50:23 +02:00
|
|
|
package mongodb
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
|
2019-04-16 14:58:56 +02:00
|
|
|
"go.mongodb.org/mongo-driver/mongo"
|
2018-06-01 15:50:23 +02:00
|
|
|
|
2021-01-11 23:55:34 +01:00
|
|
|
"github.com/mainflux/mainflux/consumers"
|
2020-06-03 15:16:19 +02:00
|
|
|
"github.com/mainflux/mainflux/pkg/errors"
|
2020-12-30 15:43:04 +01:00
|
|
|
"github.com/mainflux/mainflux/pkg/transformers/json"
|
2020-06-03 15:16:19 +02:00
|
|
|
"github.com/mainflux/mainflux/pkg/transformers/senml"
|
2018-06-01 15:50:23 +02:00
|
|
|
)
|
|
|
|
|
2020-12-30 15:43:04 +01:00
|
|
|
const (
|
|
|
|
senmlCollection string = "messages"
|
|
|
|
jsonCollection string = "json"
|
|
|
|
)
|
2018-06-01 15:50:23 +02:00
|
|
|
|
2020-12-30 15:43:04 +01:00
|
|
|
var (
|
|
|
|
errSaveMessage = errors.New("failed to save message to mongodb database")
|
|
|
|
errMessageFormat = errors.New("invalid message format")
|
|
|
|
)
|
2020-04-13 12:57:53 +02:00
|
|
|
|
2021-01-11 23:55:34 +01:00
|
|
|
var _ consumers.Consumer = (*mongoRepo)(nil)
|
2018-06-01 15:50:23 +02:00
|
|
|
|
|
|
|
type mongoRepo struct {
|
|
|
|
db *mongo.Database
|
|
|
|
}
|
|
|
|
|
|
|
|
// New returns new MongoDB writer.
|
2021-01-11 23:55:34 +01:00
|
|
|
func New(db *mongo.Database) consumers.Consumer {
|
2018-08-08 13:38:34 +02:00
|
|
|
return &mongoRepo{db}
|
2018-06-01 15:50:23 +02:00
|
|
|
}
|
|
|
|
|
2021-01-11 23:55:34 +01:00
|
|
|
func (repo *mongoRepo) Consume(message interface{}) error {
|
2020-12-30 15:43:04 +01:00
|
|
|
switch m := message.(type) {
|
|
|
|
case json.Messages:
|
|
|
|
return repo.saveJSON(m)
|
|
|
|
default:
|
|
|
|
return repo.saveSenml(m)
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
func (repo *mongoRepo) saveSenml(messages interface{}) error {
|
|
|
|
msgs, ok := messages.([]senml.Message)
|
|
|
|
if !ok {
|
|
|
|
return errSaveMessage
|
|
|
|
}
|
|
|
|
coll := repo.db.Collection(senmlCollection)
|
|
|
|
var dbMsgs []interface{}
|
|
|
|
for _, msg := range msgs {
|
|
|
|
dbMsgs = append(dbMsgs, msg)
|
|
|
|
}
|
|
|
|
|
|
|
|
_, err := coll.InsertMany(context.Background(), dbMsgs)
|
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(errSaveMessage, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (repo *mongoRepo) saveJSON(msgs json.Messages) error {
|
|
|
|
m := []interface{}{}
|
|
|
|
for _, msg := range msgs.Data {
|
|
|
|
m = append(m, msg)
|
2018-11-05 19:18:51 +01:00
|
|
|
}
|
|
|
|
|
2020-12-30 15:43:04 +01:00
|
|
|
coll := repo.db.Collection(msgs.Format)
|
|
|
|
|
|
|
|
_, err := coll.InsertMany(context.Background(), m)
|
2020-04-13 12:57:53 +02:00
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(errSaveMessage, err)
|
|
|
|
}
|
2020-12-30 15:43:04 +01:00
|
|
|
|
2020-04-13 12:57:53 +02:00
|
|
|
return nil
|
2018-06-01 15:50:23 +02:00
|
|
|
}
|