2021-11-05 07:21:57 +00:00
|
|
|
package devicemngmt
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
|
|
|
|
"github.com/Selly-Modules/mongodb"
|
|
|
|
"go.mongodb.org/mongo-driver/mongo"
|
|
|
|
)
|
|
|
|
|
|
|
|
// MongoDBConfig ...
|
|
|
|
type MongoDBConfig struct {
|
2021-11-08 03:43:09 +00:00
|
|
|
Host, User, Password, DBName, Mechanism, Source string
|
2021-11-05 07:21:57 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Config ...
|
|
|
|
type Config struct {
|
|
|
|
// MongoDB config, for save documents
|
|
|
|
MongoDB MongoDBConfig
|
|
|
|
// Table prefix, each service has its own prefix
|
|
|
|
TablePrefix string
|
|
|
|
}
|
|
|
|
|
|
|
|
// Service ...
|
|
|
|
type Service struct {
|
|
|
|
Config
|
|
|
|
DB *mongo.Database
|
|
|
|
}
|
|
|
|
|
|
|
|
var s *Service
|
|
|
|
|
|
|
|
// Init ...
|
2021-11-05 08:40:07 +00:00
|
|
|
func Init(config Config) (*Service, error) {
|
2021-11-08 10:23:03 +00:00
|
|
|
if config.MongoDB.Host == "" {
|
2021-11-05 08:40:07 +00:00
|
|
|
return nil, errors.New("please provide all necessary information for init device")
|
2021-11-05 07:21:57 +00:00
|
|
|
}
|
|
|
|
|
2021-11-10 10:08:39 +00:00
|
|
|
// If prefixTable is empty then it is devicemngmt
|
|
|
|
if config.TablePrefix == "" {
|
|
|
|
config.TablePrefix = tablePrefixDefault
|
|
|
|
}
|
|
|
|
|
2021-11-05 07:21:57 +00:00
|
|
|
// Connect MongoDB
|
|
|
|
db, err := mongodb.Connect(
|
|
|
|
config.MongoDB.Host,
|
|
|
|
config.MongoDB.User,
|
|
|
|
config.MongoDB.Password,
|
|
|
|
config.MongoDB.DBName,
|
2021-11-08 03:43:09 +00:00
|
|
|
config.MongoDB.Mechanism,
|
|
|
|
config.MongoDB.Source,
|
2021-11-05 07:21:57 +00:00
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
fmt.Println("Cannot init module DEVICE MANAGEMENT", err)
|
2021-11-05 08:40:07 +00:00
|
|
|
return nil, err
|
2021-11-05 07:21:57 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
s = &Service{
|
|
|
|
Config: config,
|
|
|
|
DB: db,
|
|
|
|
}
|
|
|
|
|
2021-11-05 08:40:07 +00:00
|
|
|
return s, nil
|
2021-11-05 07:21:57 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// GetInstance ...
|
|
|
|
func GetInstance() *Service {
|
|
|
|
return s
|
|
|
|
}
|