Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0cd71c5506 | ||
|
|
3218c69f1e | ||
|
|
7f588cc80c | ||
|
|
a37f1627fc | ||
|
|
d191d6a9c1 | ||
|
|
2716bb50d3 | ||
|
|
880461dffb | ||
|
|
77c950d299 | ||
|
|
44e00684cc | ||
|
|
5f9bfa8fe2 | ||
|
|
0eba955ddf | ||
|
|
607059e7ce | ||
|
|
acf414c876 | ||
|
|
507eb9eb09 | ||
|
|
2045465111 | ||
|
|
d332cde84f | ||
|
|
96fc87ea5e | ||
|
|
3db003fc47
|
||
|
|
e3a23aae6d
|
||
|
|
cf518fdcfb
|
||
|
|
592c51c950
|
@@ -0,0 +1,9 @@
|
|||||||
|
vendor/
|
||||||
|
|
||||||
|
# Ignore git directory
|
||||||
|
.git/
|
||||||
|
|
||||||
|
.gitea/
|
||||||
|
|
||||||
|
# Ignore environment files (configure via docker-compose instead)
|
||||||
|
.env*
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
JWT_SECRET=NULqYIzgt28bTiyziCd7IOO7b6LnWDW!
|
||||||
|
DB_NAME=textsender_db
|
||||||
|
DB_USER=textsender
|
||||||
|
DB_PASSWORD=password
|
||||||
|
DB_HOST=main_db
|
||||||
|
DB_PORT=5432
|
||||||
|
DB_SSLMODE=disable
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
JWT_SECRET=NULqYIzgt28bTiyziCd7IOO7b6LnWDW!
|
||||||
DB_NAME=textsender_db
|
DB_NAME=textsender_db
|
||||||
DB_USER=textsender
|
DB_USER=textsender
|
||||||
DB_PASSWORD=password
|
DB_PASSWORD=password
|
||||||
|
|||||||
+105
-19
@@ -11,32 +11,118 @@ jobs:
|
|||||||
runs-on: ubuntu-24.04 # You can change this to macos-latest or windows-latest if needed
|
runs-on: ubuntu-24.04 # You can change this to macos-latest or windows-latest if needed
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v5
|
||||||
|
|
||||||
- name: Set up Go
|
- name: Set up Go
|
||||||
uses: actions/setup-go@v3
|
uses: actions/setup-go@v4
|
||||||
with:
|
with:
|
||||||
go-version: '1.24.5' # You can specify a specific version or 'stable'
|
go-version: '1.25.3' # You can specify a specific version or 'stable'
|
||||||
|
|
||||||
- name: Build
|
- name: Build
|
||||||
run: go build -v ./...
|
|
||||||
|
|
||||||
- name: Test
|
|
||||||
run: go test -v ./...
|
|
||||||
|
|
||||||
- name: Run gofmt (optional)
|
|
||||||
# Uncomment to check code formatting with gofmt
|
|
||||||
run: |
|
run: |
|
||||||
if [ -n "$(gofmt -l.)" ]; then
|
echo "Initializing config"
|
||||||
echo "Go code is not formatted. Please run 'gofmt -w.' to fix it."
|
mkdir -p ~/.ssh
|
||||||
exit 1
|
echo "${{ secrets.MYREPO_TOKEN }}" > ~/.ssh/textsender_models_deploy_key
|
||||||
fi
|
chmod 600 ~/.ssh/textsender_models_deploy_key
|
||||||
|
ssh-keyscan ${{ vars.MY_HOST }} >> ~/.ssh/known_hosts
|
||||||
|
|
||||||
- name: Run golint (optional)
|
eval $(ssh-agent -s)
|
||||||
# Uncomment to check code style with golint
|
ssh-add -v ~/.ssh/textsender_models_deploy_key
|
||||||
|
|
||||||
|
go env -w GOPRIVATE='${{ secrets.GIT_HOST_ROOT }}'
|
||||||
|
|
||||||
|
echo "Creating local .gitconfig"
|
||||||
|
touch ~/.gitconfig
|
||||||
|
cat > ~/.gitconfig << "EOF"
|
||||||
|
[url "ssh://git@${{ secrets.GIT_HOST_ROOT }}"]
|
||||||
|
insteadOf = https://${{ secrets.GIT_HOST_ROOT }}
|
||||||
|
EOF
|
||||||
|
|
||||||
|
echo "Building binary"
|
||||||
|
make build
|
||||||
|
|
||||||
|
echo "Binary built"
|
||||||
|
file textsender-api
|
||||||
|
|
||||||
|
test:
|
||||||
|
name: Test
|
||||||
|
runs-on: ubuntu-24.04
|
||||||
|
services:
|
||||||
|
postgres:
|
||||||
|
image: postgres:18.0
|
||||||
|
env:
|
||||||
|
POSTGRES_USER: ${{ secrets.DB_TEST_USER }}
|
||||||
|
POSTGRES_PASSWORD: ${{ secrets.DB_TEST_PASSWORD }}
|
||||||
|
POSTGRES_DB: ${{ secrets.DB_TEST_NAME }}
|
||||||
|
ports:
|
||||||
|
- 5432:5432
|
||||||
|
options: >-
|
||||||
|
--health-cmd pg_isready
|
||||||
|
--health-interval 10s
|
||||||
|
--health-timeout 5s
|
||||||
|
--health-retries 5
|
||||||
|
steps:
|
||||||
|
- name: Checkout code
|
||||||
|
uses: actions/checkout@v5
|
||||||
|
|
||||||
|
- name: Setup Go
|
||||||
|
uses: actions/setup-go@v4
|
||||||
|
with:
|
||||||
|
go-version: '1.25.3'
|
||||||
|
|
||||||
|
- name: Install PostgreSQL client
|
||||||
|
run: sudo apt update && sudo apt-get install -y postgresql-client
|
||||||
|
|
||||||
|
- name: Wait for PostgreSQL to be ready
|
||||||
run: |
|
run: |
|
||||||
if [ -n "$(golint./...)" ]; then
|
for i in {1..30}; do
|
||||||
echo "Go code has style issues. Please run 'golint./...' to see them."
|
if pg_isready -h postgres -p 5432; then
|
||||||
exit 1
|
echo "PostgreSQL is ready"
|
||||||
|
exit 0
|
||||||
fi
|
fi
|
||||||
|
echo "Waiting for PostgreSQL... Attempt $i"
|
||||||
|
sleep 2
|
||||||
|
done
|
||||||
|
echo "PostgreSQL did not start in time"
|
||||||
|
exit 1
|
||||||
|
|
||||||
|
- name: Run tests
|
||||||
|
env:
|
||||||
|
DB_NAME: ${{ secrets.DB_TEST_NAME }}
|
||||||
|
DB_USER: ${{ secrets.DB_TEST_USER }}
|
||||||
|
DB_PASSWORD: ${{ secrets.DB_TEST_PASSWORD }}
|
||||||
|
DB_HOST: postgres
|
||||||
|
DB_PORT: 5432
|
||||||
|
DB_SSLMODE: disable
|
||||||
|
SECRET_KEY: ${{ secrets.SECRET_KEY }}
|
||||||
|
run: |
|
||||||
|
echo "Parent directory"
|
||||||
|
echo `pwd`
|
||||||
|
|
||||||
|
echo "JWT_SECRET=$SECRET_KEY" >> .env
|
||||||
|
echo "DB_NAME=$DB_NAME" > .env
|
||||||
|
echo "DB_USER=$DB_USER" >> .env
|
||||||
|
echo "DB_PASSWORD=$DB_PASSWORD" >> .env
|
||||||
|
echo "DB_HOST=$DB_HOST" >> .env
|
||||||
|
echo "DB_PORT=$DB_PORT" >> .env
|
||||||
|
echo "DB_SSLMODE=$DB_SSLMODE" >> .env
|
||||||
|
|
||||||
|
echo "Initializing config"
|
||||||
|
mkdir -p ~/.ssh
|
||||||
|
echo "${{ secrets.MYREPO_TOKEN }}" > ~/.ssh/textsender_models_deploy_key
|
||||||
|
chmod 600 ~/.ssh/textsender_models_deploy_key
|
||||||
|
ssh-keyscan ${{ vars.MY_HOST }} >> ~/.ssh/known_hosts
|
||||||
|
|
||||||
|
eval $(ssh-agent -s)
|
||||||
|
ssh-add -v ~/.ssh/textsender_models_deploy_key
|
||||||
|
|
||||||
|
go env -w GOPRIVATE='${{ secrets.GIT_HOST_ROOT }}'
|
||||||
|
|
||||||
|
echo "Creating local .gitconfig"
|
||||||
|
touch ~/.gitconfig
|
||||||
|
cat > ~/.gitconfig << "EOF"
|
||||||
|
[url "ssh://git@${{ secrets.GIT_HOST_ROOT }}"]
|
||||||
|
insteadOf = https://${{ secrets.GIT_HOST_ROOT }}
|
||||||
|
EOF
|
||||||
|
|
||||||
|
go test -v ./...
|
||||||
|
|||||||
@@ -3,3 +3,4 @@
|
|||||||
|
|
||||||
.env
|
.env
|
||||||
.env.local
|
.env.local
|
||||||
|
.env.docker
|
||||||
|
|||||||
+52
@@ -0,0 +1,52 @@
|
|||||||
|
# Multi-stage Dockerfile for Go application
|
||||||
|
FROM golang:1.25.3 AS builder
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||||
|
ca-certificates \
|
||||||
|
openssh-client git
|
||||||
|
|
||||||
|
RUN mkdir -p -m 0700 ~/.ssh && \
|
||||||
|
ssh-keyscan git.kundeng.us >> ~/.ssh/known_hosts
|
||||||
|
|
||||||
|
# Configure Git to use SSH for GitHub
|
||||||
|
RUN git config --global url."ssh://git@git.kundeng.us".insteadOf "https://git.kundeng.us"
|
||||||
|
|
||||||
|
# Set up the Go environment for private modules
|
||||||
|
ENV GOPRIVATE=git.kundeng.us
|
||||||
|
|
||||||
|
|
||||||
|
# Copy go mod and sum files
|
||||||
|
COPY go.mod go.sum ./
|
||||||
|
|
||||||
|
RUN --mount=type=ssh mkdir src && \
|
||||||
|
go mod download
|
||||||
|
|
||||||
|
# Copy source code
|
||||||
|
COPY ./cmd ./cmd
|
||||||
|
COPY ./internal ./internal
|
||||||
|
COPY ./Makefile .
|
||||||
|
COPY ./.env .
|
||||||
|
COPY ./migrations ./migrations
|
||||||
|
|
||||||
|
# Build the application
|
||||||
|
RUN CGO_ENABLED=0 GOOS=linux make build
|
||||||
|
|
||||||
|
# Runtime stage
|
||||||
|
FROM alpine:latest AS production
|
||||||
|
|
||||||
|
RUN apk --no-cache add ca-certificates
|
||||||
|
|
||||||
|
WORKDIR /root/
|
||||||
|
|
||||||
|
# Copy the pre-built binary file from the previous stage
|
||||||
|
COPY --from=builder /app/textsender-api .
|
||||||
|
COPY --from=builder /app/.env ./
|
||||||
|
COPY --from=builder /app/migrations ./migrations
|
||||||
|
|
||||||
|
# Expose port
|
||||||
|
EXPOSE 8080
|
||||||
|
|
||||||
|
# Command to run the executable
|
||||||
|
CMD ["./textsender-api"]
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
VERSION ?= $(shell git describe --tags 2>/dev/null || echo "dev")
|
||||||
|
COMMIT ?= $(shell git rev-parse --short HEAD)
|
||||||
|
BUILD_TIME ?= $(shell date -u +%Y-%m-%dT%H:%M:%SZ)
|
||||||
|
GO_VERSION ?= $(shell go version | awk '{print $$3}')
|
||||||
|
|
||||||
|
.PHONY: build
|
||||||
|
build:
|
||||||
|
go build -ldflags="\
|
||||||
|
-X 'git.kundeng.us/phoenix/textsender-api/internal/version.Version=$(VERSION)' \
|
||||||
|
-X 'git.kundeng.us/phoenix/textsender-api/internal/version.BuildTime=$(BUILD_TIME)' \
|
||||||
|
-X 'git.kundeng.us/phoenix/textsender-api/internal/version.Commit=$(COMMIT)' \
|
||||||
|
-X 'git.kundeng.us/phoenix/textsender-api/internal/version.GoVersion=$(GO_VERSION)'" \
|
||||||
|
-o textsender-api cmd/api/main.go
|
||||||
|
|
||||||
|
.PHONY: install
|
||||||
|
install:
|
||||||
|
go install -ldflags="\
|
||||||
|
-X 'git.kundeng.us/phoenix/textsender-api/internal/version.Version=$(VERSION)' \
|
||||||
|
-X 'git.kundeng.us/phoenix/textsender-api/internal/version.BuildTime=$(BUILD_TIME)' \
|
||||||
|
-X 'git.kundeng.us/phoenix/textsender-api/internal/version.Commit=$(COMMIT)' \
|
||||||
|
-X 'git.kundeng.us/phoenix/textsender-api/internal/version.GoVersion=$(GO_VERSION)'"
|
||||||
@@ -4,6 +4,7 @@ A software system to process Text messaging queueing
|
|||||||
|
|
||||||
## Getting started
|
## Getting started
|
||||||
|
|
||||||
TODO
|
### Building
|
||||||
```BASH
|
```BASH
|
||||||
|
make build
|
||||||
```
|
```
|
||||||
|
|||||||
+117
-9
@@ -1,17 +1,125 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import "fmt"
|
import (
|
||||||
import "log"
|
"context"
|
||||||
import "net/http"
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"os/signal"
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
|
||||||
import "git.kundeng.us/phoenix/textsender-api/internal/config"
|
"github.com/go-chi/chi/v5"
|
||||||
import "git.kundeng.us/phoenix/textsender-api/internal/handler"
|
"github.com/go-chi/chi/v5/middleware"
|
||||||
|
|
||||||
|
"git.kundeng.us/phoenix/textsender-api/internal/config"
|
||||||
|
database "git.kundeng.us/phoenix/textsender-api/internal/db"
|
||||||
|
"git.kundeng.us/phoenix/textsender-api/internal/handler"
|
||||||
|
"git.kundeng.us/phoenix/textsender-api/internal/handler/endpoint"
|
||||||
|
mdlware "git.kundeng.us/phoenix/textsender-api/internal/middleware"
|
||||||
|
"git.kundeng.us/phoenix/textsender-api/internal/services"
|
||||||
|
"git.kundeng.us/phoenix/textsender-api/internal/store"
|
||||||
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
fmt.Println(config.APP_NAME)
|
cfg := config.Load()
|
||||||
|
if cfg == nil {
|
||||||
|
fmt.Println("Error initializing config")
|
||||||
|
os.Exit(-1)
|
||||||
|
} else if cfg.JWTSecret == "" {
|
||||||
|
fmt.Println("Error: JWTSecret not initialized")
|
||||||
|
os.Exit(-1)
|
||||||
|
}
|
||||||
|
|
||||||
http.HandleFunc(handler.MESSAGE_DRAFT_ENDPOINT, handler.DraftMessageHandler)
|
db, err := database.NewDatabase(cfg.GetDBConnString())
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Failed to connect to database: %v", err)
|
||||||
|
}
|
||||||
|
defer db.Close()
|
||||||
|
|
||||||
log.Println("Starting server", config.PORT)
|
ctx := context.Background()
|
||||||
log.Fatal(http.ListenAndServe(config.PortString(), nil))
|
|
||||||
|
if cfg.ResetDB {
|
||||||
|
log.Println("Resetting database")
|
||||||
|
if err := db.ResetDatabase(ctx); err != nil {
|
||||||
|
log.Fatalf("Failed to reset database: %v", err)
|
||||||
|
}
|
||||||
|
log.Println("Database reset completed. Exiting.")
|
||||||
|
return
|
||||||
|
} else {
|
||||||
|
if exists, err := database.TableExists(ctx, db.Pool, "contacts "); err == nil && !exists {
|
||||||
|
fmt.Println("Resetting database")
|
||||||
|
err = db.ResetDatabase(ctx)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Printf("Error:%v", err)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
fmt.Printf("Error:%v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
jwtService := services.NewJWTService(cfg.JWTSecret)
|
||||||
|
|
||||||
|
contactStore := store.NewContactStore(db.Pool)
|
||||||
|
messageStore := store.NewMessageStore(db.Pool)
|
||||||
|
schStore := store.NewScheduledMessageStore(db.Pool)
|
||||||
|
schMsgEventStore := store.NewScheduledMessageEventStore(db.Pool)
|
||||||
|
|
||||||
|
contactHandler := handler.NewContactHandler(contactStore)
|
||||||
|
messageHandler := handler.NewMessageHandler(messageStore)
|
||||||
|
scheduledMessageHandler := handler.NewScheduledMessageHandler(schStore)
|
||||||
|
scheduledMessageEventHandler := handler.NewScheduledMessageEventHandler(schMsgEventStore, schStore)
|
||||||
|
scheduledMessageStatusHandler := handler.NewScheduledMessageStatusHandler(schMsgEventStore, schStore)
|
||||||
|
|
||||||
|
router := chi.NewRouter()
|
||||||
|
|
||||||
|
router.Use(middleware.Logger)
|
||||||
|
router.Use(middleware.Recoverer)
|
||||||
|
router.Use(middleware.Timeout(60 * time.Second))
|
||||||
|
router.Use(mdlware.JSONContentType)
|
||||||
|
|
||||||
|
router.Handle(endpoint.ADD_CONTACT_ENDPOINT, mdlware.AuthMiddleware(jwtService)(http.HandlerFunc(contactHandler.AddContact)))
|
||||||
|
router.Handle(endpoint.GET_CONTACT, mdlware.AuthMiddleware(jwtService)(http.HandlerFunc(contactHandler.GetContact)))
|
||||||
|
router.Handle(endpoint.ADD_MESSAGE, mdlware.AuthMiddleware(jwtService)(http.HandlerFunc(messageHandler.AddMessage)))
|
||||||
|
router.Handle(endpoint.GET_MESSAGE, mdlware.AuthMiddleware(jwtService)(http.HandlerFunc(messageHandler.GetMessage)))
|
||||||
|
router.Handle(endpoint.ScheduleMessageEndpoint, mdlware.AuthMiddleware(jwtService)(http.HandlerFunc(scheduledMessageHandler.AddScheduledMessage)))
|
||||||
|
router.Handle(endpoint.AddEventToScheduledMessageEndpoint, mdlware.AuthMiddleware(jwtService)(http.HandlerFunc(scheduledMessageEventHandler.AddScheduledMessageEvent)))
|
||||||
|
router.Method("GET", endpoint.GetScheduledMessageEventEndpoint, mdlware.AuthMiddleware(jwtService)(http.HandlerFunc(scheduledMessageEventHandler.GetScheduledMessageEvent)))
|
||||||
|
router.Method("DELETE", endpoint.DeleteScheduledMessageEventEndpoint, mdlware.AuthMiddleware(jwtService)(http.HandlerFunc(scheduledMessageEventHandler.DeleteScheduledMessageEvent)))
|
||||||
|
router.Method("PATCH", endpoint.UpdateScheduledMessageStatusEndpoint, mdlware.AuthMiddleware(jwtService)(http.HandlerFunc(scheduledMessageStatusHandler.UpdateStatus)))
|
||||||
|
router.Method("GET", endpoint.GetScheduledMessageEndpoint, mdlware.AuthMiddleware(jwtService)(http.HandlerFunc(scheduledMessageHandler.GetScheduledMessage)))
|
||||||
|
router.Method("GET", endpoint.FetchNextScheduledMessageEndpoint, mdlware.AuthMiddleware(jwtService)(http.HandlerFunc(scheduledMessageHandler.FetchNextMessage)))
|
||||||
|
|
||||||
|
// Start server
|
||||||
|
server := &http.Server{
|
||||||
|
Addr: ":" + cfg.ServerPort,
|
||||||
|
Handler: router,
|
||||||
|
ReadTimeout: 15 * time.Second,
|
||||||
|
WriteTimeout: 15 * time.Second,
|
||||||
|
IdleTimeout: 60 * time.Second,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Graceful shutdown
|
||||||
|
go func() {
|
||||||
|
log.Printf("Server starting on port %s", cfg.ServerPort)
|
||||||
|
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||||
|
log.Fatalf("Server failed to start: %v", err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
// Wait for interrupt signal
|
||||||
|
quit := make(chan os.Signal, 1)
|
||||||
|
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
|
||||||
|
<-quit
|
||||||
|
log.Println("Shutting down server...")
|
||||||
|
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
if err := server.Shutdown(ctx); err != nil {
|
||||||
|
log.Fatalf("Server forced to shutdown: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Println("Server exited")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,116 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"path"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
"github.com/joho/godotenv"
|
||||||
|
|
||||||
|
"git.kundeng.us/phoenix/textsender-api/internal/config"
|
||||||
|
"git.kundeng.us/phoenix/textsender-api/internal/db"
|
||||||
|
"git.kundeng.us/phoenix/textsender-api/internal/handler"
|
||||||
|
"git.kundeng.us/phoenix/textsender-api/internal/handler/endpoint"
|
||||||
|
mdlware "git.kundeng.us/phoenix/textsender-api/internal/middleware"
|
||||||
|
"git.kundeng.us/phoenix/textsender-api/internal/services"
|
||||||
|
"git.kundeng.us/phoenix/textsender-api/internal/store"
|
||||||
|
)
|
||||||
|
|
||||||
|
var testRouter *chi.Mux
|
||||||
|
|
||||||
|
func TestMain(m *testing.M) {
|
||||||
|
cfg := load()
|
||||||
|
|
||||||
|
database, err := db.NewDatabase(cfg.GetDBConnString())
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err.Error())
|
||||||
|
panic("Failed to initialize database")
|
||||||
|
}
|
||||||
|
defer database.Close()
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
if cfg.ResetDB {
|
||||||
|
if err = database.ResetDatabase(ctx); err != nil {
|
||||||
|
fmt.Println(err.Error())
|
||||||
|
panic("Failed to initialize database")
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if exists, err := db.TableExists(ctx, database.Pool, "contacts "); err == nil && !exists {
|
||||||
|
fmt.Println("Resetting database")
|
||||||
|
err = database.ResetDatabase(ctx)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Printf("Error:%v", err)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
fmt.Printf("Error:%v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
jwtService := services.NewJWTService(cfg.JWTSecret)
|
||||||
|
|
||||||
|
contactStore := store.NewContactStore(database.Pool)
|
||||||
|
messageStore := store.NewMessageStore(db.Pool)
|
||||||
|
schStore := store.NewScheduledMessageStore(db.Pool)
|
||||||
|
schMsgEventStore := store.NewScheduledMessageEventStore(db.Pool)
|
||||||
|
|
||||||
|
contactHandler := handler.NewContactHandler(contactStore)
|
||||||
|
messageHandler := handler.NewMessageHandler(messageStore)
|
||||||
|
scheduledMessageHandler := handler.NewScheduledMessageHandler(schStore)
|
||||||
|
scheduledMessageEventHandler := handler.NewScheduledMessageEventHandler(schMsgEventStore, schStore)
|
||||||
|
scheduledMessageStatusHandler := handler.NewScheduledMessageStatusHandler(schMsgEventStore, schStore)
|
||||||
|
|
||||||
|
testRouter = chi.NewRouter()
|
||||||
|
testRouter.Handle(endpoint.ADD_CONTACT_ENDPOINT, mdlware.AuthMiddleware(jwtService)(http.HandlerFunc(contactHandler.AddContact)))
|
||||||
|
testRouter.Handle(endpoint.GET_CONTACT, mdlware.AuthMiddleware(jwtService)(http.HandlerFunc(contactHandler.GetContact)))
|
||||||
|
testRouter.Handle(endpoint.ADD_MESSAGE, mdlware.AuthMiddleware(jwtService)(http.HandlerFunc(messageHandler.AddMessage)))
|
||||||
|
testRouter.Handle(endpoint.GET_MESSAGE, mdlware.AuthMiddleware(jwtService)(http.HandlerFunc(messageHandler.GetMessage)))
|
||||||
|
testRouter.Handle(endpoint.ScheduleMessageEndpoint, mdlware.AuthMiddleware(jwtService)(http.HandlerFunc(scheduledMessageHandler.AddScheduledMessage)))
|
||||||
|
testRouter.Method("GET", endpoint.GetScheduledMessageEventEndpoint, mdlware.AuthMiddleware(jwtService)(http.HandlerFunc(scheduledMessageEventHandler.GetScheduledMessageEvent)))
|
||||||
|
testRouter.Method("DELETE", endpoint.DeleteScheduledMessageEventEndpoint, mdlware.AuthMiddleware(jwtService)(http.HandlerFunc(scheduledMessageEventHandler.DeleteScheduledMessageEvent)))
|
||||||
|
testRouter.Method("PATCH", endpoint.UpdateScheduledMessageStatusEndpoint, mdlware.AuthMiddleware(jwtService)(http.HandlerFunc(scheduledMessageStatusHandler.UpdateStatus)))
|
||||||
|
testRouter.Method("GET", endpoint.GetScheduledMessageEndpoint, mdlware.AuthMiddleware(jwtService)(http.HandlerFunc(scheduledMessageHandler.GetScheduledMessage)))
|
||||||
|
testRouter.Method("GET", endpoint.FetchNextScheduledMessageEndpoint, mdlware.AuthMiddleware(jwtService)(http.HandlerFunc(scheduledMessageHandler.FetchNextMessage)))
|
||||||
|
|
||||||
|
code := m.Run()
|
||||||
|
os.Exit(code)
|
||||||
|
}
|
||||||
|
|
||||||
|
func load() *config.Config {
|
||||||
|
resetDb := flag.Bool("reset-db", false, "Reset the database schema and exit")
|
||||||
|
port := flag.String("port", config.PORT, "Server port")
|
||||||
|
flag.Parse()
|
||||||
|
|
||||||
|
cwd, _ := os.Getwd()
|
||||||
|
envPath := path.Join(cwd, ".env")
|
||||||
|
|
||||||
|
err := godotenv.Load(envPath)
|
||||||
|
if err != nil {
|
||||||
|
envPath = path.Join(cwd, "../..", ".env")
|
||||||
|
if err := godotenv.Load(envPath); err != nil {
|
||||||
|
panic("Error loading .env file: " + err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
unpackedConnString := config.UnpackDBConnString()
|
||||||
|
dbConnString := unpackedConnString.Parse()
|
||||||
|
|
||||||
|
return &config.Config{
|
||||||
|
DBConnString: dbConnString,
|
||||||
|
ServerPort: *port,
|
||||||
|
ResetDB: *resetDb,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func resetTestDB(t *testing.T) {
|
||||||
|
t.Helper()
|
||||||
|
_, err := db.Pool.Exec(context.Background(), "DELETE FROM contacts")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Failed to reset test database: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
version: '3.8' # Use a recent version
|
||||||
|
|
||||||
|
services:
|
||||||
|
api:
|
||||||
|
build: # Tells docker-compose to build the Dockerfile in the current directory
|
||||||
|
context: .
|
||||||
|
ssh: ["default"] # Uses host's SSH agent
|
||||||
|
container_name: textsender # Optional: Give the container a specific name
|
||||||
|
ports:
|
||||||
|
# Map host port 8000 to container port 3000 (adjust as needed)
|
||||||
|
- "8080:8080"
|
||||||
|
env_file:
|
||||||
|
- .env
|
||||||
|
depends_on:
|
||||||
|
main_db:
|
||||||
|
condition: service_healthy # Wait for the DB to be healthy before starting the app
|
||||||
|
networks:
|
||||||
|
- textsender-network
|
||||||
|
restart: unless-stopped # Optional: Restart policy
|
||||||
|
|
||||||
|
auth_api:
|
||||||
|
build: # Tells docker-compose to build the Dockerfile in the current directory
|
||||||
|
context: ../textsender-auth
|
||||||
|
ssh: ["default"] # Uses host's SSH agent
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
container_name: textsender_auth # Optional: Give the container a specific name
|
||||||
|
ports:
|
||||||
|
# Map host port 8000 to container port 3000 (adjust as needed)
|
||||||
|
- "9080:9080"
|
||||||
|
env_file:
|
||||||
|
- ../textsender-auth/.env
|
||||||
|
depends_on:
|
||||||
|
auth_db:
|
||||||
|
condition: service_healthy # Wait for the DB to be healthy before starting the app
|
||||||
|
networks:
|
||||||
|
- textsender-network
|
||||||
|
restart: unless-stopped # Optional: Restart policy
|
||||||
|
|
||||||
|
# PostgreSQL Database Service
|
||||||
|
main_db:
|
||||||
|
image: postgres:18.0-alpine # Use an official Postgres image (Alpine variant is smaller)
|
||||||
|
container_name: textsender_db # Optional: Give the container a specific name
|
||||||
|
environment:
|
||||||
|
# These MUST match the user, password, and database name in the DATABASE_URL above
|
||||||
|
POSTGRES_USER: ${POSTGRES_AUTH_USER:-textsender}
|
||||||
|
POSTGRES_PASSWORD: ${POSTGRES_AUTH_PASSWORD:-password}
|
||||||
|
POSTGRES_DB: ${POSTGRES_AUTH_DB:-textsender_db}
|
||||||
|
volumes:
|
||||||
|
# Persist database data using a named volume
|
||||||
|
- postgres_data:/var/lib/postgresql/data
|
||||||
|
ports:
|
||||||
|
- "5432:5432"
|
||||||
|
healthcheck:
|
||||||
|
# Checks if Postgres is ready to accept connections
|
||||||
|
test: ["CMD-SHELL", "pg_isready -U $$POSTGRES_USER -d $$POSTGRES_DB"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 5
|
||||||
|
start_period: 10s
|
||||||
|
networks:
|
||||||
|
- textsender-network
|
||||||
|
restart: always # Optional: Restart policy
|
||||||
|
|
||||||
|
auth_db:
|
||||||
|
image: postgres:18.0-alpine # Use an official Postgres image (Alpine variant is smaller)
|
||||||
|
container_name: textsender_auth_db # Optional: Give the container a specific name
|
||||||
|
environment:
|
||||||
|
# These MUST match the user, password, and database name in the DATABASE_URL above
|
||||||
|
POSTGRES_USER: ${POSTGRES_AUTH_USER:-textsender_auth}
|
||||||
|
POSTGRES_PASSWORD: ${POSTGRES_AUTH_PASSWORD:-password}
|
||||||
|
POSTGRES_DB: ${POSTGRES_AUTH_DB:-textsender_auth_db}
|
||||||
|
volumes:
|
||||||
|
# Persist database data using a named volume
|
||||||
|
- postgres_data_auth:/var/lib/postgresql/data
|
||||||
|
ports:
|
||||||
|
- "5433:5432"
|
||||||
|
healthcheck:
|
||||||
|
# Checks if Postgres is ready to accept connections
|
||||||
|
test: ["CMD-SHELL", "pg_isready -U $$POSTGRES_USER -d $$POSTGRES_DB"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 5
|
||||||
|
start_period: 10s
|
||||||
|
networks:
|
||||||
|
- textsender-network
|
||||||
|
restart: always # Optional: Restart policy
|
||||||
|
|
||||||
|
# Define the named volume for data persistence
|
||||||
|
volumes:
|
||||||
|
postgres_data:
|
||||||
|
driver: local # Use the default local driver
|
||||||
|
postgres_data_auth:
|
||||||
|
driver: local # Use the default local driver
|
||||||
|
|
||||||
|
networks:
|
||||||
|
textsender-network:
|
||||||
|
driver: bridge
|
||||||
@@ -2,4 +2,27 @@ module git.kundeng.us/phoenix/textsender-api
|
|||||||
|
|
||||||
go 1.25.3
|
go 1.25.3
|
||||||
|
|
||||||
require github.com/google/uuid v1.6.0
|
require (
|
||||||
|
git.kundeng.us/phoenix/textsender-models v0.0.6-4-e124bcfda8-556
|
||||||
|
github.com/go-chi/chi/v5 v5.2.3
|
||||||
|
github.com/golang-jwt/jwt/v5 v5.3.0
|
||||||
|
github.com/google/uuid v1.6.0
|
||||||
|
github.com/gorilla/mux v1.8.1
|
||||||
|
github.com/jackc/pgx/v5 v5.7.6
|
||||||
|
github.com/joho/godotenv v1.5.1
|
||||||
|
github.com/stretchr/testify v1.11.1
|
||||||
|
)
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||||
|
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||||
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||||
|
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||||
|
github.com/kr/text v0.2.0 // indirect
|
||||||
|
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||||
|
github.com/rogpeppe/go-internal v1.14.1 // indirect
|
||||||
|
golang.org/x/crypto v0.42.0 // indirect
|
||||||
|
golang.org/x/sync v0.17.0 // indirect
|
||||||
|
golang.org/x/text v0.29.0 // indirect
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||||
|
)
|
||||||
|
|||||||
@@ -1,2 +1,49 @@
|
|||||||
|
git.kundeng.us/phoenix/textsender-models v0.0.6-4-e124bcfda8-556 h1:2shgOKmglCODswpCJeCuyPiUAph3wfc0Ep1z6b/ifis=
|
||||||
|
git.kundeng.us/phoenix/textsender-models v0.0.6-4-e124bcfda8-556/go.mod h1:lx5MCnOgGgsdpwzrfi9uph5xmkeb6H8AuexUNGss2no=
|
||||||
|
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||||
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/go-chi/chi/v5 v5.2.3 h1:WQIt9uxdsAbgIYgid+BpYc+liqQZGMHRaUwp0JUcvdE=
|
||||||
|
github.com/go-chi/chi/v5 v5.2.3/go.mod h1:L2yAIGWB3H+phAw1NxKwWM+7eUH/lU8pOMm5hHcoops=
|
||||||
|
github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo=
|
||||||
|
github.com/golang-jwt/jwt/v5 v5.3.0/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
||||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
|
github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
|
||||||
|
github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=
|
||||||
|
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||||
|
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||||
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||||
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||||
|
github.com/jackc/pgx/v5 v5.7.6 h1:rWQc5FwZSPX58r1OQmkuaNicxdmExaEz5A2DO2hUuTk=
|
||||||
|
github.com/jackc/pgx/v5 v5.7.6/go.mod h1:aruU7o91Tc2q2cFp5h4uP3f6ztExVpyVv88Xl/8Vl8M=
|
||||||
|
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||||
|
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||||
|
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
|
||||||
|
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
|
||||||
|
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
|
||||||
|
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
|
||||||
|
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||||
|
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
|
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
|
||||||
|
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
||||||
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
|
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||||
|
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
|
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||||
|
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||||
|
golang.org/x/crypto v0.42.0 h1:chiH31gIWm57EkTXpwnqf8qeuMUi0yekh6mT2AvFlqI=
|
||||||
|
golang.org/x/crypto v0.42.0/go.mod h1:4+rDnOTJhQCx2q7/j6rAN5XDw8kPjeaXEUR2eL94ix8=
|
||||||
|
golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug=
|
||||||
|
golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||||
|
golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk=
|
||||||
|
golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4=
|
||||||
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||||
|
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||||
|
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
|||||||
+119
-3
@@ -1,13 +1,129 @@
|
|||||||
package config
|
package config
|
||||||
|
|
||||||
import "fmt"
|
import (
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
const PORT = 8080
|
"github.com/joho/godotenv"
|
||||||
|
|
||||||
|
"git.kundeng.us/phoenix/textsender-api/internal/version"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Config struct {
|
||||||
|
DBConnString string
|
||||||
|
ServerPort string
|
||||||
|
ResetDB bool
|
||||||
|
JWTSecret string `env:"JWT_SECRET" required:"true"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ConnectionInfo struct {
|
||||||
|
Username string
|
||||||
|
Password string
|
||||||
|
Database string
|
||||||
|
Host string
|
||||||
|
Port int
|
||||||
|
SslMode string
|
||||||
|
}
|
||||||
|
|
||||||
|
const PORT = "8080"
|
||||||
const APP_NAME = "textsender-api"
|
const APP_NAME = "textsender-api"
|
||||||
|
|
||||||
func PortString() string {
|
func PortString() string {
|
||||||
portMessage := fmt.Sprintf(":%d", PORT)
|
portMessage := fmt.Sprintf(":%s", PORT)
|
||||||
|
|
||||||
return portMessage
|
return portMessage
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (ci ConnectionInfo) Parse() string {
|
||||||
|
return fmt.Sprintf("postgres://%s:%s@%s:%d/%s?sslmode=%s", ci.Username, ci.Password, ci.Host, ci.Port, ci.Database, ci.SslMode)
|
||||||
|
}
|
||||||
|
|
||||||
|
func PrintName() {
|
||||||
|
fmt.Println(APP_NAME)
|
||||||
|
fmt.Println(version.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
func Load() *Config {
|
||||||
|
versionFlag := flag.Bool("version", false, "Print version information")
|
||||||
|
resetDb := flag.Bool("reset-db", false, "Reset the database schema and exit")
|
||||||
|
port := flag.String("port", PORT, "Server port")
|
||||||
|
flag.Parse()
|
||||||
|
|
||||||
|
if *versionFlag {
|
||||||
|
fmt.Println(version.String())
|
||||||
|
os.Exit(-1)
|
||||||
|
}
|
||||||
|
|
||||||
|
err := godotenv.Load()
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal("Error loading .env file")
|
||||||
|
}
|
||||||
|
|
||||||
|
unpackedConnString := UnpackDBConnString()
|
||||||
|
dbConnString := unpackedConnString.Parse()
|
||||||
|
|
||||||
|
return &Config{
|
||||||
|
DBConnString: dbConnString,
|
||||||
|
ServerPort: *port,
|
||||||
|
ResetDB: *resetDb,
|
||||||
|
JWTSecret: os.Getenv("JWT_SECRET"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func UnpackDBConnString() (connInfo ConnectionInfo) {
|
||||||
|
username := os.Getenv("DB_USER")
|
||||||
|
password := os.Getenv("DB_PASSWORD")
|
||||||
|
host := os.Getenv("DB_HOST")
|
||||||
|
port := os.Getenv("DB_PORT")
|
||||||
|
database := os.Getenv("DB_NAME")
|
||||||
|
sslMode := os.Getenv("DB_SSLMODE")
|
||||||
|
|
||||||
|
if username != "" {
|
||||||
|
connInfo.Username = username
|
||||||
|
} else {
|
||||||
|
connInfo.Username = "user"
|
||||||
|
}
|
||||||
|
|
||||||
|
if password != "" {
|
||||||
|
connInfo.Password = password
|
||||||
|
} else {
|
||||||
|
connInfo.Password = "password"
|
||||||
|
}
|
||||||
|
|
||||||
|
if host != "" {
|
||||||
|
connInfo.Host = host
|
||||||
|
} else {
|
||||||
|
connInfo.Host = "localhost"
|
||||||
|
}
|
||||||
|
|
||||||
|
if port != "" {
|
||||||
|
num, err := strconv.Atoi(port)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
connInfo.Port = num
|
||||||
|
} else {
|
||||||
|
connInfo.Port = 5432
|
||||||
|
}
|
||||||
|
|
||||||
|
if database != "" {
|
||||||
|
connInfo.Database = database
|
||||||
|
} else {
|
||||||
|
connInfo.Database = "textsender_db"
|
||||||
|
}
|
||||||
|
|
||||||
|
if sslMode != "" {
|
||||||
|
connInfo.SslMode = sslMode
|
||||||
|
} else {
|
||||||
|
connInfo.SslMode = "disable"
|
||||||
|
}
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Config) GetDBConnString() string {
|
||||||
|
return c.DBConnString
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,136 @@
|
|||||||
|
// db/connection.go
|
||||||
|
package db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
"path"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
)
|
||||||
|
|
||||||
|
var Pool *pgxpool.Pool
|
||||||
|
|
||||||
|
type Database struct {
|
||||||
|
Pool *pgxpool.Pool
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewDatabase(connString string) (*Database, error) {
|
||||||
|
ctx := context.Background()
|
||||||
|
// Parse the connection string and create pool configuration
|
||||||
|
config, err := pgxpool.ParseConfig(connString)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("unable to parse DSN: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Configure connection pool settings
|
||||||
|
config.MaxConns = 25
|
||||||
|
config.MinConns = 5
|
||||||
|
config.MaxConnLifetime = time.Hour
|
||||||
|
config.MaxConnIdleTime = 30 * time.Minute
|
||||||
|
config.HealthCheckPeriod = time.Minute
|
||||||
|
|
||||||
|
// Configure connection timeouts
|
||||||
|
config.ConnConfig.ConnectTimeout = 10 * time.Second
|
||||||
|
config.ConnConfig.RuntimeParams["timezone"] = "UTC"
|
||||||
|
|
||||||
|
// Create the connection pool
|
||||||
|
pool, err := pgxpool.NewWithConfig(ctx, config)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("unable to create connection pool: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test the connection with a short timeout
|
||||||
|
if err := pool.Ping(ctx); err != nil {
|
||||||
|
pool.Close()
|
||||||
|
return nil, fmt.Errorf("unable to ping database: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Printf("Successfully connected to database")
|
||||||
|
return &Database{Pool: pool}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func TableExists(ctx context.Context, conn *pgxpool.Pool, tableName string) (bool, error) {
|
||||||
|
var exists bool
|
||||||
|
|
||||||
|
query := `
|
||||||
|
SELECT EXISTS (
|
||||||
|
SELECT FROM information_schema.tables
|
||||||
|
WHERE table_schema = 'public'
|
||||||
|
AND table_name = $1
|
||||||
|
);
|
||||||
|
`
|
||||||
|
|
||||||
|
err := conn.QueryRow(ctx, query, tableName).Scan(&exists)
|
||||||
|
if err != nil {
|
||||||
|
return false, fmt.Errorf("error checking if table exists: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return exists, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db *Database) Close() {
|
||||||
|
if db.Pool != nil {
|
||||||
|
db.Pool.Close()
|
||||||
|
log.Println("Database connection pool closed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// HealthCheck verifies the database connection is still alive
|
||||||
|
func (db *Database) HealthCheck(ctx context.Context) error {
|
||||||
|
return db.Pool.Ping(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetPoolStats returns connection pool statistics
|
||||||
|
func (db *Database) GetPoolStats() string {
|
||||||
|
stats := db.Pool.Stat()
|
||||||
|
return fmt.Sprintf("TotalConns: %d, IdleConns: %d, AcquiredConns: %d",
|
||||||
|
stats.TotalConns(), stats.IdleConns(), stats.AcquiredConns())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db *Database) ResetDatabase(ctx context.Context) error {
|
||||||
|
tx, err := db.Pool.Begin(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("Transaction unable to begin: %v", err)
|
||||||
|
}
|
||||||
|
defer tx.Rollback(ctx)
|
||||||
|
|
||||||
|
schemaContent, err := os.ReadFile("migrations/schema.sql")
|
||||||
|
if err != nil {
|
||||||
|
log.Println("Default migrations not found. Checking different directory")
|
||||||
|
cwd, _ := os.Getwd()
|
||||||
|
migrationsPath := path.Join(cwd, "../..", "migrations/schema.sql")
|
||||||
|
schemaContent, err = os.ReadFile(migrationsPath)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("error reading schema file: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, stmt := range strings.Split(string(schemaContent), ";") {
|
||||||
|
stmt = strings.TrimSpace(stmt)
|
||||||
|
if stmt == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if strings.HasPrefix(stmt, "--") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err := tx.Exec(ctx, stmt)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("error executing SQL statement: %v\nStatement: %s", err, stmt)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := tx.Commit(ctx); err != nil {
|
||||||
|
return fmt.Errorf("unable to commit transaction: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Println("Database schema applied successfully")
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
+101
-29
@@ -5,26 +5,35 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"git.kundeng.us/phoenix/textsender-api/internal/store"
|
||||||
|
"git.kundeng.us/phoenix/textsender-models/pkg/contact"
|
||||||
)
|
)
|
||||||
|
|
||||||
type RequestAddContact struct {
|
type RequestAddContact struct {
|
||||||
PhoneNumber string `json:"phone_number"`
|
PhoneNumber string `json:"phone_number"`
|
||||||
UserId uuid.UUID`json:"user_id"`
|
UserId uuid.UUID `json:"user_id"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type LoginResponse struct {
|
type AddContactResponse struct {
|
||||||
Message string `json:"message"`
|
Message string `json:"message"`
|
||||||
Data []model.Data`json:"data"`
|
Data []contact.Contact `json:"data"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type GetContactResponse struct {
|
||||||
|
Message string `json:"message"`
|
||||||
|
Data []contact.Contact `json:"data"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type ContactHandler struct {
|
type ContactHandler struct {
|
||||||
|
ContactStore store.ContactStore
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewContactHandler(store model.Store) *ContactHandler {
|
func NewContactHandler(str store.ContactStore) *ContactHandler {
|
||||||
return &ContactHandler{Store: store}
|
return &ContactHandler{ContactStore: str}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *ContactHandler) AddContact(w http.ResponseWriter, r *http.Request) {
|
func (c *ContactHandler) AddContact(w http.ResponseWriter, r *http.Request) {
|
||||||
if r.Method != http.MethodPost {
|
if r.Method != http.MethodPost {
|
||||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||||
return
|
return
|
||||||
@@ -36,47 +45,110 @@ func (l *ContactHandler) AddContact(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
defer r.Body.Close()
|
defer r.Body.Close()
|
||||||
|
|
||||||
|
newContact := contact.Contact{PhoneNumber: req.PhoneNumber, UserId: req.UserId}
|
||||||
|
|
||||||
var statusCode int
|
var statusCode int
|
||||||
/*
|
var resp AddContactResponse
|
||||||
var resp LoginResponse
|
|
||||||
|
|
||||||
ctx := r.Context()
|
ctx := r.Context()
|
||||||
|
|
||||||
if exists, err := l.UserStore.UserExists(ctx, req.Username); err != nil {
|
if exists, err := c.ContactStore.ContactExists(ctx, newContact.PhoneNumber, newContact.UserId); err != nil {
|
||||||
fmt.Printf("Error: %v", err)
|
fmt.Printf("Error: %v", err)
|
||||||
statusCode = http.StatusInternalServerError
|
statusCode = http.StatusInternalServerError
|
||||||
resp.Message = err.Error()
|
resp.Message = err.Error()
|
||||||
} else {
|
} else {
|
||||||
if !exists {
|
if exists {
|
||||||
statusCode = http.StatusBadRequest
|
statusCode = http.StatusBadRequest
|
||||||
resp.Message = "Failure in user check"
|
resp.Message = "Cannot create contact"
|
||||||
} else {
|
} else {
|
||||||
if user, err := l.UserStore.GetUserByUsername(ctx, req.Username); err != nil {
|
if err := c.ContactStore.CreateContact(ctx, &newContact); err != nil {
|
||||||
|
fmt.Printf("Error: %v", err)
|
||||||
statusCode = http.StatusInternalServerError
|
statusCode = http.StatusInternalServerError
|
||||||
resp.Message = err.Error()
|
resp.Message = err.Error()
|
||||||
} else {
|
} else {
|
||||||
hashing := utility.HashMash{Password: req.Password}
|
statusCode = http.StatusCreated
|
||||||
if hashing.CheckPasswordHash(req.Password, user.Password) {
|
resp.Message = "Contact created"
|
||||||
var tokGen utility.TokenGenerator
|
resp.Data = append(resp.Data, newContact)
|
||||||
secretKey := config.GetSecretKey()
|
|
||||||
tokGen.SetSecretKey(secretKey)
|
|
||||||
if token, err := tokGen.GenerateToken(*user); err != nil {
|
|
||||||
fmt.Println(err.Error())
|
|
||||||
statusCode = http.StatusInternalServerError
|
|
||||||
resp.Message = "Error generating token"
|
|
||||||
} else {
|
|
||||||
statusCode = http.StatusOK
|
|
||||||
resp.Data = append(resp.Data, *token)
|
|
||||||
resp.Message = "Successful"
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
RespondWithJSON(w, statusCode, &resp)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *ContactHandler) GetContact(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Method != http.MethodGet {
|
||||||
|
fmt.Println("Method:", r.Method)
|
||||||
|
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var id, userId uuid.UUID
|
||||||
|
queryParams := r.URL.Query()
|
||||||
|
|
||||||
|
// Check if parameter exists
|
||||||
|
if _, exists := queryParams["id"]; !exists {
|
||||||
|
if _, exists := queryParams["user_id"]; !exists {
|
||||||
|
fmt.Fprintf(w, "Name parameter not provided")
|
||||||
|
http.Error(w, "Query params", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
} else {
|
||||||
|
var err error
|
||||||
|
userId, err = uuid.Parse(queryParams.Get("user_id"))
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(w, "Name parameter exists: %s", userId)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
var err error
|
||||||
|
idTmp := queryParams.Get("id")
|
||||||
|
id, err = uuid.Parse(idTmp)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println("Error:", err)
|
||||||
|
http.Error(w, "Error parsing Id", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var statusCode int
|
||||||
|
var resp GetContactResponse
|
||||||
|
|
||||||
|
ctx := r.Context()
|
||||||
|
|
||||||
|
if id != uuid.Nil {
|
||||||
|
fmt.Println("Checking with Id")
|
||||||
|
if con, err := c.ContactStore.GetContactByID(ctx, id); err == nil {
|
||||||
|
statusCode = http.StatusOK
|
||||||
|
resp.Message = "Successful"
|
||||||
|
resp.Data = append(resp.Data, *con)
|
||||||
|
} else {
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = err.Error()
|
||||||
|
}
|
||||||
|
} else if userId != uuid.Nil {
|
||||||
|
fmt.Println("Checking with User Id")
|
||||||
|
if contacts, err := c.ContactStore.GetAllContacts(ctx); err == nil {
|
||||||
|
for _, con := range contacts {
|
||||||
|
if con.UserId == userId {
|
||||||
|
resp.Data = append(resp.Data, *con)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(resp.Data) > 0 {
|
||||||
|
statusCode = http.StatusOK
|
||||||
|
resp.Message = "Successful"
|
||||||
} else {
|
} else {
|
||||||
statusCode = http.StatusNotFound
|
statusCode = http.StatusNotFound
|
||||||
resp.Message = "User not found"
|
resp.Message = "Contact not found"
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = err.Error()
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
statusCode = http.StatusBadRequest
|
||||||
|
resp.Message = "Invalid query parameter"
|
||||||
}
|
}
|
||||||
}
|
|
||||||
*/
|
|
||||||
|
|
||||||
RespondWithJson(w, statusCode, &resp)
|
RespondWithJSON(w, statusCode, &resp)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,85 @@
|
|||||||
|
package handler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.kundeng.us/phoenix/textsender-models/pkg/contact"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
|
||||||
|
"git.kundeng.us/phoenix/textsender-api/internal/db"
|
||||||
|
"git.kundeng.us/phoenix/textsender-api/internal/handler/endpoint"
|
||||||
|
"git.kundeng.us/phoenix/textsender-api/internal/store/mock"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Request struct {
|
||||||
|
PhoneNumber string
|
||||||
|
UserId uuid.UUID
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCreateContactWithMock(t *testing.T) {
|
||||||
|
mockstore := mock.NewMockContactStore()
|
||||||
|
handler := NewContactHandler(mockstore)
|
||||||
|
|
||||||
|
testUserId := uuid.New()
|
||||||
|
testBody := Request{PhoneNumber: "+12335403383", UserId: testUserId}
|
||||||
|
jsonValue, _ := json.Marshal(testBody)
|
||||||
|
|
||||||
|
req, _ := http.NewRequest("POST", endpoint.ADD_CONTACT_ENDPOINT, strings.NewReader(string(jsonValue)))
|
||||||
|
rr := httptest.NewRecorder()
|
||||||
|
|
||||||
|
handler.AddContact(rr, req)
|
||||||
|
|
||||||
|
assert.Equal(t, http.StatusCreated, rr.Code)
|
||||||
|
|
||||||
|
var response AddContactResponse
|
||||||
|
err := json.Unmarshal(rr.Body.Bytes(), &response)
|
||||||
|
assert.NoError(t, err, "Error Creating contact %v", err)
|
||||||
|
|
||||||
|
assert.NotEmpty(t, response.Data, "No Contact created")
|
||||||
|
|
||||||
|
assert.NotNil(t, response.Data[0].Id, "Id should not be nil")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGetContactWithMock(t *testing.T) {
|
||||||
|
mockstore := mock.NewMockContactStore()
|
||||||
|
testUserId := uuid.New()
|
||||||
|
|
||||||
|
testCon := contact.Contact{PhoneNumber: "+12335403383", UserId: testUserId}
|
||||||
|
ctx := t.Context()
|
||||||
|
if err := mockstore.CreateContact(ctx, &testCon); err != nil {
|
||||||
|
assert.NoError(t, err, "Error creating contact")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
url := fmt.Sprintf("%s?user_id=%s", endpoint.GET_CONTACT, testCon.UserId)
|
||||||
|
req, _ := http.NewRequest("GET", url, nil)
|
||||||
|
rr := httptest.NewRecorder()
|
||||||
|
|
||||||
|
contactHandler := NewContactHandler(mockstore)
|
||||||
|
contactHandler.GetContact(rr, req)
|
||||||
|
|
||||||
|
assert.Equal(t, http.StatusOK, rr.Code)
|
||||||
|
|
||||||
|
var response GetContactResponse
|
||||||
|
err := json.Unmarshal(rr.Body.Bytes(), &response)
|
||||||
|
assert.NoError(t, err, "Error getting contact %v", err)
|
||||||
|
|
||||||
|
assert.NotEmpty(t, response.Data, "No Contact retrieved")
|
||||||
|
|
||||||
|
assert.NotNil(t, response.Data[0].Id, "Id should not be nil")
|
||||||
|
}
|
||||||
|
|
||||||
|
func resetTestDB(t *testing.T) {
|
||||||
|
t.Helper()
|
||||||
|
_, err := db.Pool.Exec(context.Background(), "DELETE FROM contacts")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Failed to reset test database: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
package endpoint
|
||||||
|
|
||||||
|
const MESSAGE_DRAFT_ENDPOINT = "/api/v1/message/draft"
|
||||||
|
const ADD_MESSAGE = "/api/v1/message/new"
|
||||||
|
const GET_MESSAGE = "/api/v1/message"
|
||||||
|
const GET_CONTACT = "/api/v1/contact"
|
||||||
|
const ADD_CONTACT_ENDPOINT = "/api/v1/contact/new"
|
||||||
|
const ScheduleMessageEndpoint = "/api/v1/schedule/message"
|
||||||
|
const GetScheduledMessageEndpoint = "/api/v1/schedule/message"
|
||||||
|
const AddEventToScheduledMessageEndpoint = "/api/v1/schedule/message/event"
|
||||||
|
const GetScheduledMessageEventEndpoint = "/api/v1/schedule/message/event"
|
||||||
|
const DeleteScheduledMessageEventEndpoint = "/api/v1/schedule/message/event/{id}"
|
||||||
|
const UpdateScheduledMessageStatusEndpoint = "/api/v1/schedule/message/status/update"
|
||||||
|
const FetchNextScheduledMessageEndpoint = "/api/v1/schedule/message/fetch"
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
package handler
|
|
||||||
|
|
||||||
const MESSAGE_DRAFT_ENDPOINT = "/api/v1/message/draft"
|
|
||||||
const ADD_CONTACT_ENDPOINT = "/api/v1/contact";
|
|
||||||
@@ -1,9 +1,11 @@
|
|||||||
package handler
|
package handler
|
||||||
|
|
||||||
import "encoding/json"
|
import (
|
||||||
import "log"
|
"encoding/json"
|
||||||
import "net/http"
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
func ExtractFromRequest(r *http.Request, reqItem interface{}) error {
|
func ExtractFromRequest(r *http.Request, reqItem interface{}) error {
|
||||||
err := json.NewDecoder(r.Body).Decode(&reqItem)
|
err := json.NewDecoder(r.Body).Decode(&reqItem)
|
||||||
@@ -14,7 +16,6 @@ func ExtractFromRequest(r *http.Request, reqItem interface{}) error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// Helper function to send JSON responses
|
// Helper function to send JSON responses
|
||||||
func RespondWithJSON(w http.ResponseWriter, statusCode int, data interface{}) {
|
func RespondWithJSON(w http.ResponseWriter, statusCode int, data interface{}) {
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
@@ -23,3 +24,18 @@ func RespondWithJSON(w http.ResponseWriter, statusCode int, data interface{}) {
|
|||||||
log.Printf("Error encoding JSON: %v", err)
|
log.Printf("Error encoding JSON: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Gets the query parameter from the URL
|
||||||
|
func ParseQueryParams(r *http.Request, query string) (*string, error) {
|
||||||
|
queryParams := r.URL.Query()
|
||||||
|
if _, exists := queryParams[query]; exists {
|
||||||
|
value := queryParams.Get(query)
|
||||||
|
if len(value) == 0 {
|
||||||
|
return nil, fmt.Errorf("Value of query parameter is empty")
|
||||||
|
} else {
|
||||||
|
return &value, nil
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return nil, fmt.Errorf("Could not find query %s", query)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,141 @@
|
|||||||
|
package handler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"git.kundeng.us/phoenix/textsender-api/internal/store"
|
||||||
|
"git.kundeng.us/phoenix/textsender-models/pkg/message"
|
||||||
|
)
|
||||||
|
|
||||||
|
type RequestAddMessage struct {
|
||||||
|
Content string `json:"content"`
|
||||||
|
UserId uuid.UUID `json:"user_id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type AddMessageResponse struct {
|
||||||
|
Message string `json:"message"`
|
||||||
|
Data []message.Message `json:"data"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type GetMessageResponse struct {
|
||||||
|
Message string `json:"message"`
|
||||||
|
Data []message.Message `json:"data"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type MessageHandler struct {
|
||||||
|
MessageStore store.MessageStore
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewMessageHandler(str store.MessageStore) *MessageHandler {
|
||||||
|
return &MessageHandler{MessageStore: str}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MessageHandler) AddMessage(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Method != http.MethodPost {
|
||||||
|
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var req RequestAddMessage
|
||||||
|
if err := ExtractFromRequest(r, &req); err != nil {
|
||||||
|
http.Error(w, "Invalid JSON: "+err.Error(), http.StatusBadRequest)
|
||||||
|
}
|
||||||
|
defer r.Body.Close()
|
||||||
|
|
||||||
|
var statusCode int
|
||||||
|
var resp AddMessageResponse
|
||||||
|
newMessage := message.Message{Content: req.Content, UserId: req.UserId}
|
||||||
|
|
||||||
|
ctx := r.Context()
|
||||||
|
|
||||||
|
if err := m.MessageStore.CreateMessage(ctx, &newMessage); err != nil {
|
||||||
|
fmt.Println("Error:", err)
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = err.Error()
|
||||||
|
} else {
|
||||||
|
statusCode = http.StatusCreated
|
||||||
|
resp.Message = "Message created"
|
||||||
|
resp.Data = append(resp.Data, newMessage)
|
||||||
|
}
|
||||||
|
|
||||||
|
RespondWithJSON(w, statusCode, &resp)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *MessageHandler) GetMessage(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Method != http.MethodGet {
|
||||||
|
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var id, userId uuid.UUID
|
||||||
|
queryParams := r.URL.Query()
|
||||||
|
|
||||||
|
// Check if parameter exists
|
||||||
|
if _, exists := queryParams["id"]; !exists {
|
||||||
|
if _, exists := queryParams["user_id"]; !exists {
|
||||||
|
fmt.Fprintf(w, "Name parameter not provided")
|
||||||
|
http.Error(w, "Query params", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
} else {
|
||||||
|
var err error
|
||||||
|
userId, err = uuid.Parse(queryParams.Get("user_id"))
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(w, "Name parameter exists: %s", userId)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
var err error
|
||||||
|
idTmp := queryParams.Get("id")
|
||||||
|
id, err = uuid.Parse(idTmp)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println("Error:", err)
|
||||||
|
http.Error(w, "Error parsing Id", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var statusCode int
|
||||||
|
var resp GetMessageResponse
|
||||||
|
|
||||||
|
ctx := r.Context()
|
||||||
|
|
||||||
|
if id != uuid.Nil {
|
||||||
|
fmt.Println("Checking with Id")
|
||||||
|
if con, err := c.MessageStore.GetMessageByID(ctx, id); err == nil {
|
||||||
|
statusCode = http.StatusOK
|
||||||
|
resp.Message = "Successful"
|
||||||
|
resp.Data = append(resp.Data, *con)
|
||||||
|
} else {
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = err.Error()
|
||||||
|
}
|
||||||
|
} else if userId != uuid.Nil {
|
||||||
|
fmt.Println("Checking with User Id")
|
||||||
|
if contacts, err := c.MessageStore.GetAllMessages(ctx); err == nil {
|
||||||
|
for _, con := range contacts {
|
||||||
|
if con.UserId == userId {
|
||||||
|
resp.Data = append(resp.Data, *con)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(resp.Data) > 0 {
|
||||||
|
statusCode = http.StatusOK
|
||||||
|
resp.Message = "Successful"
|
||||||
|
} else {
|
||||||
|
statusCode = http.StatusNotFound
|
||||||
|
resp.Message = "Contact not found"
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = err.Error()
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
statusCode = http.StatusBadRequest
|
||||||
|
resp.Message = "Invalid query parameter"
|
||||||
|
}
|
||||||
|
|
||||||
|
RespondWithJSON(w, statusCode, &resp)
|
||||||
|
}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
package handler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.kundeng.us/phoenix/textsender-models/pkg/message"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
|
||||||
|
"git.kundeng.us/phoenix/textsender-api/internal/handler/endpoint"
|
||||||
|
"git.kundeng.us/phoenix/textsender-api/internal/store/mock"
|
||||||
|
)
|
||||||
|
|
||||||
|
type CreateMessageRequest struct {
|
||||||
|
Content string `json:"content"`
|
||||||
|
UserId uuid.UUID `json:"user_id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCreateMessageWithMock(t *testing.T) {
|
||||||
|
mockStore := mock.NewMockMessageStore()
|
||||||
|
handler := NewMessageHandler(mockStore)
|
||||||
|
|
||||||
|
testUserId := uuid.New()
|
||||||
|
testBody := CreateMessageRequest{Content: "Who could tell?", UserId: testUserId}
|
||||||
|
jsonValue, _ := json.Marshal(testBody)
|
||||||
|
|
||||||
|
req, _ := http.NewRequest("POST", endpoint.ADD_MESSAGE, strings.NewReader(string(jsonValue)))
|
||||||
|
rr := httptest.NewRecorder()
|
||||||
|
|
||||||
|
handler.AddMessage(rr, req)
|
||||||
|
|
||||||
|
assert.Equal(t, http.StatusCreated, rr.Code)
|
||||||
|
|
||||||
|
var response AddMessageResponse
|
||||||
|
err := json.Unmarshal(rr.Body.Bytes(), &response)
|
||||||
|
assert.NoError(t, err, "Error Creating message %v", err)
|
||||||
|
|
||||||
|
assert.NotEmpty(t, response.Data, "No Message created")
|
||||||
|
|
||||||
|
assert.NotNil(t, response.Data[0].Id, "Id should not be nil")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGetMessageWithMock(t *testing.T) {
|
||||||
|
mockstore := mock.NewMockMessageStore()
|
||||||
|
testUserId := uuid.New()
|
||||||
|
|
||||||
|
testCon := message.Message{Content: "Who is the one that benefits?", UserId: testUserId}
|
||||||
|
ctx := t.Context()
|
||||||
|
if err := mockstore.CreateMessage(ctx, &testCon); err != nil {
|
||||||
|
assert.NoError(t, err, "Error creating message")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
url := fmt.Sprintf("%s?user_id=%s", endpoint.GET_MESSAGE, testCon.UserId)
|
||||||
|
req, _ := http.NewRequest("GET", url, nil)
|
||||||
|
rr := httptest.NewRecorder()
|
||||||
|
|
||||||
|
messageHandler := NewMessageHandler(mockstore)
|
||||||
|
messageHandler.GetMessage(rr, req)
|
||||||
|
|
||||||
|
assert.Equal(t, http.StatusOK, rr.Code)
|
||||||
|
|
||||||
|
var response GetMessageResponse
|
||||||
|
err := json.Unmarshal(rr.Body.Bytes(), &response)
|
||||||
|
assert.NoError(t, err, "Error getting message %v", err)
|
||||||
|
|
||||||
|
assert.NotEmpty(t, response.Data, "No Message retrieved")
|
||||||
|
|
||||||
|
assert.NotNil(t, response.Data[0].Id, "Id should not be nil")
|
||||||
|
}
|
||||||
@@ -0,0 +1,154 @@
|
|||||||
|
package handler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"git.kundeng.us/phoenix/textsender-api/internal/store"
|
||||||
|
"git.kundeng.us/phoenix/textsender-models/pkg/message/scheduling"
|
||||||
|
)
|
||||||
|
|
||||||
|
type RequestScheduledMessageStatus struct {
|
||||||
|
ScheduledMessageId uuid.UUID `json:"scheduled_message_id"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ScheduledMessageChange struct {
|
||||||
|
OldStatus string `json:"old_status"`
|
||||||
|
ScheduledMessage scheduling.ScheduledMessage `json:"scheduled_message"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ScheduledMessageStatusResponse struct {
|
||||||
|
Message string `json:"message"`
|
||||||
|
Data []ScheduledMessageChange `json:"data"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ScheduledMessageStatusHandler struct {
|
||||||
|
ScheduledMessageEventStore store.ScheduledMessageEventStore
|
||||||
|
ScheduledMessageStore store.ScheduledMessageStore
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewScheduledMessageStatusHandler(str store.ScheduledMessageEventStore, schStore store.ScheduledMessageStore) *ScheduledMessageStatusHandler {
|
||||||
|
return &ScheduledMessageStatusHandler{ScheduledMessageEventStore: str, ScheduledMessageStore: schStore}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ScheduledMessageStatusHandler) UpdateStatus(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Method != http.MethodPatch {
|
||||||
|
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var req RequestScheduledMessageStatus
|
||||||
|
if err := ExtractFromRequest(r, &req); err != nil {
|
||||||
|
http.Error(w, "Invalid JSON: "+err.Error(), http.StatusBadRequest)
|
||||||
|
}
|
||||||
|
defer r.Body.Close()
|
||||||
|
|
||||||
|
var statusCode int
|
||||||
|
var resp ScheduledMessageStatusResponse
|
||||||
|
|
||||||
|
if req.ScheduledMessageId == uuid.Nil {
|
||||||
|
statusCode = http.StatusBadRequest
|
||||||
|
resp.Message = "Scheduled messaged Id is nil"
|
||||||
|
} else if len(req.Status) == 0 {
|
||||||
|
statusCode = http.StatusBadRequest
|
||||||
|
resp.Message = "No status provided"
|
||||||
|
} else {
|
||||||
|
ctx := r.Context()
|
||||||
|
|
||||||
|
if schMsg, err := s.ScheduledMessageStore.Get(ctx, req.ScheduledMessageId); err != nil {
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = err.Error()
|
||||||
|
} else {
|
||||||
|
if schMsg.Status == scheduling.Done {
|
||||||
|
statusCode = http.StatusNotFound
|
||||||
|
resp.Message = "Scheduled message has already completed"
|
||||||
|
} else {
|
||||||
|
switch req.Status {
|
||||||
|
case scheduling.Pending:
|
||||||
|
{
|
||||||
|
if schMsg.Status == scheduling.Processing {
|
||||||
|
statusCode = http.StatusBadRequest
|
||||||
|
resp.Message = "Message is currently processing"
|
||||||
|
} else {
|
||||||
|
if returnedStatus, err := s.ScheduledMessageStore.UpdateStatus(ctx, schMsg.Id, req.Status); err != nil {
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = err.Error()
|
||||||
|
} else {
|
||||||
|
chg := initScheduledMessageChange(schMsg, schMsg.Status, *returnedStatus)
|
||||||
|
statusCode = http.StatusOK
|
||||||
|
resp.Message = "Successful"
|
||||||
|
resp.Data = append(resp.Data, chg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case scheduling.Ready:
|
||||||
|
{
|
||||||
|
if events, err := s.ScheduledMessageEventStore.GetWithScheduleMessageId(ctx, schMsg.Id); err != nil {
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = err.Error()
|
||||||
|
} else {
|
||||||
|
oldStatus := schMsg.Status
|
||||||
|
if schMsg.Status != scheduling.Processing && schMsg.Status != scheduling.Ready {
|
||||||
|
// Update status
|
||||||
|
if len(events) > 0 {
|
||||||
|
if returnedStatus, err := s.ScheduledMessageStore.UpdateStatus(ctx, schMsg.Id, req.Status); err != nil {
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = err.Error()
|
||||||
|
} else {
|
||||||
|
chg := initScheduledMessageChange(schMsg, oldStatus, *returnedStatus)
|
||||||
|
statusCode = http.StatusOK
|
||||||
|
resp.Message = "Successful"
|
||||||
|
resp.Data = append(resp.Data, chg)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = "Not enough scheduled message events"
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if schMsg.Status == scheduling.Processing {
|
||||||
|
statusCode = http.StatusBadRequest
|
||||||
|
resp.Message = "Scheduled messages are processing"
|
||||||
|
} else {
|
||||||
|
statusCode = http.StatusNotModified
|
||||||
|
resp.Message = "Status is already set"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case scheduling.Processing, scheduling.Done:
|
||||||
|
{
|
||||||
|
if events, err := s.ScheduledMessageEventStore.GetWithScheduleMessageId(ctx, schMsg.Id); err != nil {
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = err.Error()
|
||||||
|
} else {
|
||||||
|
if len(events) > 0 {
|
||||||
|
if returnedStatus, err := s.ScheduledMessageStore.UpdateStatus(ctx, schMsg.Id, req.Status); err != nil {
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = err.Error()
|
||||||
|
} else {
|
||||||
|
chg := initScheduledMessageChange(schMsg, schMsg.Status, *returnedStatus)
|
||||||
|
statusCode = http.StatusOK
|
||||||
|
resp.Message = "Successful"
|
||||||
|
resp.Data = append(resp.Data, chg)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = "Not enough scheduled message events"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
RespondWithJSON(w, statusCode, &resp)
|
||||||
|
}
|
||||||
|
|
||||||
|
func initScheduledMessageChange(schMsg *scheduling.ScheduledMessage, oldStatus, newStatus string) ScheduledMessageChange {
|
||||||
|
schMsg.Status = newStatus
|
||||||
|
return ScheduledMessageChange{OldStatus: oldStatus, ScheduledMessage: *schMsg}
|
||||||
|
}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
package handler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.kundeng.us/phoenix/textsender-models/pkg/message/scheduling"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
|
||||||
|
"git.kundeng.us/phoenix/textsender-api/internal/handler/endpoint"
|
||||||
|
"git.kundeng.us/phoenix/textsender-api/internal/store/mock"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestUpdateScheduledMessageStatusWithMock(t *testing.T) {
|
||||||
|
now := time.Now()
|
||||||
|
|
||||||
|
schMsgEventStore := mock.NewMockScheduledMessageEventStore()
|
||||||
|
contactStore := mock.NewMockContactStore()
|
||||||
|
messageStore := mock.NewMockMessageStore()
|
||||||
|
schMsgStore := mock.NewMockScheduledMessageStore()
|
||||||
|
|
||||||
|
recipientId := uuid.New()
|
||||||
|
messageId := uuid.New()
|
||||||
|
scheduledMessageId := uuid.New()
|
||||||
|
testUserId := uuid.New()
|
||||||
|
|
||||||
|
con := testContact(recipientId, testUserId)
|
||||||
|
msg := testMessage(messageId, testUserId)
|
||||||
|
schMsg := testScheduledMessage(scheduledMessageId, testUserId, now)
|
||||||
|
event := testScheduledMessageEvent(msg.Id, con.Id, schMsg.Id)
|
||||||
|
|
||||||
|
ctx := t.Context()
|
||||||
|
|
||||||
|
if err := contactStore.CreateContact(ctx, &con); err != nil {
|
||||||
|
assert.NoError(t, err, "Error creating contact: %v", err)
|
||||||
|
} else if err = messageStore.CreateMessage(ctx, &msg); err != nil {
|
||||||
|
assert.NoError(t, err, "Error creating message: %v", err)
|
||||||
|
} else if err = schMsgStore.CreateScheduledMessage(ctx, &schMsg); err != nil {
|
||||||
|
assert.NoError(t, err, "Error creating scheduled message: %v", err)
|
||||||
|
} else if err = schMsgEventStore.CreateScheduledMessageEvent(ctx, &event); err != nil {
|
||||||
|
assert.NoError(t, err, "Error creating scheduled message event: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
testReq := RequestScheduledMessageStatus{}
|
||||||
|
testReq.Status = scheduling.Ready
|
||||||
|
testReq.ScheduledMessageId = schMsg.Id
|
||||||
|
jsonValue, _ := json.Marshal(testReq)
|
||||||
|
jsonBody := strings.NewReader(string(jsonValue))
|
||||||
|
|
||||||
|
req, _ := http.NewRequest("PATCH", endpoint.UpdateScheduledMessageStatusEndpoint, jsonBody)
|
||||||
|
rr := httptest.NewRecorder()
|
||||||
|
|
||||||
|
handler := NewScheduledMessageStatusHandler(schMsgEventStore, schMsgStore)
|
||||||
|
handler.UpdateStatus(rr, req)
|
||||||
|
|
||||||
|
assert.Equal(t, http.StatusOK, rr.Code)
|
||||||
|
|
||||||
|
var response ScheduledMessageStatusResponse
|
||||||
|
err := json.Unmarshal(rr.Body.Bytes(), &response)
|
||||||
|
assert.NoError(t, err, "Error creating event %v", err)
|
||||||
|
|
||||||
|
assert.NotEmpty(t, response.Data, "Data should not be empty")
|
||||||
|
|
||||||
|
changes := response.Data[0]
|
||||||
|
assert.NotEqual(t, changes.OldStatus, changes.ScheduledMessage.Status, "The status should not match")
|
||||||
|
assert.Equal(t, scheduling.Pending, changes.OldStatus, "The Old status does not match Old %s New %s", changes.OldStatus, scheduling.Pending)
|
||||||
|
assert.Equal(t, scheduling.Ready, changes.ScheduledMessage.Status, "Status has not been updated")
|
||||||
|
}
|
||||||
@@ -0,0 +1,205 @@
|
|||||||
|
package handler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"git.kundeng.us/phoenix/textsender-api/internal/store"
|
||||||
|
"git.kundeng.us/phoenix/textsender-models/pkg/message/scheduling"
|
||||||
|
)
|
||||||
|
|
||||||
|
type RequestAddScheduledMessage struct {
|
||||||
|
Scheduled time.Time `json:"scheduled"`
|
||||||
|
Created time.Time `json:"created"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
UserId uuid.UUID `json:"user_id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type AddScheduledMessageResponse struct {
|
||||||
|
Message string `json:"message"`
|
||||||
|
Data []scheduling.ScheduledMessage `json:"data"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type GetScheduledMessageResponse struct {
|
||||||
|
Message string `json:"message"`
|
||||||
|
Data []scheduling.ScheduledMessage `json:"data"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type FetchNextMessageResponse struct {
|
||||||
|
Message string `json:"message"`
|
||||||
|
Data []scheduling.ScheduledMessage `json:"data"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ScheduledMessageHandler struct {
|
||||||
|
ScheduledMessageStore store.ScheduledMessageStore
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewScheduledMessageHandler(str store.ScheduledMessageStore) *ScheduledMessageHandler {
|
||||||
|
return &ScheduledMessageHandler{ScheduledMessageStore: str}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ScheduledMessageHandler) AddScheduledMessage(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Method != http.MethodPost {
|
||||||
|
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var req RequestAddScheduledMessage
|
||||||
|
if err := ExtractFromRequest(r, &req); err != nil {
|
||||||
|
http.Error(w, "Invalid JSON: "+err.Error(), http.StatusBadRequest)
|
||||||
|
}
|
||||||
|
defer r.Body.Close()
|
||||||
|
|
||||||
|
scheduledMessage := scheduling.ScheduledMessage{Scheduled: req.Scheduled, Status: req.Status, UserId: req.UserId}
|
||||||
|
|
||||||
|
var statusCode int
|
||||||
|
var resp AddScheduledMessageResponse
|
||||||
|
|
||||||
|
if scheduledMessage.UserId == uuid.Nil {
|
||||||
|
statusCode = http.StatusBadRequest
|
||||||
|
resp.Message = "No UserId"
|
||||||
|
} else {
|
||||||
|
ctx := r.Context()
|
||||||
|
|
||||||
|
if validStatus, err := IsStatusValid(&scheduledMessage); err == nil {
|
||||||
|
if validStatus {
|
||||||
|
if valid, err := isScheduledTimeValid(&scheduledMessage); err == nil && valid {
|
||||||
|
if err = s.ScheduledMessageStore.CreateScheduledMessage(ctx, &scheduledMessage); err == nil {
|
||||||
|
statusCode = http.StatusCreated
|
||||||
|
resp.Data = append(resp.Data, scheduledMessage)
|
||||||
|
resp.Message = "Successful"
|
||||||
|
} else {
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = err.Error()
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
statusCode = http.StatusBadRequest
|
||||||
|
resp.Message = "Invalid scheduled time"
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
statusCode = http.StatusBadRequest
|
||||||
|
resp.Message = "Invalid status"
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = err.Error()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
RespondWithJSON(w, statusCode, &resp)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ScheduledMessageHandler) GetScheduledMessage(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var id, userId uuid.UUID
|
||||||
|
|
||||||
|
if idParam, err := ParseQueryParams(r, "id"); err == nil {
|
||||||
|
var err error
|
||||||
|
id, err = uuid.Parse(*idParam)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Error parsing Id", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if userIdParam, err := ParseQueryParams(r, "user_id"); err == nil {
|
||||||
|
userId, err = uuid.Parse(*userIdParam)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Error parsing Id", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var resp GetScheduledMessageResponse
|
||||||
|
var statusCode int
|
||||||
|
ctx := r.Context()
|
||||||
|
|
||||||
|
if userId == uuid.Nil && id == uuid.Nil {
|
||||||
|
http.Error(w, "Invalid query parameters", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
} else if userId != uuid.Nil && id != uuid.Nil {
|
||||||
|
if schMsgs, err := s.ScheduledMessageStore.GetWithUserId(ctx, userId); err != nil {
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = err.Error()
|
||||||
|
} else {
|
||||||
|
for _, schMsg := range schMsgs {
|
||||||
|
if schMsg.Id == id {
|
||||||
|
resp.Data = append(resp.Data, *schMsg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
statusCode = http.StatusOK
|
||||||
|
resp.Message = "Successful"
|
||||||
|
}
|
||||||
|
} else if id != uuid.Nil {
|
||||||
|
if schMsg, err := s.ScheduledMessageStore.Get(ctx, id); err != nil {
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = err.Error()
|
||||||
|
} else {
|
||||||
|
statusCode = http.StatusOK
|
||||||
|
resp.Message = "Successful"
|
||||||
|
resp.Data = append(resp.Data, *schMsg)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if schMsgs, err := s.ScheduledMessageStore.GetWithUserId(ctx, userId); err != nil {
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = err.Error()
|
||||||
|
} else {
|
||||||
|
statusCode = http.StatusOK
|
||||||
|
resp.Message = "Successful"
|
||||||
|
for _, schMsg := range schMsgs {
|
||||||
|
resp.Data = append(resp.Data, *schMsg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
RespondWithJSON(w, statusCode, &resp)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ScheduledMessageHandler) FetchNextMessage(w http.ResponseWriter, r *http.Request) {
|
||||||
|
ctx := r.Context()
|
||||||
|
var resp FetchNextMessageResponse
|
||||||
|
var statusCode int
|
||||||
|
|
||||||
|
if schMsg, err := s.ScheduledMessageStore.FetchNextScheduledMessage(ctx); err != nil {
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = err.Error()
|
||||||
|
} else {
|
||||||
|
if schMsg != nil {
|
||||||
|
statusCode = http.StatusOK
|
||||||
|
resp.Message = "Successful"
|
||||||
|
resp.Data = append(resp.Data, *schMsg)
|
||||||
|
} else {
|
||||||
|
statusCode = http.StatusNotFound
|
||||||
|
resp.Message = "No item"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
RespondWithJSON(w, statusCode, &resp)
|
||||||
|
}
|
||||||
|
|
||||||
|
func isScheduledTimeValid(schMsg *scheduling.ScheduledMessage) (bool, error) {
|
||||||
|
now := time.Now()
|
||||||
|
timeCutOff := now.Add(-5 * time.Minute)
|
||||||
|
futureCutOff := now.Add((24 * 7) * time.Hour)
|
||||||
|
|
||||||
|
if schMsg.Scheduled.After(timeCutOff) {
|
||||||
|
if schMsg.Scheduled.Before(futureCutOff) {
|
||||||
|
return true, nil
|
||||||
|
} else {
|
||||||
|
return false, fmt.Errorf("Scheduled Time is too far in the future")
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func IsStatusValid(schMsg *scheduling.ScheduledMessage) (bool, error) {
|
||||||
|
schMsg.Status = strings.ToUpper(schMsg.Status)
|
||||||
|
if schMsg.Status == scheduling.Pending {
|
||||||
|
return true, nil
|
||||||
|
} else {
|
||||||
|
return false, fmt.Errorf("Status is not valid for creating scheduled message %s", schMsg.Status)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,208 @@
|
|||||||
|
package handler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"git.kundeng.us/phoenix/textsender-api/internal/store"
|
||||||
|
"git.kundeng.us/phoenix/textsender-models/pkg/message/scheduling"
|
||||||
|
)
|
||||||
|
|
||||||
|
type RequestAddScheduledMessageEvent struct {
|
||||||
|
RecipientId uuid.UUID `json:"recipient_id"`
|
||||||
|
MessageId uuid.UUID `json:"message_id"`
|
||||||
|
ScheduledMessageId uuid.UUID `json:"scheduled_message_id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type AddScheduledMessageEventResponse struct {
|
||||||
|
Message string `json:"message"`
|
||||||
|
Data []scheduling.ScheduledMessageEvent `json:"data"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type GetScheduledMessageEventResponse struct {
|
||||||
|
Message string `json:"message"`
|
||||||
|
Data []scheduling.ScheduledMessageEvent `json:"data"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type DeleteScheduledMessageEventResponse struct {
|
||||||
|
Message string `json:"message"`
|
||||||
|
Data []scheduling.ScheduledMessageEvent `json:"data"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ScheduledMessageEventHandler struct {
|
||||||
|
ScheduledMessageEventStore store.ScheduledMessageEventStore
|
||||||
|
ScheduledMessageStore store.ScheduledMessageStore
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewScheduledMessageEventHandler(str store.ScheduledMessageEventStore, schStore store.ScheduledMessageStore) *ScheduledMessageEventHandler {
|
||||||
|
return &ScheduledMessageEventHandler{ScheduledMessageEventStore: str, ScheduledMessageStore: schStore}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ScheduledMessageEventHandler) AddScheduledMessageEvent(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Method != http.MethodPost {
|
||||||
|
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var req RequestAddScheduledMessageEvent
|
||||||
|
if err := ExtractFromRequest(r, &req); err != nil {
|
||||||
|
http.Error(w, "Invalid JSON: "+err.Error(), http.StatusBadRequest)
|
||||||
|
}
|
||||||
|
defer r.Body.Close()
|
||||||
|
|
||||||
|
event := scheduling.ScheduledMessageEvent{RecipientId: req.RecipientId, MessageId: req.MessageId, ScheduledMessageId: req.ScheduledMessageId}
|
||||||
|
|
||||||
|
var statusCode int
|
||||||
|
var resp AddScheduledMessageEventResponse
|
||||||
|
|
||||||
|
if event.RecipientId == uuid.Nil {
|
||||||
|
statusCode = http.StatusBadRequest
|
||||||
|
resp.Message = "Recipient Id is nil"
|
||||||
|
} else if event.MessageId == uuid.Nil {
|
||||||
|
statusCode = http.StatusBadRequest
|
||||||
|
resp.Message = "Message Id is nil"
|
||||||
|
} else if event.ScheduledMessageId == uuid.Nil {
|
||||||
|
statusCode = http.StatusBadRequest
|
||||||
|
resp.Message = "Scheduled Message Id is nil"
|
||||||
|
} else {
|
||||||
|
ctx := r.Context()
|
||||||
|
|
||||||
|
if schMsg, err := s.ScheduledMessageStore.Get(ctx, event.ScheduledMessageId); err != nil {
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = err.Error()
|
||||||
|
} else {
|
||||||
|
if schMsg.Status == scheduling.Pending {
|
||||||
|
if exists, err := s.ScheduledMessageEventStore.Exists(ctx, &event); err == nil {
|
||||||
|
if exists {
|
||||||
|
statusCode = http.StatusBadRequest
|
||||||
|
resp.Message = "Event already present"
|
||||||
|
} else {
|
||||||
|
if err = s.ScheduledMessageEventStore.CreateScheduledMessageEvent(ctx, &event); err == nil {
|
||||||
|
statusCode = http.StatusCreated
|
||||||
|
resp.Message = "Successful"
|
||||||
|
resp.Data = append(resp.Data, event)
|
||||||
|
} else {
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = err.Error()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = err.Error()
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
statusCode = http.StatusBadRequest
|
||||||
|
resp.Message = "Scheduled message cannot be modified due to the status"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
RespondWithJSON(w, statusCode, &resp)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ScheduledMessageEventHandler) GetScheduledMessageEvent(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Method != http.MethodGet {
|
||||||
|
http.Error(w, "Metnot allowed", http.StatusMethodNotAllowed)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var id, scheduledMessageId uuid.UUID
|
||||||
|
if idParam, err := ParseQueryParams(r, "id"); err == nil {
|
||||||
|
id, err = uuid.Parse(*idParam)
|
||||||
|
}
|
||||||
|
if scheduledMessageIdParam, err := ParseQueryParams(r, "scheduled_message_id"); err == nil {
|
||||||
|
scheduledMessageId, err = uuid.Parse(*scheduledMessageIdParam)
|
||||||
|
}
|
||||||
|
|
||||||
|
var statusCode int
|
||||||
|
var resp GetScheduledMessageEventResponse
|
||||||
|
ctx := r.Context()
|
||||||
|
|
||||||
|
if id == uuid.Nil && scheduledMessageId == uuid.Nil {
|
||||||
|
statusCode = http.StatusBadRequest
|
||||||
|
resp.Message = "Query parameters missing"
|
||||||
|
} else if id != uuid.Nil {
|
||||||
|
if event, err := s.ScheduledMessageEventStore.Get(ctx, id); err != nil {
|
||||||
|
resp.Message = err.Error()
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
} else {
|
||||||
|
if event != nil {
|
||||||
|
resp.Message = "Successful"
|
||||||
|
statusCode = http.StatusOK
|
||||||
|
resp.Data = append(resp.Data, *event)
|
||||||
|
} else {
|
||||||
|
statusCode = http.StatusNotFound
|
||||||
|
resp.Message = "Scheduled message event not found"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if events, err := s.ScheduledMessageEventStore.GetWithScheduleMessageId(ctx, scheduledMessageId); err != nil {
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
resp.Message = err.Error()
|
||||||
|
} else {
|
||||||
|
statusCode = http.StatusOK
|
||||||
|
resp.Message = "Successful"
|
||||||
|
for _, event := range events {
|
||||||
|
resp.Data = append(resp.Data, *event)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
RespondWithJSON(w, statusCode, &resp)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ScheduledMessageEventHandler) DeleteScheduledMessageEvent(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Method != http.MethodDelete {
|
||||||
|
http.Error(w, "Metnot allowed", http.StatusMethodNotAllowed)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
id := chi.URLParam(r, "id")
|
||||||
|
if len(id) == 0 {
|
||||||
|
pathParts := strings.Split(r.URL.Path, "/")
|
||||||
|
if len(pathParts) < 7 {
|
||||||
|
http.Error(w, "Id not provided", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
} else {
|
||||||
|
id = pathParts[6]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var resp DeleteScheduledMessageEventResponse
|
||||||
|
var statusCode int
|
||||||
|
|
||||||
|
if parsedId, err := uuid.Parse(id); err != nil {
|
||||||
|
resp.Message = err.Error()
|
||||||
|
statusCode = http.StatusBadRequest
|
||||||
|
} else {
|
||||||
|
ctx := r.Context()
|
||||||
|
if event, err := s.ScheduledMessageEventStore.Get(ctx, parsedId); err != nil {
|
||||||
|
resp.Message = err.Error()
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
} else {
|
||||||
|
if schMsg, err := s.ScheduledMessageStore.Get(ctx, event.ScheduledMessageId); err != nil {
|
||||||
|
resp.Message = err.Error()
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
} else {
|
||||||
|
if schMsg.Status == scheduling.Pending {
|
||||||
|
if err = s.ScheduledMessageEventStore.Delete(ctx, event.Id); err != nil {
|
||||||
|
resp.Message = err.Error()
|
||||||
|
statusCode = http.StatusInternalServerError
|
||||||
|
} else {
|
||||||
|
resp.Message = "Successful"
|
||||||
|
resp.Data = append(resp.Data, *event)
|
||||||
|
statusCode = http.StatusOK
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
statusCode = http.StatusBadRequest
|
||||||
|
resp.Message = "Invalid status"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
RespondWithJSON(w, statusCode, &resp)
|
||||||
|
}
|
||||||
@@ -0,0 +1,206 @@
|
|||||||
|
package handler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.kundeng.us/phoenix/textsender-models/pkg/contact"
|
||||||
|
"git.kundeng.us/phoenix/textsender-models/pkg/message"
|
||||||
|
"git.kundeng.us/phoenix/textsender-models/pkg/message/scheduling"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
|
||||||
|
"git.kundeng.us/phoenix/textsender-api/internal/handler/endpoint"
|
||||||
|
"git.kundeng.us/phoenix/textsender-api/internal/store/mock"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
recipientId = uuid.New()
|
||||||
|
messageId = uuid.New()
|
||||||
|
scheduledMessageId = uuid.New()
|
||||||
|
testUserId = uuid.New()
|
||||||
|
)
|
||||||
|
|
||||||
|
type CreateScheduledMessageEventRequest struct {
|
||||||
|
RecipientId uuid.UUID `json:"recipient_id"`
|
||||||
|
MessageId uuid.UUID `json:"message_id"`
|
||||||
|
ScheduledMessageId uuid.UUID `json:"scheduled_message_id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCreateScheduledMessageEventWithMock(t *testing.T) {
|
||||||
|
now := time.Now()
|
||||||
|
|
||||||
|
mockStore := mock.NewMockScheduledMessageEventStore()
|
||||||
|
contactStore := mock.NewMockContactStore()
|
||||||
|
messageStore := mock.NewMockMessageStore()
|
||||||
|
schMsgStore := mock.NewMockScheduledMessageStore()
|
||||||
|
|
||||||
|
handler := NewScheduledMessageEventHandler(mockStore, schMsgStore)
|
||||||
|
|
||||||
|
recipientId := uuid.New()
|
||||||
|
messageId := uuid.New()
|
||||||
|
scheduledMessageId := uuid.New()
|
||||||
|
testUserId := uuid.New()
|
||||||
|
|
||||||
|
con := testContact(recipientId, testUserId)
|
||||||
|
msg := testMessage(messageId, testUserId)
|
||||||
|
schMsg := testScheduledMessage(scheduledMessageId, testUserId, now)
|
||||||
|
|
||||||
|
ctx := t.Context()
|
||||||
|
|
||||||
|
if err := contactStore.CreateContact(ctx, &con); err != nil {
|
||||||
|
assert.NoError(t, err, "Error creating contact: %v", err)
|
||||||
|
} else if err = messageStore.CreateMessage(ctx, &msg); err != nil {
|
||||||
|
assert.NoError(t, err, "Error creating message: %v", err)
|
||||||
|
} else if err = schMsgStore.CreateScheduledMessage(ctx, &schMsg); err != nil {
|
||||||
|
assert.NoError(t, err, "Error creating scheduled message: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
testReq := CreateScheduledMessageEventRequest{RecipientId: recipientId, MessageId: messageId, ScheduledMessageId: scheduledMessageId}
|
||||||
|
jsonValue, _ := json.Marshal(testReq)
|
||||||
|
|
||||||
|
req, _ := http.NewRequest("POST", endpoint.AddEventToScheduledMessageEndpoint, strings.NewReader(string(jsonValue)))
|
||||||
|
rr := httptest.NewRecorder()
|
||||||
|
|
||||||
|
handler.AddScheduledMessageEvent(rr, req)
|
||||||
|
|
||||||
|
assert.Equal(t, http.StatusCreated, rr.Code)
|
||||||
|
|
||||||
|
var response AddScheduledMessageEventResponse
|
||||||
|
err := json.Unmarshal(rr.Body.Bytes(), &response)
|
||||||
|
assert.NoError(t, err, "Error creating event %v", err)
|
||||||
|
|
||||||
|
assert.NotEmpty(t, response.Data, "No event created")
|
||||||
|
|
||||||
|
var event scheduling.ScheduledMessageEvent
|
||||||
|
event = response.Data[0]
|
||||||
|
|
||||||
|
assert.NotEmpty(t, event.Created, "Created date should not be empty")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGetScheduledMessageEventWithMock(t *testing.T) {
|
||||||
|
now := time.Now()
|
||||||
|
|
||||||
|
contactStore := mock.NewMockContactStore()
|
||||||
|
messageStore := mock.NewMockMessageStore()
|
||||||
|
schMsgStore := mock.NewMockScheduledMessageStore()
|
||||||
|
schMsgEventStore := mock.NewMockScheduledMessageEventStore()
|
||||||
|
handler := NewScheduledMessageEventHandler(schMsgEventStore, schMsgStore)
|
||||||
|
|
||||||
|
recipientId := uuid.New()
|
||||||
|
messageId := uuid.New()
|
||||||
|
scheduledMessageId := uuid.New()
|
||||||
|
testUserId := uuid.New()
|
||||||
|
|
||||||
|
con := testContact(recipientId, testUserId)
|
||||||
|
msg := testMessage(messageId, testUserId)
|
||||||
|
schMsg := testScheduledMessage(scheduledMessageId, testUserId, now)
|
||||||
|
event := testScheduledMessageEvent(msg.Id, con.Id, schMsg.Id)
|
||||||
|
|
||||||
|
ctx := t.Context()
|
||||||
|
|
||||||
|
if err := contactStore.CreateContact(ctx, &con); err != nil {
|
||||||
|
assert.NoError(t, err, "Error creating contact: %v", err)
|
||||||
|
} else if err = messageStore.CreateMessage(ctx, &msg); err != nil {
|
||||||
|
assert.NoError(t, err, "Error creating message: %v", err)
|
||||||
|
} else if err = schMsgStore.CreateScheduledMessage(ctx, &schMsg); err != nil {
|
||||||
|
assert.NoError(t, err, "Error creating scheduled message: %v", err)
|
||||||
|
} else if err = schMsgEventStore.CreateScheduledMessageEvent(ctx, &event); err != nil {
|
||||||
|
assert.NoError(t, err, "Error creating scheduled message event: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
url := fmt.Sprintf("%s?id=%s", endpoint.GetScheduledMessageEventEndpoint, event.Id.String())
|
||||||
|
req, _ := http.NewRequest("GET", url, nil)
|
||||||
|
rr := httptest.NewRecorder()
|
||||||
|
|
||||||
|
handler.GetScheduledMessageEvent(rr, req)
|
||||||
|
|
||||||
|
assert.Equal(t, http.StatusOK, rr.Code)
|
||||||
|
|
||||||
|
var response GetScheduledMessageEventResponse
|
||||||
|
err := json.Unmarshal(rr.Body.Bytes(), &response)
|
||||||
|
assert.NoError(t, err, "Error creating event %v", err)
|
||||||
|
|
||||||
|
assert.NotEmpty(t, response.Data, "No event created")
|
||||||
|
|
||||||
|
msgEvent := response.Data[0]
|
||||||
|
|
||||||
|
assert.NotEmpty(t, msgEvent.Created, "Created date should not be empty")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeleteScheduledMessageEventWithMock(t *testing.T) {
|
||||||
|
now := time.Now()
|
||||||
|
contactStore := mock.NewMockContactStore()
|
||||||
|
messageStore := mock.NewMockMessageStore()
|
||||||
|
schMsgStore := mock.NewMockScheduledMessageStore()
|
||||||
|
schMsgEventStore := mock.NewMockScheduledMessageEventStore()
|
||||||
|
handler := NewScheduledMessageEventHandler(schMsgEventStore, schMsgStore)
|
||||||
|
|
||||||
|
con := testContact(recipientId, testUserId)
|
||||||
|
msg := testMessage(messageId, testUserId)
|
||||||
|
schMsg := testScheduledMessage(scheduledMessageId, testUserId, now)
|
||||||
|
event := testScheduledMessageEvent(msg.Id, con.Id, schMsg.Id)
|
||||||
|
|
||||||
|
ctx := t.Context()
|
||||||
|
|
||||||
|
if err := contactStore.CreateContact(ctx, &con); err != nil {
|
||||||
|
assert.NoError(t, err, "Error creating contact: %v", err)
|
||||||
|
} else if err = messageStore.CreateMessage(ctx, &msg); err != nil {
|
||||||
|
assert.NoError(t, err, "Error creating message: %v", err)
|
||||||
|
} else if err = schMsgStore.CreateScheduledMessage(ctx, &schMsg); err != nil {
|
||||||
|
assert.NoError(t, err, "Error creating scheduled message: %v", err)
|
||||||
|
} else if err = schMsgEventStore.CreateScheduledMessageEvent(ctx, &event); err != nil {
|
||||||
|
assert.NoError(t, err, "Error creating scheduled message event: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
endpointValue := strings.Replace(endpoint.DeleteScheduledMessageEventEndpoint, "{id}", event.Id.String(), 1)
|
||||||
|
req, _ := http.NewRequest("DELETE", endpointValue, nil)
|
||||||
|
rr := httptest.NewRecorder()
|
||||||
|
|
||||||
|
handler.DeleteScheduledMessageEvent(rr, req)
|
||||||
|
|
||||||
|
assert.Equal(t, http.StatusOK, rr.Code)
|
||||||
|
|
||||||
|
var response DeleteScheduledMessageEventResponse
|
||||||
|
err := json.Unmarshal(rr.Body.Bytes(), &response)
|
||||||
|
assert.NoError(t, err, "Error creating event %v", err)
|
||||||
|
|
||||||
|
assert.NotEmpty(t, response.Data, "No event created")
|
||||||
|
|
||||||
|
msgEvent := response.Data[0]
|
||||||
|
|
||||||
|
assert.NotEmpty(t, msgEvent.Created, "Created date should not be empty")
|
||||||
|
}
|
||||||
|
|
||||||
|
func testContact(id uuid.UUID, userId uuid.UUID) contact.Contact {
|
||||||
|
if id == uuid.Nil {
|
||||||
|
return contact.Contact{Id: uuid.New(), PhoneNumber: "+10123456789", UserId: userId}
|
||||||
|
} else {
|
||||||
|
return contact.Contact{Id: id, PhoneNumber: "+10123456789", UserId: userId}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func testMessage(id uuid.UUID, userId uuid.UUID) message.Message {
|
||||||
|
if id == uuid.Nil {
|
||||||
|
return message.Message{Id: uuid.New(), Content: "Oh how the mighty have fallen", UserId: userId}
|
||||||
|
} else {
|
||||||
|
return message.Message{Id: id, Content: "Oh how the mighty have fallen", UserId: userId}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func testScheduledMessage(id uuid.UUID, userId uuid.UUID, now time.Time) scheduling.ScheduledMessage {
|
||||||
|
if id == uuid.Nil {
|
||||||
|
return scheduling.ScheduledMessage{Id: uuid.New(), UserId: userId, Scheduled: now.Add(20 * time.Minute), Status: scheduling.Pending}
|
||||||
|
} else {
|
||||||
|
return scheduling.ScheduledMessage{Id: id, UserId: userId, Scheduled: now.Add(20 * time.Minute), Status: scheduling.Pending}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func testScheduledMessageEvent(messageId, recipientId, scheduledMessageId uuid.UUID) scheduling.ScheduledMessageEvent {
|
||||||
|
return scheduling.ScheduledMessageEvent{MessageId: messageId, RecipientId: recipientId, ScheduledMessageId: scheduledMessageId}
|
||||||
|
}
|
||||||
@@ -0,0 +1,135 @@
|
|||||||
|
package handler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.kundeng.us/phoenix/textsender-models/pkg/message/scheduling"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
|
||||||
|
"git.kundeng.us/phoenix/textsender-api/internal/handler/endpoint"
|
||||||
|
"git.kundeng.us/phoenix/textsender-api/internal/store/mock"
|
||||||
|
)
|
||||||
|
|
||||||
|
type CreateScheduledMessageRequest struct {
|
||||||
|
Scheduled time.Time `json:"scheduled"`
|
||||||
|
Status string `json:"status"`
|
||||||
|
UserId uuid.UUID `json:"user_id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCreateScheduledMessageWithMock(t *testing.T) {
|
||||||
|
now := time.Now()
|
||||||
|
mockStore := mock.NewMockScheduledMessageStore()
|
||||||
|
handler := NewScheduledMessageHandler(mockStore)
|
||||||
|
|
||||||
|
testUserId := uuid.New()
|
||||||
|
testBody := testCreateScheduledMessageRequest(testUserId, now)
|
||||||
|
jsonValue, _ := json.Marshal(testBody)
|
||||||
|
|
||||||
|
req, _ := http.NewRequest("POST", endpoint.ScheduleMessageEndpoint, strings.NewReader(string(jsonValue)))
|
||||||
|
rr := httptest.NewRecorder()
|
||||||
|
|
||||||
|
handler.AddScheduledMessage(rr, req)
|
||||||
|
|
||||||
|
assert.Equal(t, http.StatusCreated, rr.Code)
|
||||||
|
|
||||||
|
var response AddScheduledMessageResponse
|
||||||
|
err := json.Unmarshal(rr.Body.Bytes(), &response)
|
||||||
|
assert.NoError(t, err, "Error Creating message %v", err)
|
||||||
|
|
||||||
|
assert.NotEmpty(t, response.Data, "No Message created")
|
||||||
|
|
||||||
|
assert.NotNil(t, response.Data[0].Id, "Id should not be nil")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGetScheduledMessageWithMock(t *testing.T) {
|
||||||
|
now := time.Now()
|
||||||
|
mockStore := mock.NewMockScheduledMessageStore()
|
||||||
|
|
||||||
|
testUserId := uuid.New()
|
||||||
|
testBody := testCreateScheduledMessageRequest(testUserId, now)
|
||||||
|
|
||||||
|
ctx := t.Context()
|
||||||
|
schMsg := scheduling.ScheduledMessage{}
|
||||||
|
schMsg.Scheduled = testBody.Scheduled
|
||||||
|
schMsg.Status = testBody.Status
|
||||||
|
schMsg.UserId = testBody.UserId
|
||||||
|
if err := mockStore.CreateScheduledMessage(ctx, &schMsg); err != nil {
|
||||||
|
assert.NoError(t, err, "Error Creating message %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
url := fmt.Sprintf("%s?id=%s&user_id=%s", endpoint.GetScheduledMessageEndpoint, schMsg.Id, schMsg.UserId)
|
||||||
|
req, _ := http.NewRequest("GET", url, nil)
|
||||||
|
rr := httptest.NewRecorder()
|
||||||
|
|
||||||
|
handler := NewScheduledMessageHandler(mockStore)
|
||||||
|
handler.GetScheduledMessage(rr, req)
|
||||||
|
|
||||||
|
assert.Equal(t, http.StatusOK, rr.Code)
|
||||||
|
|
||||||
|
var response GetScheduledMessageResponse
|
||||||
|
err := json.Unmarshal(rr.Body.Bytes(), &response)
|
||||||
|
assert.NoError(t, err, "Error parsing response %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFetchScheduledMessageWithMock(t *testing.T) {
|
||||||
|
now := time.Now()
|
||||||
|
mockStore := mock.NewMockScheduledMessageStore()
|
||||||
|
contactStore := mock.NewMockContactStore()
|
||||||
|
messageStore := mock.NewMockMessageStore()
|
||||||
|
schMsgEventStore := mock.NewMockScheduledMessageEventStore()
|
||||||
|
|
||||||
|
recipientId := uuid.New()
|
||||||
|
messageId := uuid.New()
|
||||||
|
scheduledMessageId := uuid.New()
|
||||||
|
testUserId := uuid.New()
|
||||||
|
|
||||||
|
con := testContact(recipientId, testUserId)
|
||||||
|
msg := testMessage(messageId, testUserId)
|
||||||
|
schMsg := testScheduledMessage(scheduledMessageId, testUserId, now)
|
||||||
|
event := testScheduledMessageEvent(msg.Id, con.Id, schMsg.Id)
|
||||||
|
|
||||||
|
ctx := t.Context()
|
||||||
|
|
||||||
|
if err := contactStore.CreateContact(ctx, &con); err != nil {
|
||||||
|
assert.NoError(t, err, "Error creating contact: %v", err)
|
||||||
|
} else if err = messageStore.CreateMessage(ctx, &msg); err != nil {
|
||||||
|
assert.NoError(t, err, "Error creating message: %v", err)
|
||||||
|
} else if err = mockStore.CreateScheduledMessage(ctx, &schMsg); err != nil {
|
||||||
|
assert.NoError(t, err, "Error creating scheduled message: %v", err)
|
||||||
|
} else if err = schMsgEventStore.CreateScheduledMessageEvent(ctx, &event); err != nil {
|
||||||
|
assert.NoError(t, err, "Error creating scheduled message event: %v", err)
|
||||||
|
} else if newStatus, err := mockStore.UpdateStatus(ctx, schMsg.Id, scheduling.Ready); err != nil {
|
||||||
|
assert.NoError(t, err, "Error updating status: %v", err)
|
||||||
|
} else {
|
||||||
|
assert.Equal(t, *newStatus, scheduling.Ready)
|
||||||
|
}
|
||||||
|
|
||||||
|
req, _ := http.NewRequest("GET", endpoint.FetchNextScheduledMessageEndpoint, nil)
|
||||||
|
rr := httptest.NewRecorder()
|
||||||
|
|
||||||
|
handler := NewScheduledMessageHandler(mockStore)
|
||||||
|
handler.FetchNextMessage(rr, req)
|
||||||
|
|
||||||
|
assert.Equal(t, http.StatusOK, rr.Code)
|
||||||
|
|
||||||
|
var response FetchNextMessageResponse
|
||||||
|
err := json.Unmarshal(rr.Body.Bytes(), &response)
|
||||||
|
assert.NoError(t, err, "Error fetching scheduled message: %v", err)
|
||||||
|
|
||||||
|
assert.NotEmpty(t, response.Data, "No data")
|
||||||
|
|
||||||
|
fetchedSchMsg := response.Data[0]
|
||||||
|
assert.Equal(t, scheduling.Processing, fetchedSchMsg.Status, "The statuses do not match")
|
||||||
|
}
|
||||||
|
|
||||||
|
func testCreateScheduledMessageRequest(userId uuid.UUID, now time.Time) CreateScheduledMessageRequest {
|
||||||
|
scheduled := now.Add(5 * time.Minute)
|
||||||
|
return CreateScheduledMessageRequest{Status: scheduling.Pending, UserId: userId, Scheduled: scheduled}
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
package middleware
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"git.kundeng.us/phoenix/textsender-api/internal/services"
|
||||||
|
)
|
||||||
|
|
||||||
|
type contextKey string
|
||||||
|
|
||||||
|
const (
|
||||||
|
UserContextKey contextKey = "user"
|
||||||
|
)
|
||||||
|
|
||||||
|
func AuthMiddleware(authService *services.JWTService) func(http.Handler) http.Handler {
|
||||||
|
return func(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
authHeader := r.Header.Get("Authorization")
|
||||||
|
if authHeader == "" {
|
||||||
|
http.Error(w, "Authorization header required", http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extract token from "Bearer <token>"
|
||||||
|
parts := strings.Split(authHeader, " ")
|
||||||
|
if len(parts) != 2 || parts[0] != "Bearer" {
|
||||||
|
http.Error(w, "Invalid authorization header format", http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
token := parts[1]
|
||||||
|
|
||||||
|
// Validate token with auth service
|
||||||
|
user, err := authService.ValidateToken(token)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Invalid token", http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add user to context
|
||||||
|
ctx := context.WithValue(r.Context(), UserContextKey, user)
|
||||||
|
next.ServeHTTP(w, r.WithContext(ctx))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
package services
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/golang-jwt/jwt/v5"
|
||||||
|
|
||||||
|
txtmodels_token "git.kundeng.us/phoenix/textsender-models/pkg/token"
|
||||||
|
txtmodels_user "git.kundeng.us/phoenix/textsender-models/pkg/user"
|
||||||
|
)
|
||||||
|
|
||||||
|
type JWTService struct {
|
||||||
|
secretKey []byte
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewJWTService(secretKey string) *JWTService {
|
||||||
|
return &JWTService{
|
||||||
|
secretKey: []byte(secretKey),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *JWTService) ValidateToken(tokenString string) (*txtmodels_user.User, error) {
|
||||||
|
// TODO: Include more user information in the claims to populate user
|
||||||
|
claims := &txtmodels_token.Claims{}
|
||||||
|
|
||||||
|
token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
|
||||||
|
// Validate the signing method
|
||||||
|
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||||
|
return nil, jwt.ErrSignatureInvalid
|
||||||
|
}
|
||||||
|
return s.secretKey, nil
|
||||||
|
})
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if !token.Valid {
|
||||||
|
return nil, jwt.ErrSignatureInvalid
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check token expiration
|
||||||
|
if time.Now().After(claims.ExpiresAt.Time) {
|
||||||
|
return nil, jwt.ErrTokenExpired
|
||||||
|
}
|
||||||
|
|
||||||
|
return &txtmodels_user.User{
|
||||||
|
Id: claims.UserId,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
|
||||||
|
"git.kundeng.us/phoenix/textsender-models/pkg/contact"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ContactStore interface {
|
||||||
|
CreateContact(ctx context.Context, con *contact.Contact) error
|
||||||
|
GetContactByID(ctx context.Context, id uuid.UUID) (*contact.Contact, error)
|
||||||
|
GetContactByPhone(ctx context.Context, phone string, userId uuid.UUID) (*contact.Contact, error)
|
||||||
|
GetAllContacts(ctx context.Context) ([]*contact.Contact, error)
|
||||||
|
ContactExists(ctx context.Context, phone string, userId uuid.UUID) (bool, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type PGContactStore struct {
|
||||||
|
db *pgxpool.Pool
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewContactStore(db *pgxpool.Pool) *PGContactStore {
|
||||||
|
return &PGContactStore{db: db}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *PGContactStore) CreateContact(ctx context.Context, con *contact.Contact) error {
|
||||||
|
query := `
|
||||||
|
INSERT INTO contacts (phone_number, user_id)
|
||||||
|
VALUES ($1, $2)
|
||||||
|
RETURNING id, phone_number, user_id
|
||||||
|
`
|
||||||
|
|
||||||
|
return s.db.QueryRow(ctx, query, con.PhoneNumber, con.UserId).Scan(
|
||||||
|
&con.Id, &con.PhoneNumber, &con.UserId,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *PGContactStore) GetContactByID(ctx context.Context, id uuid.UUID) (*contact.Contact, error) {
|
||||||
|
query := `SELECT id, phone_number, user_id FROM contacts WHERE id = $1`
|
||||||
|
|
||||||
|
var con contact.Contact
|
||||||
|
err := s.db.QueryRow(ctx, query, id).Scan(
|
||||||
|
&con.Id, &con.PhoneNumber, &con.UserId,
|
||||||
|
)
|
||||||
|
|
||||||
|
if err == pgx.ErrNoRows {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("getting contact by ID: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &con, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *PGContactStore) GetContactByPhone(ctx context.Context, phone string, userId uuid.UUID) (*contact.Contact, error) {
|
||||||
|
query := `SELECT id, phone_number, user_id FROM contacts WHERE phone_number = $1 AND user_id = $2`
|
||||||
|
|
||||||
|
var con contact.Contact
|
||||||
|
err := s.db.QueryRow(ctx, query, phone, userId).Scan(
|
||||||
|
&con.Id, &con.PhoneNumber, &con.UserId,
|
||||||
|
)
|
||||||
|
|
||||||
|
if err == pgx.ErrNoRows {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("getting contact by phone and User ID: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &con, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *PGContactStore) GetAllContacts(ctx context.Context) ([]*contact.Contact, error) {
|
||||||
|
query := `SELECT id, phone_number, user_id FROM contacts`
|
||||||
|
|
||||||
|
rows, err := s.db.Query(ctx, query)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("querying all contacts: %w", err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
var cons []*contact.Contact
|
||||||
|
for rows.Next() {
|
||||||
|
var con contact.Contact
|
||||||
|
if err := rows.Scan(
|
||||||
|
&con.Id, &con.PhoneNumber, &con.UserId,
|
||||||
|
); err != nil {
|
||||||
|
return nil, fmt.Errorf("scanning contact row: %w", err)
|
||||||
|
}
|
||||||
|
cons = append(cons, &con)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return nil, fmt.Errorf("iterating contact rows: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return cons, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *PGContactStore) ContactExists(ctx context.Context, phone string, userId uuid.UUID) (bool, error) {
|
||||||
|
query := `SELECT EXISTS(SELECT 1 FROM contacts WHERE phone_number = $1 AND user_id = $2)`
|
||||||
|
|
||||||
|
var exists bool
|
||||||
|
err := s.db.QueryRow(ctx, query, phone, userId).Scan(&exists)
|
||||||
|
if err != nil {
|
||||||
|
return false, fmt.Errorf("checking if contact exists: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return exists, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
|
||||||
|
"git.kundeng.us/phoenix/textsender-models/pkg/message"
|
||||||
|
)
|
||||||
|
|
||||||
|
type MessageStore interface {
|
||||||
|
GetMessageByID(ctx context.Context, id uuid.UUID) (*message.Message, error)
|
||||||
|
CreateMessage(ctx context.Context, msg *message.Message) error
|
||||||
|
GetAllMessages(ctx context.Context) ([]*message.Message, error)
|
||||||
|
MessageExists(ctx context.Context, msg *message.Message) (bool, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type PGMessageStore struct {
|
||||||
|
db *pgxpool.Pool
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewMessageStore(db *pgxpool.Pool) *PGMessageStore {
|
||||||
|
return &PGMessageStore{db: db}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *PGMessageStore) CreateMessage(ctx context.Context, msg *message.Message) error {
|
||||||
|
query := `
|
||||||
|
INSERT INTO messages (content, user_id)
|
||||||
|
VALUES ($1, $2)
|
||||||
|
RETURNING id
|
||||||
|
`
|
||||||
|
|
||||||
|
return m.db.QueryRow(ctx, query, msg.Content, msg.UserId).Scan(
|
||||||
|
&msg.Id,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *PGMessageStore) MessageExists(ctx context.Context, msg *message.Message) (bool, error) {
|
||||||
|
query := `SELECT EXISTS(SELECT 1 FROM messages WHERE content = $1 AND user_id = $2)`
|
||||||
|
|
||||||
|
var exists bool
|
||||||
|
err := m.db.QueryRow(ctx, query, msg.Content, msg.UserId).Scan(&exists)
|
||||||
|
if err != nil {
|
||||||
|
return false, fmt.Errorf("checking if message exists: %w", err)
|
||||||
|
} else {
|
||||||
|
return exists, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *PGMessageStore) GetAllMessages(ctx context.Context) ([]*message.Message, error) {
|
||||||
|
query := `SELECT id, content, user_id FROM messages`
|
||||||
|
|
||||||
|
rows, err := m.db.Query(ctx, query)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("querying all messages: %w", err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
var messages []*message.Message
|
||||||
|
for rows.Next() {
|
||||||
|
var msg message.Message
|
||||||
|
if err := rows.Scan(
|
||||||
|
&msg.Id, &msg.Content, &msg.UserId,
|
||||||
|
); err != nil {
|
||||||
|
return nil, fmt.Errorf("scanning message row: %w", err)
|
||||||
|
}
|
||||||
|
messages = append(messages, &msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return nil, fmt.Errorf("iterating message rows: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return messages, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *PGMessageStore) GetMessageByID(ctx context.Context, id uuid.UUID) (*message.Message, error) {
|
||||||
|
query := `SELECT id, content, user_id FROM messages WHERE id = $1`
|
||||||
|
|
||||||
|
var msg message.Message
|
||||||
|
err := m.db.QueryRow(ctx, query, id).Scan(
|
||||||
|
&msg.Id, &msg.Content, &msg.UserId,
|
||||||
|
)
|
||||||
|
|
||||||
|
if err == pgx.ErrNoRows {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("getting message by ID: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &msg, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,202 @@
|
|||||||
|
package mock
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"git.kundeng.us/phoenix/textsender-models/pkg/contact"
|
||||||
|
"git.kundeng.us/phoenix/textsender-models/pkg/message"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Key struct {
|
||||||
|
PhoneNumber string
|
||||||
|
UserId uuid.UUID
|
||||||
|
}
|
||||||
|
|
||||||
|
type MockContactStore struct {
|
||||||
|
Contacts map[uuid.UUID]*contact.Contact
|
||||||
|
ContactsByKey map[Key]*contact.Contact
|
||||||
|
mu sync.RWMutex
|
||||||
|
Error error // Optional: simulate errors
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewMockContactStore() *MockContactStore {
|
||||||
|
return &MockContactStore{
|
||||||
|
Contacts: make(map[uuid.UUID]*contact.Contact),
|
||||||
|
ContactsByKey: make(map[Key]*contact.Contact),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MockContactStore) CreateContact(ctx context.Context, con *contact.Contact) error {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
|
||||||
|
if m.Error != nil {
|
||||||
|
return m.Error
|
||||||
|
}
|
||||||
|
|
||||||
|
if con.Id == uuid.Nil {
|
||||||
|
con.Id = uuid.New()
|
||||||
|
}
|
||||||
|
|
||||||
|
key := Key{PhoneNumber: con.PhoneNumber, UserId: con.UserId}
|
||||||
|
if _, exists := m.ContactsByKey[key]; exists {
|
||||||
|
return errors.New("Contact with phone number already exists")
|
||||||
|
}
|
||||||
|
|
||||||
|
m.Contacts[con.Id] = con
|
||||||
|
m.ContactsByKey[key] = con
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MockContactStore) GetContactByID(ctx context.Context, id uuid.UUID) (*contact.Contact, error) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
|
||||||
|
if m.Error != nil {
|
||||||
|
return nil, m.Error
|
||||||
|
}
|
||||||
|
|
||||||
|
if m.Error != nil {
|
||||||
|
return nil, m.Error
|
||||||
|
}
|
||||||
|
|
||||||
|
con, exists := m.Contacts[id]
|
||||||
|
if !exists {
|
||||||
|
return nil, errors.New("Contact not found")
|
||||||
|
}
|
||||||
|
|
||||||
|
return con, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MockContactStore) GetContactByPhone(ctx context.Context, phoneNumber string, userId uuid.UUID) (*contact.Contact, error) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
|
||||||
|
if m.Error != nil {
|
||||||
|
return nil, m.Error
|
||||||
|
}
|
||||||
|
|
||||||
|
con, exists := m.ContactsByKey[Key{PhoneNumber: phoneNumber, UserId: userId}]
|
||||||
|
if !exists {
|
||||||
|
return nil, errors.New("Contact not found")
|
||||||
|
}
|
||||||
|
|
||||||
|
return con, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MockContactStore) GetAllContacts(ctx context.Context) ([]*contact.Contact, error) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
|
||||||
|
if m.Error != nil {
|
||||||
|
return nil, m.Error
|
||||||
|
}
|
||||||
|
|
||||||
|
cons := make([]*contact.Contact, 0, len(m.Contacts))
|
||||||
|
for _, con := range m.Contacts {
|
||||||
|
cons = append(cons, con)
|
||||||
|
}
|
||||||
|
|
||||||
|
return cons, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MockContactStore) ContactExists(ctx context.Context, phoneNumber string, userId uuid.UUID) (bool, error) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
|
||||||
|
if m.Error != nil {
|
||||||
|
return false, m.Error
|
||||||
|
}
|
||||||
|
|
||||||
|
_, exists := m.ContactsByKey[Key{PhoneNumber: phoneNumber, UserId: userId}]
|
||||||
|
|
||||||
|
return exists, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type MessageKey struct {
|
||||||
|
Content string
|
||||||
|
UserId uuid.UUID
|
||||||
|
}
|
||||||
|
|
||||||
|
type MockMessageStore struct {
|
||||||
|
Messages map[uuid.UUID]*message.Message
|
||||||
|
MessagesByKey map[MessageKey]*message.Message
|
||||||
|
mu sync.RWMutex
|
||||||
|
Error error // Optional: simulate errors
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewMockMessageStore() *MockMessageStore {
|
||||||
|
return &MockMessageStore{
|
||||||
|
Messages: make(map[uuid.UUID]*message.Message),
|
||||||
|
MessagesByKey: make(map[MessageKey]*message.Message),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MockMessageStore) CreateMessage(ctx context.Context, msg *message.Message) error {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
|
||||||
|
if m.Error != nil {
|
||||||
|
return m.Error
|
||||||
|
}
|
||||||
|
|
||||||
|
if msg.Id == uuid.Nil {
|
||||||
|
msg.Id = uuid.New()
|
||||||
|
}
|
||||||
|
|
||||||
|
key := MessageKey{Content: msg.Content, UserId: msg.UserId}
|
||||||
|
if _, exists := m.MessagesByKey[key]; exists {
|
||||||
|
return errors.New("Message already exists")
|
||||||
|
}
|
||||||
|
|
||||||
|
m.Messages[msg.Id] = msg
|
||||||
|
m.MessagesByKey[key] = msg
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MockMessageStore) GetAllMessages(ctx context.Context) ([]*message.Message, error) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
|
||||||
|
if m.Error != nil {
|
||||||
|
return nil, m.Error
|
||||||
|
}
|
||||||
|
|
||||||
|
var msgs []*message.Message
|
||||||
|
|
||||||
|
for _, msg := range m.Messages {
|
||||||
|
msgs = append(msgs, msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
return msgs, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MockMessageStore) GetMessageByID(ctx context.Context, id uuid.UUID) (*message.Message, error) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
|
||||||
|
if m.Error != nil {
|
||||||
|
return nil, m.Error
|
||||||
|
}
|
||||||
|
|
||||||
|
msg := m.Messages[id]
|
||||||
|
|
||||||
|
return msg, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MockMessageStore) MessageExists(ctx context.Context, msg *message.Message) (bool, error) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
|
||||||
|
if m.Error != nil {
|
||||||
|
return false, m.Error
|
||||||
|
}
|
||||||
|
|
||||||
|
_, exists := m.MessagesByKey[MessageKey{Content: msg.Content, UserId: msg.UserId}]
|
||||||
|
|
||||||
|
return exists, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,160 @@
|
|||||||
|
package mock
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"git.kundeng.us/phoenix/textsender-models/pkg/message/scheduling"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ScheduledMessageEventKey struct {
|
||||||
|
RecipientId uuid.UUID
|
||||||
|
MessageId uuid.UUID
|
||||||
|
ScheduledMessageId uuid.UUID
|
||||||
|
}
|
||||||
|
|
||||||
|
type MockScheduledMessageEventStore struct {
|
||||||
|
ScheduledMessageEvents map[uuid.UUID]*scheduling.ScheduledMessageEvent
|
||||||
|
ScheduledMessageEventsByKey map[ScheduledMessageEventKey]*scheduling.ScheduledMessageEvent
|
||||||
|
mu sync.RWMutex
|
||||||
|
Error error // Optional: simulate errors
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewMockScheduledMessageEventStore() *MockScheduledMessageEventStore {
|
||||||
|
return &MockScheduledMessageEventStore{
|
||||||
|
ScheduledMessageEvents: make(map[uuid.UUID]*scheduling.ScheduledMessageEvent),
|
||||||
|
ScheduledMessageEventsByKey: make(map[ScheduledMessageEventKey]*scheduling.ScheduledMessageEvent),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MockScheduledMessageEventStore) Get(ctx context.Context, id uuid.UUID) (*scheduling.ScheduledMessageEvent, error) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
|
||||||
|
if m.Error != nil {
|
||||||
|
return nil, m.Error
|
||||||
|
}
|
||||||
|
|
||||||
|
if id == uuid.Nil {
|
||||||
|
return nil, fmt.Errorf("Id is nil")
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, exists := m.ScheduledMessageEvents[id]; exists {
|
||||||
|
return m.ScheduledMessageEvents[id], nil
|
||||||
|
} else {
|
||||||
|
return nil, fmt.Errorf("Not found")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MockScheduledMessageEventStore) GetWithScheduleMessageId(ctx context.Context, schMsgId uuid.UUID) ([]*scheduling.ScheduledMessageEvent, error) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
|
||||||
|
if m.Error != nil {
|
||||||
|
return nil, m.Error
|
||||||
|
}
|
||||||
|
|
||||||
|
if schMsgId == uuid.Nil {
|
||||||
|
return nil, fmt.Errorf("Scheduled message Id is nil")
|
||||||
|
}
|
||||||
|
|
||||||
|
var events []*scheduling.ScheduledMessageEvent
|
||||||
|
|
||||||
|
for _, event := range m.ScheduledMessageEvents {
|
||||||
|
if event.ScheduledMessageId == schMsgId {
|
||||||
|
events = append(events, event)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(events) > 0 {
|
||||||
|
return events, nil
|
||||||
|
} else {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MockScheduledMessageEventStore) Delete(ctx context.Context, id uuid.UUID) error {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
|
||||||
|
if m.Error != nil {
|
||||||
|
return m.Error
|
||||||
|
}
|
||||||
|
|
||||||
|
if id == uuid.Nil {
|
||||||
|
return fmt.Errorf("Id is nil")
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, exists := m.ScheduledMessageEvents[id]; exists {
|
||||||
|
originalAmount := len(m.ScheduledMessageEvents)
|
||||||
|
copiedEvents := make(map[uuid.UUID]*scheduling.ScheduledMessageEvent)
|
||||||
|
copiedEventsKey := make(map[ScheduledMessageEventKey]*scheduling.ScheduledMessageEvent)
|
||||||
|
|
||||||
|
for i, schMsgEvent := range m.ScheduledMessageEvents {
|
||||||
|
key := ScheduledMessageEventKey{RecipientId: schMsgEvent.RecipientId, MessageId: schMsgEvent.MessageId, ScheduledMessageId: schMsgEvent.ScheduledMessageId}
|
||||||
|
if schMsgEvent.Id != id {
|
||||||
|
copiedEvents[i] = schMsgEvent
|
||||||
|
copiedEventsKey[key] = schMsgEvent
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if originalAmount > 1 {
|
||||||
|
if len(copiedEvents) > 0 && len(copiedEventsKey) > 0 {
|
||||||
|
m.ScheduledMessageEvents = copiedEvents
|
||||||
|
m.ScheduledMessageEventsByKey = copiedEventsKey
|
||||||
|
return nil
|
||||||
|
} else {
|
||||||
|
return fmt.Errorf("Not removed")
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
m.ScheduledMessageEvents = make(map[uuid.UUID]*scheduling.ScheduledMessageEvent)
|
||||||
|
m.ScheduledMessageEventsByKey = make(map[ScheduledMessageEventKey]*scheduling.ScheduledMessageEvent)
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return fmt.Errorf("Not found")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MockScheduledMessageEventStore) CreateScheduledMessageEvent(ctx context.Context, event *scheduling.ScheduledMessageEvent) error {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
|
||||||
|
if m.Error != nil {
|
||||||
|
return m.Error
|
||||||
|
}
|
||||||
|
|
||||||
|
if event.Id == uuid.Nil {
|
||||||
|
event.Id = uuid.New()
|
||||||
|
}
|
||||||
|
|
||||||
|
key := ScheduledMessageEventKey{RecipientId: event.RecipientId, MessageId: event.MessageId, ScheduledMessageId: event.ScheduledMessageId}
|
||||||
|
|
||||||
|
if _, exists := m.ScheduledMessageEventsByKey[key]; exists {
|
||||||
|
return fmt.Errorf("Already exists")
|
||||||
|
} else {
|
||||||
|
event.Created = time.Now()
|
||||||
|
m.ScheduledMessageEvents[event.Id] = event
|
||||||
|
m.ScheduledMessageEventsByKey[key] = event
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MockScheduledMessageEventStore) Exists(ctx context.Context, event *scheduling.ScheduledMessageEvent) (bool, error) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
|
||||||
|
if m.Error != nil {
|
||||||
|
return false, m.Error
|
||||||
|
}
|
||||||
|
|
||||||
|
key := ScheduledMessageEventKey{RecipientId: event.RecipientId, MessageId: event.MessageId, ScheduledMessageId: event.ScheduledMessageId}
|
||||||
|
_, exists := m.ScheduledMessageEventsByKey[key]
|
||||||
|
|
||||||
|
return exists, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
package mock
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"git.kundeng.us/phoenix/textsender-models/pkg/message/scheduling"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ScheduledMessageKey struct {
|
||||||
|
UserId uuid.UUID
|
||||||
|
}
|
||||||
|
|
||||||
|
type MockScheduledMessageStore struct {
|
||||||
|
ScheduledMessages map[uuid.UUID]*scheduling.ScheduledMessage
|
||||||
|
ScheduledMessagesByKey map[ScheduledMessageKey]*scheduling.ScheduledMessage
|
||||||
|
mu sync.RWMutex
|
||||||
|
Error error // Optional: simulate errors
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewMockScheduledMessageStore() *MockScheduledMessageStore {
|
||||||
|
return &MockScheduledMessageStore{
|
||||||
|
ScheduledMessages: make(map[uuid.UUID]*scheduling.ScheduledMessage),
|
||||||
|
ScheduledMessagesByKey: make(map[ScheduledMessageKey]*scheduling.ScheduledMessage),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MockScheduledMessageStore) Get(ctx context.Context, id uuid.UUID) (*scheduling.ScheduledMessage, error) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
|
||||||
|
if m.Error != nil {
|
||||||
|
return nil, m.Error
|
||||||
|
}
|
||||||
|
|
||||||
|
if id == uuid.Nil {
|
||||||
|
return nil, fmt.Errorf("Id is nil")
|
||||||
|
} else {
|
||||||
|
if schMsg := m.ScheduledMessages[id]; schMsg != nil {
|
||||||
|
return schMsg, nil
|
||||||
|
} else {
|
||||||
|
return nil, fmt.Errorf("Scheduled message does not exist")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MockScheduledMessageStore) FetchNextScheduledMessage(ctx context.Context) (*scheduling.ScheduledMessage, error) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
|
||||||
|
if m.Error != nil {
|
||||||
|
return nil, m.Error
|
||||||
|
}
|
||||||
|
|
||||||
|
var schMsg *scheduling.ScheduledMessage
|
||||||
|
for _, msg := range m.ScheduledMessages {
|
||||||
|
if msg.Status == scheduling.Ready {
|
||||||
|
msg.Status = scheduling.Processing
|
||||||
|
schMsg = msg
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if schMsg == nil {
|
||||||
|
return nil, fmt.Errorf("No scheduled message is ready")
|
||||||
|
} else {
|
||||||
|
return schMsg, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MockScheduledMessageStore) GetWithUserId(ctx context.Context, userId uuid.UUID) ([]*scheduling.ScheduledMessage, error) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
|
||||||
|
if m.Error != nil {
|
||||||
|
return nil, m.Error
|
||||||
|
}
|
||||||
|
|
||||||
|
if userId == uuid.Nil {
|
||||||
|
return nil, fmt.Errorf("User Id is nil")
|
||||||
|
} else {
|
||||||
|
var schMsgs []*scheduling.ScheduledMessage
|
||||||
|
for _, schMsg := range m.ScheduledMessages {
|
||||||
|
if schMsg.UserId == userId {
|
||||||
|
schMsgs = append(schMsgs, schMsg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(schMsgs) == 0 {
|
||||||
|
return nil, nil
|
||||||
|
} else {
|
||||||
|
return schMsgs, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MockScheduledMessageStore) CreateScheduledMessage(ctx context.Context, schedMsg *scheduling.ScheduledMessage) error {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
|
||||||
|
if m.Error != nil {
|
||||||
|
return m.Error
|
||||||
|
}
|
||||||
|
|
||||||
|
if schedMsg.Id == uuid.Nil {
|
||||||
|
schedMsg.Id = uuid.New()
|
||||||
|
}
|
||||||
|
|
||||||
|
key := ScheduledMessageKey{UserId: schedMsg.UserId}
|
||||||
|
|
||||||
|
m.ScheduledMessages[schedMsg.Id] = schedMsg
|
||||||
|
m.ScheduledMessagesByKey[key] = schedMsg
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *MockScheduledMessageStore) UpdateStatus(ctx context.Context, id uuid.UUID, updatedStatus string) (*string, error) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
|
||||||
|
if m.Error != nil {
|
||||||
|
return nil, m.Error
|
||||||
|
}
|
||||||
|
|
||||||
|
if id == uuid.Nil {
|
||||||
|
return nil, fmt.Errorf("Id is nil")
|
||||||
|
} else {
|
||||||
|
if schMsg := m.ScheduledMessages[id]; schMsg != nil {
|
||||||
|
key := ScheduledMessageKey{UserId: schMsg.UserId}
|
||||||
|
|
||||||
|
schMsg.Status = updatedStatus
|
||||||
|
m.ScheduledMessages[schMsg.Id] = schMsg
|
||||||
|
m.ScheduledMessagesByKey[key] = schMsg
|
||||||
|
|
||||||
|
return &updatedStatus, nil
|
||||||
|
} else {
|
||||||
|
return nil, fmt.Errorf("Scheduled message does not exist")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
|
||||||
|
"git.kundeng.us/phoenix/textsender-models/pkg/message/scheduling"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ScheduledMessageEventStore interface {
|
||||||
|
Get(ctx context.Context, id uuid.UUID) (*scheduling.ScheduledMessageEvent, error)
|
||||||
|
GetWithScheduleMessageId(ctx context.Context, schMsgId uuid.UUID) ([]*scheduling.ScheduledMessageEvent, error)
|
||||||
|
Delete(ctx context.Context, id uuid.UUID) error
|
||||||
|
CreateScheduledMessageEvent(ctx context.Context, event *scheduling.ScheduledMessageEvent) error
|
||||||
|
Exists(ctx context.Context, event *scheduling.ScheduledMessageEvent) (bool, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type PGScheduledMessageEventStore struct {
|
||||||
|
db *pgxpool.Pool
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewScheduledMessageEventStore(db *pgxpool.Pool) *PGScheduledMessageEventStore {
|
||||||
|
return &PGScheduledMessageEventStore{db: db}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *PGScheduledMessageEventStore) Get(ctx context.Context, id uuid.UUID) (*scheduling.ScheduledMessageEvent, error) {
|
||||||
|
query := `SELECT id, recipient_id, message_id, scheduled_message_id, created FROM scheduled_message_events WHERE id = $1`
|
||||||
|
|
||||||
|
var event scheduling.ScheduledMessageEvent
|
||||||
|
err := s.db.QueryRow(ctx, query, id).Scan(
|
||||||
|
&event.Id, &event.RecipientId, &event.MessageId, &event.ScheduledMessageId, &event.Created,
|
||||||
|
)
|
||||||
|
|
||||||
|
if err == pgx.ErrNoRows {
|
||||||
|
return nil, nil
|
||||||
|
} else if err != nil {
|
||||||
|
return nil, fmt.Errorf("getting scheduled message event by ID: %w", err)
|
||||||
|
} else {
|
||||||
|
return &event, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *PGScheduledMessageEventStore) GetWithScheduleMessageId(ctx context.Context, schMsgId uuid.UUID) ([]*scheduling.ScheduledMessageEvent, error) {
|
||||||
|
var events []*scheduling.ScheduledMessageEvent
|
||||||
|
query := `SELECT id, recipient_id, message_id, scheduled_message_id, created FROM scheduled_message_events WHERE scheduled_message_id = $1
|
||||||
|
`
|
||||||
|
|
||||||
|
rows, err := s.db.Query(ctx, query, schMsgId)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("Error retrieving rows from scheduled_message_Events: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
for rows.Next() {
|
||||||
|
var event scheduling.ScheduledMessageEvent
|
||||||
|
|
||||||
|
if err := rows.Scan(&event.Id, &event.RecipientId, &event.MessageId, &event.ScheduledMessageId, &event.Created); err != nil {
|
||||||
|
return nil, fmt.Errorf("Error fetching data from row: %w", err)
|
||||||
|
} else {
|
||||||
|
events = append(events, &event)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return events, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *PGScheduledMessageEventStore) Delete(ctx context.Context, id uuid.UUID) error {
|
||||||
|
query := `
|
||||||
|
DELETE FROM scheduled_message_events WHERE id = $1
|
||||||
|
`
|
||||||
|
|
||||||
|
commandTag, err := s.db.Exec(ctx, query, id)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("error deleting event: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if commandTag.RowsAffected() == 0 {
|
||||||
|
return fmt.Errorf("no event found with id %d", id)
|
||||||
|
} else {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *PGScheduledMessageEventStore) CreateScheduledMessageEvent(ctx context.Context, event *scheduling.ScheduledMessageEvent) error {
|
||||||
|
query := `
|
||||||
|
INSERT INTO scheduled_message_events (recipient_id, message_id, scheduled_message_id)
|
||||||
|
VALUES ($1, $2, $3)
|
||||||
|
RETURNING id, created
|
||||||
|
`
|
||||||
|
|
||||||
|
return s.db.QueryRow(ctx, query, event.RecipientId, event.MessageId, event.ScheduledMessageId).Scan(
|
||||||
|
&event.Id, &event.Created,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *PGScheduledMessageEventStore) Exists(ctx context.Context, event *scheduling.ScheduledMessageEvent) (bool, error) {
|
||||||
|
query := `SELECT EXISTS(SELECT 1 FROM scheduled_message_events WHERE scheduled_message_id = $1 AND recipient_id = $2)`
|
||||||
|
|
||||||
|
var exists bool
|
||||||
|
err := s.db.QueryRow(ctx, query, event.ScheduledMessageId, event.RecipientId).Scan(&exists)
|
||||||
|
if err != nil {
|
||||||
|
return false, fmt.Errorf("Scheduled message event does not exist: %w", err)
|
||||||
|
} else {
|
||||||
|
return exists, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,128 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
|
||||||
|
"git.kundeng.us/phoenix/textsender-models/pkg/message/scheduling"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ScheduledMessageStore interface {
|
||||||
|
Get(ctx context.Context, id uuid.UUID) (*scheduling.ScheduledMessage, error)
|
||||||
|
FetchNextScheduledMessage(ctx context.Context) (*scheduling.ScheduledMessage, error)
|
||||||
|
GetWithUserId(ctx context.Context, userId uuid.UUID) ([]*scheduling.ScheduledMessage, error)
|
||||||
|
CreateScheduledMessage(ctx context.Context, schedMsg *scheduling.ScheduledMessage) error
|
||||||
|
UpdateStatus(ctx context.Context, id uuid.UUID, updatedStatus string) (*string, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type PGScheduledMessageStore struct {
|
||||||
|
db *pgxpool.Pool
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewScheduledMessageStore(db *pgxpool.Pool) *PGScheduledMessageStore {
|
||||||
|
return &PGScheduledMessageStore{db: db}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *PGScheduledMessageStore) Get(ctx context.Context, id uuid.UUID) (*scheduling.ScheduledMessage, error) {
|
||||||
|
query := `
|
||||||
|
SELECT id, scheduled, created, status, user_id FROM scheduled_messages WHERE id = $1
|
||||||
|
`
|
||||||
|
|
||||||
|
var schMsg scheduling.ScheduledMessage
|
||||||
|
err := s.db.QueryRow(ctx, query, id).Scan(
|
||||||
|
&schMsg.Id, &schMsg.Scheduled, &schMsg.Created, &schMsg.Status, &schMsg.UserId,
|
||||||
|
)
|
||||||
|
|
||||||
|
if err == pgx.ErrNoRows {
|
||||||
|
return nil, fmt.Errorf("No rows")
|
||||||
|
} else if err != nil {
|
||||||
|
return nil, fmt.Errorf("Getting scheduled message: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &schMsg, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *PGScheduledMessageStore) FetchNextScheduledMessage(ctx context.Context) (*scheduling.ScheduledMessage, error) {
|
||||||
|
query := `
|
||||||
|
UPDATE scheduled_messages
|
||||||
|
SET status = $1
|
||||||
|
WHERE id = (
|
||||||
|
SELECT id FROM scheduled_messages
|
||||||
|
WHERE status = $2
|
||||||
|
ORDER BY id
|
||||||
|
FOR UPDATE SKIP LOCKED
|
||||||
|
LIMIT 1
|
||||||
|
)
|
||||||
|
RETURNING id, scheduled, created, status, user_id
|
||||||
|
`
|
||||||
|
var schMsg scheduling.ScheduledMessage
|
||||||
|
err := s.db.QueryRow(ctx, query, scheduling.Processing, scheduling.Ready).Scan(
|
||||||
|
&schMsg.Id, &schMsg.Scheduled, &schMsg.Created, &schMsg.Status, &schMsg.UserId,
|
||||||
|
)
|
||||||
|
|
||||||
|
if err == pgx.ErrNoRows {
|
||||||
|
return nil, nil
|
||||||
|
} else if err != nil {
|
||||||
|
return nil, fmt.Errorf("Getting scheduled message: %w", err)
|
||||||
|
} else {
|
||||||
|
return &schMsg, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *PGScheduledMessageStore) GetWithUserId(ctx context.Context, userId uuid.UUID) ([]*scheduling.ScheduledMessage, error) {
|
||||||
|
query := `
|
||||||
|
SELECT id, scheduled, created, status, user_id FROM scheduled_messages WHERE user_id = $1
|
||||||
|
`
|
||||||
|
rows, err := s.db.Query(ctx, query, userId)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("Error retrieving rows from scheduled_messages: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var schMsgs []*scheduling.ScheduledMessage
|
||||||
|
|
||||||
|
for rows.Next() {
|
||||||
|
var schMsg scheduling.ScheduledMessage
|
||||||
|
if err := rows.Scan(&schMsg.Id, &schMsg.Scheduled, &schMsg.Created, &schMsg.Status, &schMsg.UserId); err != nil {
|
||||||
|
return nil, fmt.Errorf("Error fetching data from row: %w", err)
|
||||||
|
} else {
|
||||||
|
schMsgs = append(schMsgs, &schMsg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
} else {
|
||||||
|
return schMsgs, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *PGScheduledMessageStore) CreateScheduledMessage(ctx context.Context, schedMsg *scheduling.ScheduledMessage) error {
|
||||||
|
query := `
|
||||||
|
INSERT INTO scheduled_messages (scheduled, status, user_id)
|
||||||
|
VALUES ($1, $2, $3)
|
||||||
|
RETURNING id, created
|
||||||
|
`
|
||||||
|
|
||||||
|
return s.db.QueryRow(ctx, query, schedMsg.Scheduled, schedMsg.Status, schedMsg.UserId).Scan(
|
||||||
|
&schedMsg.Id, &schedMsg.Created,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *PGScheduledMessageStore) UpdateStatus(ctx context.Context, id uuid.UUID, updatedStatus string) (*string, error) {
|
||||||
|
query := `
|
||||||
|
UPDATE scheduled_messages set status = $1 WHERE id = $2
|
||||||
|
RETURNING status
|
||||||
|
`
|
||||||
|
|
||||||
|
var returnedStatus string
|
||||||
|
|
||||||
|
if err := s.db.QueryRow(ctx, query, updatedStatus, id).Scan(&returnedStatus); err != nil {
|
||||||
|
return nil, err
|
||||||
|
} else {
|
||||||
|
return &returnedStatus, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package version
|
||||||
|
|
||||||
|
import "fmt"
|
||||||
|
|
||||||
|
var (
|
||||||
|
Version = "dev"
|
||||||
|
BuildTime = "none"
|
||||||
|
Commit = "unknown"
|
||||||
|
GoVersion = "unknown"
|
||||||
|
)
|
||||||
|
|
||||||
|
func String() string {
|
||||||
|
return fmt.Sprintf(
|
||||||
|
"Version: %s\nBuild Date: %s\nCommit: %s\nGo Version: %s",
|
||||||
|
Version, BuildTime, Commit, GoVersion,
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
|
||||||
|
|
||||||
|
DROP TABLE IF EXISTS contacts CASCADE;
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS contacts (
|
||||||
|
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
||||||
|
phone_number TEXT NOT NULL,
|
||||||
|
user_id UUID NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS messages (
|
||||||
|
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
||||||
|
content TEXT NOT NULL,
|
||||||
|
user_id UUID NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS scheduled_messages (
|
||||||
|
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
||||||
|
scheduled timestamptz NOT NULL,
|
||||||
|
created timestamptz DEFAULT now(),
|
||||||
|
status TEXT CHECK (status IN ('PENDING', 'READY', 'PROCESSING', 'DONE')),
|
||||||
|
user_id UUID NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS scheduled_message_events (
|
||||||
|
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
||||||
|
recipient_id UUID NOT NULL,
|
||||||
|
message_id UUID NOT NULL,
|
||||||
|
scheduled_message_id UUID NOT NULL,
|
||||||
|
created timestamptz DEFAULT now()
|
||||||
|
)
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
package version
|
|
||||||
|
|
||||||
var (
|
|
||||||
Version = "dev"
|
|
||||||
Commit = "none"
|
|
||||||
Date = "unknown"
|
|
||||||
)
|
|
||||||
Reference in New Issue
Block a user