105 lines
1.8 KiB
Go
105 lines
1.8 KiB
Go
|
package dal
|
||
|
|
||
|
import (
|
||
|
"bitbucket.org/BlackBroker/heruvym/model"
|
||
|
"context"
|
||
|
"github.com/rs/xid"
|
||
|
"github.com/themakers/hlog"
|
||
|
"go.mongodb.org/mongo-driver/mongo"
|
||
|
"go.mongodb.org/mongo-driver/mongo/options"
|
||
|
"go.mongodb.org/mongo-driver/mongo/readpref"
|
||
|
"time"
|
||
|
)
|
||
|
|
||
|
const collMessages = "messages"
|
||
|
|
||
|
type DAL struct {
|
||
|
logger hlog.Logger
|
||
|
col *mongo.Collection
|
||
|
client *mongo.Client
|
||
|
}
|
||
|
|
||
|
type ErrorConnectToDB struct {
|
||
|
Err error
|
||
|
MongoURI string
|
||
|
}
|
||
|
|
||
|
type ErrorPingDB struct {
|
||
|
Err error
|
||
|
MongoURI string
|
||
|
}
|
||
|
|
||
|
type InfoPing struct {
|
||
|
MongoURI string
|
||
|
Nanoseconds int
|
||
|
}
|
||
|
|
||
|
func New(
|
||
|
ctx context.Context,
|
||
|
mongoURI, database string,
|
||
|
log hlog.Logger,
|
||
|
) (*DAL, error) {
|
||
|
client, err := mongo.Connect(ctx, options.Client().ApplyURI(mongoURI))
|
||
|
if err != nil {
|
||
|
log.Emit(ErrorConnectToDB{
|
||
|
Err: err,
|
||
|
MongoURI: mongoURI,
|
||
|
})
|
||
|
return nil, err
|
||
|
}
|
||
|
|
||
|
before := time.Now().Nanosecond()
|
||
|
|
||
|
if err := client.Ping(ctx, readpref.PrimaryPreferred()); err != nil {
|
||
|
log.Emit(ErrorPingDB{
|
||
|
Err: err,
|
||
|
MongoURI: mongoURI,
|
||
|
})
|
||
|
|
||
|
return nil, err
|
||
|
}
|
||
|
|
||
|
log.Emit(InfoPing{
|
||
|
MongoURI: mongoURI,
|
||
|
Nanoseconds: time.Now().Nanosecond() - before,
|
||
|
})
|
||
|
|
||
|
return &DAL{
|
||
|
client: client,
|
||
|
col: client.Database(database).Collection(collMessages),
|
||
|
logger: log.Module("DAL"),
|
||
|
}, nil
|
||
|
}
|
||
|
|
||
|
type ErrorInsert struct {
|
||
|
Err error
|
||
|
UserID, SessionID string
|
||
|
}
|
||
|
|
||
|
func (d *DAL) PutMessage(
|
||
|
ctx context.Context,
|
||
|
title, message, userID, sessionID string,
|
||
|
files []string,
|
||
|
) error {
|
||
|
|
||
|
if _, err := d.col.InsertOne(ctx, &model.Message{
|
||
|
ID: xid.New().String(),
|
||
|
UserID: userID,
|
||
|
SessionID: sessionID,
|
||
|
Title: title,
|
||
|
Message: message,
|
||
|
Files: files,
|
||
|
CreatedAt: time.Now(),
|
||
|
}); err != nil {
|
||
|
d.logger.Emit(ErrorInsert{
|
||
|
Err: err,
|
||
|
UserID: userID,
|
||
|
SessionID: sessionID,
|
||
|
})
|
||
|
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
return nil
|
||
|
}
|