Initial commit

This commit is contained in:
2025-03-07 11:12:53 +07:00
commit 5a7e718666
22 changed files with 4527 additions and 0 deletions

View File

@@ -0,0 +1,53 @@
package database
import (
"context"
"fmt"
"log"
"os"
"time"
_ "github.com/joho/godotenv/autoload"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type Service interface {
Health() map[string]string
}
type service struct {
db *mongo.Client
}
var (
host = os.Getenv("BLUEPRINT_DB_HOST")
port = os.Getenv("BLUEPRINT_DB_PORT")
//database = os.Getenv("BLUEPRINT_DB_DATABASE")
)
func New() Service {
client, err := mongo.Connect(context.Background(), options.Client().ApplyURI(fmt.Sprintf("mongodb://%s:%s", host, port)))
if err != nil {
log.Fatal(err)
}
return &service{
db: client,
}
}
func (s *service) Health() map[string]string {
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
err := s.db.Ping(ctx, nil)
if err != nil {
log.Fatalf(fmt.Sprintf("db down: %v", err))
}
return map[string]string{
"message": "It's healthy",
}
}

View File

@@ -0,0 +1,61 @@
package database
import (
"context"
"log"
"testing"
"github.com/testcontainers/testcontainers-go/modules/mongodb"
)
func mustStartMongoContainer() (func(context.Context) error, error) {
dbContainer, err := mongodb.Run(context.Background(), "mongo:latest")
if err != nil {
return nil, err
}
dbHost, err := dbContainer.Host(context.Background())
if err != nil {
return dbContainer.Terminate, err
}
dbPort, err := dbContainer.MappedPort(context.Background(), "27017/tcp")
if err != nil {
return dbContainer.Terminate, err
}
host = dbHost
port = dbPort.Port()
return dbContainer.Terminate, err
}
func TestMain(m *testing.M) {
teardown, err := mustStartMongoContainer()
if err != nil {
log.Fatalf("could not start mongodb container: %v", err)
}
m.Run()
if teardown != nil && teardown(context.Background()) != nil {
log.Fatalf("could not teardown mongodb container: %v", err)
}
}
func TestNew(t *testing.T) {
srv := New()
if srv == nil {
t.Fatal("New() returned nil")
}
}
func TestHealth(t *testing.T) {
srv := New()
stats := srv.Health()
if stats["message"] != "It's healthy" {
t.Fatalf("expected message to be 'It's healthy', got %s", stats["message"])
}
}