1
0
mirror of https://github.com/mainflux/mainflux.git synced 2025-05-09 19:29:29 +08:00
Dušan Borovčanin 6b7dc54c8b
NOISSUE - Switch to Consumers interface (#1316)
* Replace Writer with Consumer

Signed-off-by: dusanb94 <dusan.borovcanin@mainflux.com>

* Add Notifications package

Signed-off-by: dusanb94 <dusan.borovcanin@mainflux.com>

* Update Consumer Start

Signed-off-by: dusanb94 <dusan.borovcanin@mainflux.com>

* Fix Readers

Signed-off-by: dusanb94 <dusan.borovcanin@mainflux.com>

* Fix Consumer naming

Signed-off-by: dusanb94 <dusan.borovcanin@mainflux.com>

* Add repo to Notify

Signed-off-by: dusanb94 <dusan.borovcanin@mainflux.com>

* Remove notify

Signed-off-by: dusanb94 <dusan.borovcanin@mainflux.com>

* Rename consumer field in middlewares

Signed-off-by: dusanb94 <dusan.borovcanin@mainflux.com>

* Fix remarks and add Readme

Signed-off-by: dusanb94 <dusan.borovcanin@mainflux.com>
2021-01-11 23:55:34 +01:00

82 lines
1.6 KiB
Go

// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package mongodb
import (
"context"
"go.mongodb.org/mongo-driver/mongo"
"github.com/mainflux/mainflux/consumers"
"github.com/mainflux/mainflux/pkg/errors"
"github.com/mainflux/mainflux/pkg/transformers/json"
"github.com/mainflux/mainflux/pkg/transformers/senml"
)
const (
senmlCollection string = "messages"
jsonCollection string = "json"
)
var (
errSaveMessage = errors.New("failed to save message to mongodb database")
errMessageFormat = errors.New("invalid message format")
)
var _ consumers.Consumer = (*mongoRepo)(nil)
type mongoRepo struct {
db *mongo.Database
}
// New returns new MongoDB writer.
func New(db *mongo.Database) consumers.Consumer {
return &mongoRepo{db}
}
func (repo *mongoRepo) Consume(message interface{}) error {
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)
}
coll := repo.db.Collection(msgs.Format)
_, err := coll.InsertMany(context.Background(), m)
if err != nil {
return errors.Wrap(errSaveMessage, err)
}
return nil
}