tsk-51: Send message endpoint (#52)
Closes #51 Reviewed-on: phoenix/textsender-api#52 Co-authored-by: phoenix <kundeng00@pm.me> Co-committed-by: phoenix <kundeng00@pm.me>
This commit is contained in:
@@ -5,3 +5,7 @@ DB_PASSWORD=password
|
||||
DB_HOST=main_db
|
||||
DB_PORT=5432
|
||||
DB_SSLMODE=disable
|
||||
TWILIO_AUTH_SID=9M438C93R943U4329MCU43C34U
|
||||
TWILIO_SERVICE_SID=9M4J3X8439U398NUVT3342MC349C348T
|
||||
TWILIO_AUTH_TOKEN="f4a1f2b0b79ea3735078c2d8ee9684e1"
|
||||
TWILIO_PHONE_NUMBER=+10123456789
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
JWT_SECRET=NULqYIzgt28bTiyziCd7IOO7b6LnWDW!
|
||||
DB_NAME=textsender_db
|
||||
DB_USER=textsender
|
||||
DB_PASSWORD=password
|
||||
DB_HOST=localhost
|
||||
DB_PORT=5432
|
||||
DB_SSLMODE=disable
|
||||
TWILIO_AUTH_SID=9M438C93R943U4329MCU43C34U
|
||||
TWILIO_SERVICE_SID=9M4J3X8439U398NUVT3342MC349C348T
|
||||
TWILIO_AUTH_TOKEN="f4a1f2b0b79ea3735078c2d8ee9684e1"
|
||||
TWILIO_PHONE_NUMBER=+10123456789
|
||||
@@ -1,7 +0,0 @@
|
||||
JWT_SECRET=NULqYIzgt28bTiyziCd7IOO7b6LnWDW!
|
||||
DB_NAME=textsender_db
|
||||
DB_USER=textsender
|
||||
DB_PASSWORD=password
|
||||
DB_HOST=localhost
|
||||
DB_PORT=5432
|
||||
DB_SSLMODE=disable
|
||||
@@ -103,6 +103,10 @@ jobs:
|
||||
echo "DB_HOST=$DB_HOST" >> .env
|
||||
echo "DB_PORT=$DB_PORT" >> .env
|
||||
echo "DB_SSLMODE=$DB_SSLMODE" >> .env
|
||||
echo "TWILIO_AUTH_SID=9M438C93R943U4329MCU43C34U" >> .env
|
||||
echo "TWILIO_SERVICE_SID=9M4J3X8439U398NUVT3342MC349C348T" >> .env
|
||||
echo "TWILIO_AUTH_TOKEN=f4a1f2b0b79ea3735078c2d8ee9684e1" >> .env
|
||||
echo "TWILIO_PHONE_NUMBER=10123456789" >> .env
|
||||
|
||||
echo "Initializing config"
|
||||
mkdir -p ~/.ssh
|
||||
|
||||
+23
-19
@@ -15,6 +15,7 @@ import (
|
||||
"github.com/swaggo/http-swagger/v2"
|
||||
|
||||
_ "git.kundeng.us/phoenix/textsender-api/docs"
|
||||
"git.kundeng.us/phoenix/textsender-api/internal/app"
|
||||
"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"
|
||||
@@ -36,18 +37,20 @@ import (
|
||||
// @name Authorization
|
||||
// @description JWT Bearer Token
|
||||
func main() {
|
||||
cfg := config.Load()
|
||||
if cfg == nil {
|
||||
fmt.Println("Error initializing config")
|
||||
os.Exit(-1)
|
||||
cfg, tCfg, err := config.Load()
|
||||
if err != nil {
|
||||
log.Fatal("Error:", err)
|
||||
} else if cfg == nil {
|
||||
log.Fatal("Error initializing config")
|
||||
} else if cfg.JWTSecret == "" {
|
||||
fmt.Println("Error: JWTSecret not initialized")
|
||||
os.Exit(-1)
|
||||
log.Fatal("Error: JWTSecret not initialized")
|
||||
}
|
||||
|
||||
apiApp := app.App{TwilioConfig: tCfg}
|
||||
|
||||
db, err := database.NewDatabase(cfg.GetDBConnString())
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to connect to database: %v", err)
|
||||
log.Fatal("Failed to connect to database:", err)
|
||||
}
|
||||
defer db.Close()
|
||||
|
||||
@@ -56,19 +59,18 @@ func main() {
|
||||
if cfg.ResetDB {
|
||||
log.Println("Resetting database")
|
||||
if err := db.ResetDatabase(ctx); err != nil {
|
||||
log.Fatalf("Failed to reset database: %v", err)
|
||||
log.Fatal("Failed to reset database:", 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)
|
||||
log.Println("Resetting database")
|
||||
if err = db.ResetDatabase(ctx); err != nil {
|
||||
log.Fatal("Error:", err)
|
||||
}
|
||||
} else {
|
||||
fmt.Printf("Error:%v", err)
|
||||
log.Fatal("Error:", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -80,12 +82,13 @@ func main() {
|
||||
schMsgEventStore := store.NewScheduledMessageEventStore(db.Pool)
|
||||
merStore := store.NewMessageEventResponseStore(db.Pool)
|
||||
|
||||
contactHandler := handler.NewContactHandler(contactStore)
|
||||
messageHandler := handler.NewMessageHandler(messageStore)
|
||||
scheduledMessageHandler := handler.NewScheduledMessageHandler(schStore)
|
||||
scheduledMessageEventHandler := handler.NewScheduledMessageEventHandler(schMsgEventStore, schStore)
|
||||
scheduledMessageStatusHandler := handler.NewScheduledMessageStatusHandler(schMsgEventStore, schStore)
|
||||
eventHandler := handler.NewEventResponseHandler(merStore)
|
||||
contactHandler := handler.NewContactHandler(&apiApp, contactStore)
|
||||
messageHandler := handler.NewMessageHandler(&apiApp, messageStore)
|
||||
scheduledMessageHandler := handler.NewScheduledMessageHandler(&apiApp, schStore)
|
||||
scheduledMessageEventHandler := handler.NewScheduledMessageEventHandler(&apiApp, schMsgEventStore, schStore)
|
||||
scheduledMessageStatusHandler := handler.NewScheduledMessageStatusHandler(&apiApp, schMsgEventStore, schStore)
|
||||
eventHandler := handler.NewEventResponseHandler(&apiApp, merStore)
|
||||
instantMessageHandler := handler.NewSendInstantMessageHandler(&apiApp, merStore, contactStore, messageStore)
|
||||
|
||||
router := chi.NewRouter()
|
||||
|
||||
@@ -106,6 +109,7 @@ func main() {
|
||||
router.Method("GET", endpoint.GetScheduledMessageEndpoint, mdlware.AuthMiddleware(jwtService)(http.HandlerFunc(scheduledMessageHandler.GetScheduledMessage)))
|
||||
router.Method("GET", endpoint.FetchNextScheduledMessageEndpoint, mdlware.AuthMiddleware(jwtService)(http.HandlerFunc(scheduledMessageHandler.FetchNextMessage)))
|
||||
router.Method("POST", endpoint.RecordEventResponse, mdlware.AuthMiddleware(jwtService)(http.HandlerFunc(eventHandler.RecordResponse)))
|
||||
router.Method("POST", endpoint.SendInstantMessageEndpoint, mdlware.AuthMiddleware(jwtService)(http.HandlerFunc(instantMessageHandler.Send)))
|
||||
|
||||
router.Method("GET", "/swagger/*", httpSwagger.Handler(
|
||||
httpSwagger.URL(fmt.Sprintf("http://localhost:%s/swagger/doc.json", config.PORT)),
|
||||
|
||||
+19
-12
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"path"
|
||||
@@ -12,6 +13,7 @@ import (
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/joho/godotenv"
|
||||
|
||||
"git.kundeng.us/phoenix/textsender-api/internal/app"
|
||||
"git.kundeng.us/phoenix/textsender-api/internal/config"
|
||||
"git.kundeng.us/phoenix/textsender-api/internal/db"
|
||||
"git.kundeng.us/phoenix/textsender-api/internal/handler"
|
||||
@@ -24,7 +26,7 @@ import (
|
||||
var testRouter *chi.Mux
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
cfg := load()
|
||||
cfg, apiApp := load()
|
||||
|
||||
database, err := db.NewDatabase(cfg.GetDBConnString())
|
||||
if err != nil {
|
||||
@@ -60,12 +62,12 @@ func TestMain(m *testing.M) {
|
||||
schMsgEventStore := store.NewScheduledMessageEventStore(db.Pool)
|
||||
merStore := store.NewMessageEventResponseStore(db.Pool)
|
||||
|
||||
contactHandler := handler.NewContactHandler(contactStore)
|
||||
messageHandler := handler.NewMessageHandler(messageStore)
|
||||
scheduledMessageHandler := handler.NewScheduledMessageHandler(schStore)
|
||||
scheduledMessageEventHandler := handler.NewScheduledMessageEventHandler(schMsgEventStore, schStore)
|
||||
scheduledMessageStatusHandler := handler.NewScheduledMessageStatusHandler(schMsgEventStore, schStore)
|
||||
eventHandler := handler.NewEventResponseHandler(merStore)
|
||||
contactHandler := handler.NewContactHandler(apiApp, contactStore)
|
||||
messageHandler := handler.NewMessageHandler(apiApp, messageStore)
|
||||
scheduledMessageHandler := handler.NewScheduledMessageHandler(apiApp, schStore)
|
||||
scheduledMessageEventHandler := handler.NewScheduledMessageEventHandler(apiApp, schMsgEventStore, schStore)
|
||||
scheduledMessageStatusHandler := handler.NewScheduledMessageStatusHandler(apiApp, schMsgEventStore, schStore)
|
||||
eventHandler := handler.NewEventResponseHandler(apiApp, merStore)
|
||||
|
||||
testRouter = chi.NewRouter()
|
||||
testRouter.Handle(endpoint.ADD_CONTACT_ENDPOINT, mdlware.AuthMiddleware(jwtService)(http.HandlerFunc(contactHandler.AddContact)))
|
||||
@@ -84,7 +86,7 @@ func TestMain(m *testing.M) {
|
||||
os.Exit(code)
|
||||
}
|
||||
|
||||
func load() *config.Config {
|
||||
func load() (*config.Config, *app.App) {
|
||||
resetDb := flag.Bool("reset-db", false, "Reset the database schema and exit")
|
||||
port := flag.String("port", config.PORT, "Server port")
|
||||
flag.Parse()
|
||||
@@ -103,10 +105,15 @@ func load() *config.Config {
|
||||
unpackedConnString := config.UnpackDBConnString()
|
||||
dbConnString := unpackedConnString.Parse()
|
||||
|
||||
return &config.Config{
|
||||
DBConnString: dbConnString,
|
||||
ServerPort: *port,
|
||||
ResetDB: *resetDb,
|
||||
if tCfg, err := config.TwilioConfig(); err != nil {
|
||||
log.Fatal("Error: ", err)
|
||||
return nil, nil
|
||||
} else {
|
||||
return &config.Config{
|
||||
DBConnString: dbConnString,
|
||||
ServerPort: *port,
|
||||
ResetDB: *resetDb,
|
||||
}, &app.App{TwilioConfig: tCfg}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+105
@@ -122,6 +122,57 @@ const docTemplate = `{
|
||||
}
|
||||
}
|
||||
},
|
||||
"/instant/message": {
|
||||
"post": {
|
||||
"security": [
|
||||
{
|
||||
"BearerAuth": []
|
||||
}
|
||||
],
|
||||
"description": "Send a message without the constraints of scheduled messages (requires JWT)",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"messages"
|
||||
],
|
||||
"summary": "Send instant message",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "Send an instnt message",
|
||||
"name": "request",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/handler.SendInstantMessageRequest"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"201": {
|
||||
"description": "Created",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/handler.SendInstantMessageResponse"
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/handler.SendInstantMessageResponse"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/handler.SendInstantMessageResponse"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/message": {
|
||||
"get": {
|
||||
"security": [
|
||||
@@ -828,6 +879,37 @@ const docTemplate = `{
|
||||
}
|
||||
}
|
||||
},
|
||||
"handler.SendInstantMessageRequest": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"contact_ids": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"message_id": {
|
||||
"type": "string"
|
||||
},
|
||||
"user_id": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"handler.SendInstantMessageResponse": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"data": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/message.MessageEventResponse"
|
||||
}
|
||||
},
|
||||
"message": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"message.Message": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -842,6 +924,29 @@ const docTemplate = `{
|
||||
}
|
||||
}
|
||||
},
|
||||
"message.MessageEventResponse": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string"
|
||||
},
|
||||
"response": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "integer"
|
||||
}
|
||||
},
|
||||
"scheduled_message_event_id": {
|
||||
"type": "string"
|
||||
},
|
||||
"sent": {
|
||||
"type": "string"
|
||||
},
|
||||
"user_id": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"scheduling.ScheduledMessage": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
|
||||
@@ -116,6 +116,57 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/instant/message": {
|
||||
"post": {
|
||||
"security": [
|
||||
{
|
||||
"BearerAuth": []
|
||||
}
|
||||
],
|
||||
"description": "Send a message without the constraints of scheduled messages (requires JWT)",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"messages"
|
||||
],
|
||||
"summary": "Send instant message",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "Send an instnt message",
|
||||
"name": "request",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/handler.SendInstantMessageRequest"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"201": {
|
||||
"description": "Created",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/handler.SendInstantMessageResponse"
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/handler.SendInstantMessageResponse"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/handler.SendInstantMessageResponse"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/message": {
|
||||
"get": {
|
||||
"security": [
|
||||
@@ -822,6 +873,37 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"handler.SendInstantMessageRequest": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"contact_ids": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"message_id": {
|
||||
"type": "string"
|
||||
},
|
||||
"user_id": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"handler.SendInstantMessageResponse": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"data": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/message.MessageEventResponse"
|
||||
}
|
||||
},
|
||||
"message": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"message.Message": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -836,6 +918,29 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"message.MessageEventResponse": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string"
|
||||
},
|
||||
"response": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "integer"
|
||||
}
|
||||
},
|
||||
"scheduled_message_event_id": {
|
||||
"type": "string"
|
||||
},
|
||||
"sent": {
|
||||
"type": "string"
|
||||
},
|
||||
"user_id": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"scheduling.ScheduledMessage": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
|
||||
@@ -154,6 +154,26 @@ definitions:
|
||||
message:
|
||||
type: string
|
||||
type: object
|
||||
handler.SendInstantMessageRequest:
|
||||
properties:
|
||||
contact_ids:
|
||||
items:
|
||||
type: string
|
||||
type: array
|
||||
message_id:
|
||||
type: string
|
||||
user_id:
|
||||
type: string
|
||||
type: object
|
||||
handler.SendInstantMessageResponse:
|
||||
properties:
|
||||
data:
|
||||
items:
|
||||
$ref: '#/definitions/message.MessageEventResponse'
|
||||
type: array
|
||||
message:
|
||||
type: string
|
||||
type: object
|
||||
message.Message:
|
||||
properties:
|
||||
content:
|
||||
@@ -163,6 +183,21 @@ definitions:
|
||||
user_id:
|
||||
type: string
|
||||
type: object
|
||||
message.MessageEventResponse:
|
||||
properties:
|
||||
id:
|
||||
type: string
|
||||
response:
|
||||
items:
|
||||
type: integer
|
||||
type: array
|
||||
scheduled_message_event_id:
|
||||
type: string
|
||||
sent:
|
||||
type: string
|
||||
user_id:
|
||||
type: string
|
||||
type: object
|
||||
scheduling.ScheduledMessage:
|
||||
properties:
|
||||
created:
|
||||
@@ -266,6 +301,39 @@ paths:
|
||||
summary: Add contact
|
||||
tags:
|
||||
- contacts
|
||||
/instant/message:
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Send a message without the constraints of scheduled messages (requires
|
||||
JWT)
|
||||
parameters:
|
||||
- description: Send an instnt message
|
||||
in: body
|
||||
name: request
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/handler.SendInstantMessageRequest'
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"201":
|
||||
description: Created
|
||||
schema:
|
||||
$ref: '#/definitions/handler.SendInstantMessageResponse'
|
||||
"400":
|
||||
description: Bad Request
|
||||
schema:
|
||||
$ref: '#/definitions/handler.SendInstantMessageResponse'
|
||||
"500":
|
||||
description: Internal Server Error
|
||||
schema:
|
||||
$ref: '#/definitions/handler.SendInstantMessageResponse'
|
||||
security:
|
||||
- BearerAuth: []
|
||||
summary: Send instant message
|
||||
tags:
|
||||
- messages
|
||||
/message:
|
||||
get:
|
||||
consumes:
|
||||
|
||||
@@ -3,6 +3,7 @@ module git.kundeng.us/phoenix/textsender-api
|
||||
go 1.25.4
|
||||
|
||||
require (
|
||||
git.kundeng.us/phoenix/swoosh v0.0.7
|
||||
git.kundeng.us/phoenix/textsender-models v0.0.11
|
||||
github.com/go-chi/chi/v5 v5.2.3
|
||||
github.com/golang-jwt/jwt/v5 v5.3.0
|
||||
@@ -27,13 +28,15 @@ require (
|
||||
github.com/go-openapi/swag/stringutils v0.25.4 // indirect
|
||||
github.com/go-openapi/swag/typeutils v0.25.4 // indirect
|
||||
github.com/go-openapi/swag/yamlutils v0.25.4 // indirect
|
||||
github.com/golang/mock v1.6.0 // indirect
|
||||
github.com/google/go-cmp v0.7.0 // 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/pkg/errors v0.9.1 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||
github.com/swaggo/files/v2 v2.0.2 // indirect
|
||||
github.com/twilio/twilio-go v1.28.8 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.4 // indirect
|
||||
golang.org/x/crypto v0.45.0 // indirect
|
||||
golang.org/x/mod v0.30.0 // indirect
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
git.kundeng.us/phoenix/swoosh v0.0.7 h1:9M42tgKr6o34YOiwds7offvjCUoFzYN2B5TrFKbefFo=
|
||||
git.kundeng.us/phoenix/swoosh v0.0.7/go.mod h1:9iXlBd7UCMA7/jj8gZ1CxEfBualsClpiJrqGj8Fo2Xw=
|
||||
git.kundeng.us/phoenix/textsender-models v0.0.11 h1:kd2FdeZJhJJAXBm8MoyadtgNGyzC+puU1oR8B8N+MfE=
|
||||
git.kundeng.us/phoenix/textsender-models v0.0.11/go.mod h1:9iPDQJg1Tc6WMNoW5+f8YKmnosMwlWHJ++hmxNLDEe0=
|
||||
github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc=
|
||||
github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE=
|
||||
github.com/beevik/etree v1.1.0/go.mod h1:r8Aw8JqVegEf0w2fDnATrX9VpkMcyFeM0FhwO62wh+A=
|
||||
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=
|
||||
@@ -35,8 +38,11 @@ github.com/go-openapi/testify/enable/yaml/v2 v2.0.2 h1:0+Y41Pz1NkbTHz8NngxTuAXxE
|
||||
github.com/go-openapi/testify/enable/yaml/v2 v2.0.2/go.mod h1:kme83333GCtJQHXQ8UKX3IBZu6z8T5Dvy5+CW3NLUUg=
|
||||
github.com/go-openapi/testify/v2 v2.0.2 h1:X999g3jeLcoY8qctY/c/Z8iBHTbwLz7R2WXd6Ub6wls=
|
||||
github.com/go-openapi/testify/v2 v2.0.2/go.mod h1:HCPmvFFnheKK2BuwSA0TbbdxJ3I16pjwMkYkP4Ywn54=
|
||||
github.com/golang-jwt/jwt/v5 v5.2.2/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
|
||||
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/golang/mock v1.6.0 h1:ErTB+efbowRARo13NNdxyJji2egdxLGQhRaY+DUumQc=
|
||||
github.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
@@ -53,8 +59,15 @@ 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/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/localtunnel/go-localtunnel v0.0.0-20170326223115-8a804488f275 h1:IZycmTpoUtQK3PD60UYBwjaCUHUP7cML494ao9/O8+Q=
|
||||
github.com/localtunnel/go-localtunnel v0.0.0-20170326223115-8a804488f275/go.mod h1:zt6UU74K6Z6oMOYJbJzYpYucqdcQwSMPBEdSvGiaUMw=
|
||||
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
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=
|
||||
@@ -70,19 +83,45 @@ github.com/swaggo/http-swagger/v2 v2.0.2 h1:FKCdLsl+sFCx60KFsyM0rDarwiUSZ8DqbfSy
|
||||
github.com/swaggo/http-swagger/v2 v2.0.2/go.mod h1:r7/GBkAWIfK6E/OLnE8fXnviHiDeAHmgIyooa4xm3AQ=
|
||||
github.com/swaggo/swag v1.16.6 h1:qBNcx53ZaX+M5dxVyTrgQ0PJ/ACK+NzhwcbieTt+9yI=
|
||||
github.com/swaggo/swag v1.16.6/go.mod h1:ngP2etMK5a0P3QBizic5MEwpRmluJZPHjXcMoj4Xesg=
|
||||
github.com/twilio/twilio-go v1.28.8 h1:wbFz7Wt4S5mCEaes6FcM/ddcJGIhdjwp/9CHb9e+4fk=
|
||||
github.com/twilio/twilio-go v1.28.8/go.mod h1:FpgNWMoD8CFnmukpKq9RNpUSGXC0BwnbeKZj2YHlIkw=
|
||||
github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
|
||||
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
|
||||
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q=
|
||||
golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4=
|
||||
golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||
golang.org/x/mod v0.30.0 h1:fDEXFVZ/fmCKProc/yAXXUijritrDzahmwwefnjoPFk=
|
||||
golang.org/x/mod v0.30.0/go.mod h1:lAsf5O2EvJeSFMiBxXDki7sCgAxEUcZHXoXMKT4GJKc=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.18.0 h1:kr88TuHDroi+UVf+0hZnirlk8o8T+4MrK6mr60WkH/I=
|
||||
golang.org/x/sync v0.18.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM=
|
||||
golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
|
||||
golang.org/x/tools v0.39.0 h1:ik4ho21kwuQln40uelmciQPp9SipgNDdrafrYA4TmQQ=
|
||||
golang.org/x/tools v0.39.0/go.mod h1:JnefbkDPyD8UU2kI5fuf8ZX4/yUeh9W877ZeBONxUqQ=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/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=
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"git.kundeng.us/phoenix/textsender-models/tx0/config"
|
||||
)
|
||||
|
||||
type App struct {
|
||||
TwilioConfig *config.TwiloConfig
|
||||
}
|
||||
+39
-10
@@ -3,10 +3,10 @@ package config
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"strconv"
|
||||
|
||||
"git.kundeng.us/phoenix/textsender-models/tx0/config"
|
||||
"github.com/joho/godotenv"
|
||||
|
||||
"git.kundeng.us/phoenix/textsender-api/internal/version"
|
||||
@@ -17,6 +17,7 @@ type Config struct {
|
||||
ServerPort string
|
||||
ResetDB bool
|
||||
JWTSecret string `env:"JWT_SECRET" required:"true"`
|
||||
TwilioConfig *config.TwiloConfig
|
||||
}
|
||||
|
||||
type ConnectionInfo struct {
|
||||
@@ -46,7 +47,7 @@ func PrintName() {
|
||||
fmt.Println(version.String())
|
||||
}
|
||||
|
||||
func Load() *Config {
|
||||
func Load() (*Config, *config.TwiloConfig, error) {
|
||||
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")
|
||||
@@ -57,19 +58,22 @@ func Load() *Config {
|
||||
os.Exit(-1)
|
||||
}
|
||||
|
||||
err := godotenv.Load()
|
||||
if err != nil {
|
||||
log.Fatal("Error loading .env file")
|
||||
if err := godotenv.Load(); err != nil {
|
||||
return nil, nil, fmt.Errorf("Error loading .env file")
|
||||
}
|
||||
|
||||
unpackedConnString := UnpackDBConnString()
|
||||
dbConnString := unpackedConnString.Parse()
|
||||
|
||||
return &Config{
|
||||
DBConnString: dbConnString,
|
||||
ServerPort: *port,
|
||||
ResetDB: *resetDb,
|
||||
JWTSecret: os.Getenv("JWT_SECRET"),
|
||||
if cfg, err := TwilioConfig(); err != nil {
|
||||
return nil, nil, err
|
||||
} else {
|
||||
return &Config{
|
||||
DBConnString: dbConnString,
|
||||
ServerPort: *port,
|
||||
ResetDB: *resetDb,
|
||||
JWTSecret: os.Getenv("JWT_SECRET"),
|
||||
}, cfg, nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -124,6 +128,31 @@ func UnpackDBConnString() (connInfo ConnectionInfo) {
|
||||
return
|
||||
}
|
||||
|
||||
func TwilioConfig() (*config.TwiloConfig, error) {
|
||||
authSid := os.Getenv("TWILIO_AUTH_SID")
|
||||
serviceSid := os.Getenv("TWILIO_SERVICE_SID")
|
||||
authToken := os.Getenv("TWILIO_AUTH_TOKEN")
|
||||
phoneNumber := os.Getenv("TWILIO_PHONE_NUMBER")
|
||||
|
||||
if len(authSid) == 0 {
|
||||
return nil, fmt.Errorf("Twilio config account sid not found")
|
||||
} else if len(serviceSid) == 0 {
|
||||
return nil, fmt.Errorf("Twilio config service sid not found")
|
||||
} else if len(authToken) == 0 {
|
||||
return nil, fmt.Errorf("Twilio config auth token not found")
|
||||
} else if len(phoneNumber) == 0 {
|
||||
return nil, fmt.Errorf("Twilio config phone number not found")
|
||||
} else {
|
||||
var cfg config.TwiloConfig
|
||||
cfg.AccountSID = authSid
|
||||
cfg.ServiceSID = serviceSid
|
||||
cfg.AuthToken = authToken
|
||||
cfg.Number = phoneNumber
|
||||
|
||||
return &cfg, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Config) GetDBConnString() string {
|
||||
return c.DBConnString
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"git.kundeng.us/phoenix/textsender-models/tx0/contact"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"git.kundeng.us/phoenix/textsender-api/internal/app"
|
||||
"git.kundeng.us/phoenix/textsender-api/internal/store"
|
||||
)
|
||||
|
||||
@@ -21,11 +22,12 @@ type AddContactResponse struct {
|
||||
}
|
||||
|
||||
type ContactHandler struct {
|
||||
App *app.App
|
||||
ContactStore store.ContactStore
|
||||
}
|
||||
|
||||
func NewContactHandler(str store.ContactStore) *ContactHandler {
|
||||
return &ContactHandler{ContactStore: str}
|
||||
func NewContactHandler(apiApp *app.App, str store.ContactStore) *ContactHandler {
|
||||
return &ContactHandler{App: apiApp, ContactStore: str}
|
||||
}
|
||||
|
||||
// AddContact godoc
|
||||
|
||||
@@ -25,7 +25,10 @@ type Request struct {
|
||||
|
||||
func TestCreateContactWithMock(t *testing.T) {
|
||||
mockstore := mock.NewMockContactStore()
|
||||
handler := NewContactHandler(mockstore)
|
||||
apiApp, err := GetApp()
|
||||
assert.NoError(t, err, "Error getting app")
|
||||
|
||||
handler := NewContactHandler(apiApp, mockstore)
|
||||
|
||||
testUserId := uuid.New()
|
||||
testBody := Request{PhoneNumber: "+12335403383", UserId: testUserId}
|
||||
@@ -39,7 +42,7 @@ func TestCreateContactWithMock(t *testing.T) {
|
||||
assert.Equal(t, http.StatusCreated, rr.Code)
|
||||
|
||||
var response AddContactResponse
|
||||
err := json.Unmarshal(rr.Body.Bytes(), &response)
|
||||
err = json.Unmarshal(rr.Body.Bytes(), &response)
|
||||
assert.NoError(t, err, "Error Creating contact %v", err)
|
||||
|
||||
assert.NotEmpty(t, response.Data, "No Contact created")
|
||||
@@ -62,13 +65,15 @@ func TestGetContactWithMock(t *testing.T) {
|
||||
req, _ := http.NewRequest("GET", url, nil)
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
contactHandler := NewContactHandler(mockstore)
|
||||
apiApp, err := GetApp()
|
||||
assert.NoError(t, err, "Error getting app")
|
||||
contactHandler := NewContactHandler(apiApp, mockstore)
|
||||
contactHandler.GetContact(rr, req)
|
||||
|
||||
assert.Equal(t, http.StatusOK, rr.Code)
|
||||
|
||||
var response GetContactResponse
|
||||
err := json.Unmarshal(rr.Body.Bytes(), &response)
|
||||
err = json.Unmarshal(rr.Body.Bytes(), &response)
|
||||
assert.NoError(t, err, "Error getting contact %v", err)
|
||||
|
||||
assert.NotEmpty(t, response.Data, "No Contact retrieved")
|
||||
|
||||
@@ -13,3 +13,4 @@ const DeleteScheduledMessageEventEndpoint = "/api/v1/schedule/message/event/{id}
|
||||
const UpdateScheduledMessageStatusEndpoint = "/api/v1/schedule/message/status/update"
|
||||
const FetchNextScheduledMessageEndpoint = "/api/v1/schedule/message/fetch"
|
||||
const RecordEventResponse = "/api/v1/schedule/message/event/response/record"
|
||||
const SendInstantMessageEndpoint = "/api/v1/instant/message"
|
||||
|
||||
@@ -16,7 +16,12 @@ func ExtractFromRequest(r *http.Request, reqItem interface{}) error {
|
||||
}
|
||||
}
|
||||
|
||||
func InvalidJson(err error) string {
|
||||
return fmt.Sprintf("Invalid JSON: %s", err.Error())
|
||||
}
|
||||
|
||||
// Helper function to send JSON responses
|
||||
// TODO: Change type of data to any
|
||||
func RespondWithJSON(w http.ResponseWriter, statusCode int, data interface{}) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(statusCode)
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path"
|
||||
|
||||
"github.com/joho/godotenv"
|
||||
|
||||
"git.kundeng.us/phoenix/textsender-api/internal/app"
|
||||
"git.kundeng.us/phoenix/textsender-api/internal/config"
|
||||
)
|
||||
|
||||
func GetApp() (*app.App, error) {
|
||||
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())
|
||||
}
|
||||
}
|
||||
|
||||
if tCfg, err := config.TwilioConfig(); err != nil {
|
||||
return nil, fmt.Errorf("Error: %v", err)
|
||||
} else {
|
||||
return &app.App{TwilioConfig: tCfg}, nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.kundeng.us/phoenix/swoosh/swoop/send"
|
||||
"git.kundeng.us/phoenix/textsender-models/tx0/contact"
|
||||
"git.kundeng.us/phoenix/textsender-models/tx0/message"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"git.kundeng.us/phoenix/textsender-api/internal/app"
|
||||
"git.kundeng.us/phoenix/textsender-api/internal/store"
|
||||
)
|
||||
|
||||
const Contact_Limit = 400
|
||||
|
||||
type SendInstantMessageHandler struct {
|
||||
App *app.App
|
||||
MERStore store.MessageEventResponseStore
|
||||
ContactStore store.ContactStore
|
||||
MessageStore store.MessageStore
|
||||
}
|
||||
|
||||
func NewSendInstantMessageHandler(apiApp *app.App, str store.MessageEventResponseStore, cStore store.ContactStore, mStore store.MessageStore) *SendInstantMessageHandler {
|
||||
return &SendInstantMessageHandler{App: apiApp, MERStore: str, ContactStore: cStore, MessageStore: mStore}
|
||||
}
|
||||
|
||||
type SendInstantMessageRequest struct {
|
||||
ContactIds []uuid.UUID `json:"contact_ids"`
|
||||
MessageId uuid.UUID `json:"message_id"`
|
||||
UserId uuid.UUID `json:"user_id"`
|
||||
}
|
||||
|
||||
type SendInstantMessageResponse struct {
|
||||
Message string `json:"message"`
|
||||
Data []*message.MessageEventResponse `json:"data"`
|
||||
}
|
||||
|
||||
// Sent godoc
|
||||
// @Summary Send instant message
|
||||
// @Description Send a message without the constraints of scheduled messages (requires JWT)
|
||||
// @Tags messages
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param request body SendInstantMessageRequest true "Send an instnt message"
|
||||
// @Success 201 {object} SendInstantMessageResponse
|
||||
// @Failure 400 {object} SendInstantMessageResponse
|
||||
// @Failure 500 {object} SendInstantMessageResponse
|
||||
// @Router /instant/message [post]
|
||||
func (s *SendInstantMessageHandler) Send(w http.ResponseWriter, r *http.Request) {
|
||||
var req SendInstantMessageRequest
|
||||
if err := ExtractFromRequest(r, &req); err != nil {
|
||||
http.Error(w, InvalidJson(err), http.StatusBadRequest)
|
||||
}
|
||||
defer r.Body.Close()
|
||||
|
||||
var statusCode int
|
||||
var resp SendInstantMessageResponse
|
||||
|
||||
if req.UserId == uuid.Nil {
|
||||
statusCode = http.StatusBadRequest
|
||||
resp.Message = "User Id is nil"
|
||||
} else if req.MessageId == uuid.Nil {
|
||||
statusCode = http.StatusBadRequest
|
||||
resp.Message = "Message Id is nil"
|
||||
} else if len(req.ContactIds) == 0 {
|
||||
statusCode = http.StatusBadRequest
|
||||
resp.Message = "No contacts provided"
|
||||
} else {
|
||||
if len(req.ContactIds) > Contact_Limit {
|
||||
statusCode = http.StatusBadRequest
|
||||
resp.Message = "Too many contacts"
|
||||
} else {
|
||||
ctx := r.Context()
|
||||
if msg, contacts, err := s.verify(ctx, &req); err != nil {
|
||||
statusCode = http.StatusInternalServerError
|
||||
resp.Message = err.Error()
|
||||
} else {
|
||||
if msg == nil {
|
||||
statusCode = http.StatusBadRequest
|
||||
resp.Message = "Message is empty"
|
||||
} else if len(contacts) == 0 {
|
||||
statusCode = http.StatusBadRequest
|
||||
resp.Message = "Contacts not found"
|
||||
} else {
|
||||
if s.App != nil {
|
||||
msgSender := send.MessageSender{Config: s.App.TwilioConfig}
|
||||
for _, c := range contacts {
|
||||
if twilioResp, err := msgSender.Send(*msg, *c, nil); err != nil {
|
||||
statusCode = http.StatusInternalServerError
|
||||
resp.Message = err.Error()
|
||||
} else {
|
||||
if data, err := json.Marshal(twilioResp); err != nil {
|
||||
statusCode = http.StatusInternalServerError
|
||||
resp.Message = err.Error()
|
||||
} else {
|
||||
dateStr := strings.TrimSpace(*twilioResp.DateUpdated)
|
||||
if parsedTime, err := time.Parse(time.RFC1123Z, dateStr); err != nil {
|
||||
statusCode = http.StatusInternalServerError
|
||||
resp.Message = err.Error()
|
||||
} else {
|
||||
mer := message.MessageEventResponse{}
|
||||
mer.Response = data
|
||||
mer.UserId = req.UserId
|
||||
mer.Sent = parsedTime
|
||||
if err := s.MERStore.Create(ctx, &mer); err != nil {
|
||||
statusCode = http.StatusInternalServerError
|
||||
resp.Message = err.Error()
|
||||
} else {
|
||||
statusCode = http.StatusOK
|
||||
resp.Message = "Successful"
|
||||
resp.Data = append(resp.Data, &mer)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
statusCode = http.StatusInternalServerError
|
||||
resp.Message = "Config not properly configured"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
RespondWithJSON(w, statusCode, &resp)
|
||||
}
|
||||
|
||||
func (s *SendInstantMessageHandler) verify(ctx context.Context, req *SendInstantMessageRequest) (*message.Message, []*contact.Contact, error) {
|
||||
if msg, err := s.verifyMessage(ctx, req.MessageId); err != nil {
|
||||
log.Println("Huh?")
|
||||
return nil, nil, fmt.Errorf("Error:%v", err)
|
||||
} else {
|
||||
log.Println("Okay")
|
||||
if msg != nil {
|
||||
if contacts, err := s.verifyContacts(ctx, req.ContactIds); err != nil {
|
||||
return nil, nil, fmt.Errorf("Error:%v", err)
|
||||
} else {
|
||||
if len(contacts) == 0 {
|
||||
return msg, nil, nil
|
||||
} else {
|
||||
return msg, contacts, nil
|
||||
}
|
||||
}
|
||||
} else {
|
||||
log.Println("How can this be?")
|
||||
return nil, nil, fmt.Errorf("Could not verify message")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *SendInstantMessageHandler) verifyMessage(ctx context.Context, messageId uuid.UUID) (*message.Message, error) {
|
||||
if msg, err := s.MessageStore.GetMessageByID(ctx, messageId); err != nil {
|
||||
return nil, fmt.Errorf("Error getting message:%v", err)
|
||||
} else {
|
||||
if msg == nil {
|
||||
log.Println("Message is nil")
|
||||
return nil, nil
|
||||
} else {
|
||||
return msg, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *SendInstantMessageHandler) verifyContacts(ctx context.Context, contactIds []uuid.UUID) ([]*contact.Contact, error) {
|
||||
var contacts []*contact.Contact
|
||||
|
||||
for _, contactId := range contactIds {
|
||||
if c, err := s.ContactStore.GetContactByID(ctx, contactId); err != nil {
|
||||
return nil, fmt.Errorf("Error getting contacts:%v", err)
|
||||
} else {
|
||||
if c != nil {
|
||||
contacts = append(contacts, c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(contacts) == 0 {
|
||||
return nil, nil
|
||||
} else {
|
||||
return contacts, nil
|
||||
}
|
||||
}
|
||||
@@ -2,11 +2,13 @@ package handler
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"git.kundeng.us/phoenix/textsender-models/tx0/message"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"git.kundeng.us/phoenix/textsender-api/internal/app"
|
||||
"git.kundeng.us/phoenix/textsender-api/internal/store"
|
||||
)
|
||||
|
||||
@@ -21,11 +23,12 @@ type AddMessageResponse struct {
|
||||
}
|
||||
|
||||
type MessageHandler struct {
|
||||
App *app.App
|
||||
MessageStore store.MessageStore
|
||||
}
|
||||
|
||||
func NewMessageHandler(str store.MessageStore) *MessageHandler {
|
||||
return &MessageHandler{MessageStore: str}
|
||||
func NewMessageHandler(apiApp *app.App, str store.MessageStore) *MessageHandler {
|
||||
return &MessageHandler{App: apiApp, MessageStore: str}
|
||||
}
|
||||
|
||||
const Message_Limit = 200
|
||||
@@ -143,7 +146,7 @@ func (c *MessageHandler) GetMessage(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
|
||||
if id != uuid.Nil {
|
||||
fmt.Println("Checking with Id")
|
||||
log.Println("Checking with Id")
|
||||
if con, err := c.MessageStore.GetMessageByID(ctx, id); err == nil {
|
||||
statusCode = http.StatusOK
|
||||
resp.Message = "Successful"
|
||||
@@ -153,8 +156,9 @@ func (c *MessageHandler) GetMessage(w http.ResponseWriter, r *http.Request) {
|
||||
resp.Message = err.Error()
|
||||
}
|
||||
} else if userId != uuid.Nil {
|
||||
fmt.Println("Checking with User Id")
|
||||
log.Println("Checking with User Id")
|
||||
if messages, err := c.MessageStore.GetAllMessages(ctx); err == nil {
|
||||
log.Println("Amount of messages:", len(messages))
|
||||
for _, msg := range messages {
|
||||
if msg.UserId == userId {
|
||||
resp.Data = append(resp.Data, *msg)
|
||||
|
||||
@@ -8,15 +8,17 @@ import (
|
||||
"git.kundeng.us/phoenix/textsender-models/tx0/types"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"git.kundeng.us/phoenix/textsender-api/internal/app"
|
||||
"git.kundeng.us/phoenix/textsender-api/internal/store"
|
||||
)
|
||||
|
||||
type EventResponseHandler struct {
|
||||
App *app.App
|
||||
MessageEventResponseStore store.MessageEventResponseStore
|
||||
}
|
||||
|
||||
func NewEventResponseHandler(str store.MessageEventResponseStore) *EventResponseHandler {
|
||||
return &EventResponseHandler{MessageEventResponseStore: str}
|
||||
func NewEventResponseHandler(apiApp *app.App, str store.MessageEventResponseStore) *EventResponseHandler {
|
||||
return &EventResponseHandler{App: apiApp, MessageEventResponseStore: str}
|
||||
}
|
||||
|
||||
type RecordEventRequest struct {
|
||||
|
||||
@@ -26,7 +26,9 @@ func TestRecordMessageEventResponseWithMock(t *testing.T) {
|
||||
schMsgStore := mock.NewMockScheduledMessageStore()
|
||||
merStore := mock.NewMockMessageEventResponseStore()
|
||||
|
||||
handler := NewEventResponseHandler(merStore)
|
||||
apiApp, err := GetApp()
|
||||
assert.NoError(t, err, "Error getting app")
|
||||
handler := NewEventResponseHandler(apiApp, merStore)
|
||||
|
||||
recipientId := uuid.New()
|
||||
messageId := uuid.New()
|
||||
@@ -69,7 +71,7 @@ func TestRecordMessageEventResponseWithMock(t *testing.T) {
|
||||
assert.Equal(t, http.StatusCreated, rr.Code)
|
||||
|
||||
var response RecordEventResponse
|
||||
err := json.Unmarshal(rr.Body.Bytes(), &response)
|
||||
err = json.Unmarshal(rr.Body.Bytes(), &response)
|
||||
assert.NoError(t, err, "Error parsing message event response:%v", err)
|
||||
|
||||
assert.NotEmpty(t, response.Data, "No message event response created")
|
||||
|
||||
@@ -23,7 +23,9 @@ type CreateMessageRequest struct {
|
||||
|
||||
func TestCreateMessageWithMock(t *testing.T) {
|
||||
mockStore := mock.NewMockMessageStore()
|
||||
handler := NewMessageHandler(mockStore)
|
||||
apiApp, err := GetApp()
|
||||
assert.NoError(t, err, "Error getting app")
|
||||
handler := NewMessageHandler(apiApp, mockStore)
|
||||
|
||||
testUserId := uuid.New()
|
||||
testBody := CreateMessageRequest{Content: "Who could tell?", UserId: testUserId}
|
||||
@@ -37,7 +39,7 @@ func TestCreateMessageWithMock(t *testing.T) {
|
||||
assert.Equal(t, http.StatusCreated, rr.Code)
|
||||
|
||||
var response AddMessageResponse
|
||||
err := json.Unmarshal(rr.Body.Bytes(), &response)
|
||||
err = json.Unmarshal(rr.Body.Bytes(), &response)
|
||||
assert.NoError(t, err, "Error Creating message %v", err)
|
||||
|
||||
assert.NotEmpty(t, response.Data, "No Message created")
|
||||
@@ -60,13 +62,15 @@ func TestGetMessageWithMock(t *testing.T) {
|
||||
req, _ := http.NewRequest("GET", url, nil)
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
messageHandler := NewMessageHandler(mockstore)
|
||||
apiApp, err := GetApp()
|
||||
assert.NoError(t, err, "Error getting app")
|
||||
messageHandler := NewMessageHandler(apiApp, mockstore)
|
||||
messageHandler.GetMessage(rr, req)
|
||||
|
||||
assert.Equal(t, http.StatusOK, rr.Code)
|
||||
|
||||
var response GetMessageResponse
|
||||
err := json.Unmarshal(rr.Body.Bytes(), &response)
|
||||
err = json.Unmarshal(rr.Body.Bytes(), &response)
|
||||
assert.NoError(t, err, "Error getting message %v", err)
|
||||
|
||||
assert.NotEmpty(t, response.Data, "No Message retrieved")
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"git.kundeng.us/phoenix/textsender-models/tx0/message/scheduling"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"git.kundeng.us/phoenix/textsender-api/internal/app"
|
||||
"git.kundeng.us/phoenix/textsender-api/internal/store"
|
||||
)
|
||||
|
||||
@@ -25,12 +26,13 @@ type ScheduledMessageStatusResponse struct {
|
||||
}
|
||||
|
||||
type ScheduledMessageStatusHandler struct {
|
||||
App *app.App
|
||||
ScheduledMessageEventStore store.ScheduledMessageEventStore
|
||||
ScheduledMessageStore store.ScheduledMessageStore
|
||||
}
|
||||
|
||||
func NewScheduledMessageStatusHandler(str store.ScheduledMessageEventStore, schStore store.ScheduledMessageStore) *ScheduledMessageStatusHandler {
|
||||
return &ScheduledMessageStatusHandler{ScheduledMessageEventStore: str, ScheduledMessageStore: schStore}
|
||||
func NewScheduledMessageStatusHandler(apiApp *app.App, str store.ScheduledMessageEventStore, schStore store.ScheduledMessageStore) *ScheduledMessageStatusHandler {
|
||||
return &ScheduledMessageStatusHandler{App: apiApp, ScheduledMessageEventStore: str, ScheduledMessageStore: schStore}
|
||||
}
|
||||
|
||||
// UpdateStatus godoc
|
||||
|
||||
@@ -55,13 +55,15 @@ func TestUpdateScheduledMessageStatusWithMock(t *testing.T) {
|
||||
req, _ := http.NewRequest("PATCH", endpoint.UpdateScheduledMessageStatusEndpoint, jsonBody)
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
handler := NewScheduledMessageStatusHandler(schMsgEventStore, schMsgStore)
|
||||
apiApp, err := GetApp()
|
||||
assert.NoError(t, err, "Error getting app")
|
||||
handler := NewScheduledMessageStatusHandler(apiApp, schMsgEventStore, schMsgStore)
|
||||
handler.UpdateStatus(rr, req)
|
||||
|
||||
assert.Equal(t, http.StatusOK, rr.Code)
|
||||
|
||||
var response ScheduledMessageStatusResponse
|
||||
err := json.Unmarshal(rr.Body.Bytes(), &response)
|
||||
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")
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"git.kundeng.us/phoenix/textsender-models/tx0/message/scheduling"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"git.kundeng.us/phoenix/textsender-api/internal/app"
|
||||
"git.kundeng.us/phoenix/textsender-api/internal/store"
|
||||
)
|
||||
|
||||
@@ -34,11 +35,12 @@ type FetchNextMessageResponse struct {
|
||||
}
|
||||
|
||||
type ScheduledMessageHandler struct {
|
||||
App *app.App
|
||||
ScheduledMessageStore store.ScheduledMessageStore
|
||||
}
|
||||
|
||||
func NewScheduledMessageHandler(str store.ScheduledMessageStore) *ScheduledMessageHandler {
|
||||
return &ScheduledMessageHandler{ScheduledMessageStore: str}
|
||||
func NewScheduledMessageHandler(apiApp *app.App, str store.ScheduledMessageStore) *ScheduledMessageHandler {
|
||||
return &ScheduledMessageHandler{App: apiApp, ScheduledMessageStore: str}
|
||||
}
|
||||
|
||||
// AddScheduledMessage godoc
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"git.kundeng.us/phoenix/textsender-api/internal/app"
|
||||
"git.kundeng.us/phoenix/textsender-api/internal/store"
|
||||
)
|
||||
|
||||
@@ -33,12 +34,13 @@ type DeleteScheduledMessageEventResponse struct {
|
||||
}
|
||||
|
||||
type ScheduledMessageEventHandler struct {
|
||||
App *app.App
|
||||
ScheduledMessageEventStore store.ScheduledMessageEventStore
|
||||
ScheduledMessageStore store.ScheduledMessageStore
|
||||
}
|
||||
|
||||
func NewScheduledMessageEventHandler(str store.ScheduledMessageEventStore, schStore store.ScheduledMessageStore) *ScheduledMessageEventHandler {
|
||||
return &ScheduledMessageEventHandler{ScheduledMessageEventStore: str, ScheduledMessageStore: schStore}
|
||||
func NewScheduledMessageEventHandler(apiApp *app.App, str store.ScheduledMessageEventStore, schStore store.ScheduledMessageStore) *ScheduledMessageEventHandler {
|
||||
return &ScheduledMessageEventHandler{App: apiApp, ScheduledMessageEventStore: str, ScheduledMessageStore: schStore}
|
||||
}
|
||||
|
||||
// AddContact godoc
|
||||
|
||||
@@ -40,7 +40,9 @@ func TestCreateScheduledMessageEventWithMock(t *testing.T) {
|
||||
messageStore := mock.NewMockMessageStore()
|
||||
schMsgStore := mock.NewMockScheduledMessageStore()
|
||||
|
||||
handler := NewScheduledMessageEventHandler(mockStore, schMsgStore)
|
||||
apiApp, err := GetApp()
|
||||
assert.NoError(t, err, "Error getting app")
|
||||
handler := NewScheduledMessageEventHandler(apiApp, mockStore, schMsgStore)
|
||||
|
||||
recipientId := uuid.New()
|
||||
messageId := uuid.New()
|
||||
@@ -72,7 +74,7 @@ func TestCreateScheduledMessageEventWithMock(t *testing.T) {
|
||||
assert.Equal(t, http.StatusCreated, rr.Code)
|
||||
|
||||
var response AddScheduledMessageEventResponse
|
||||
err := json.Unmarshal(rr.Body.Bytes(), &response)
|
||||
err = json.Unmarshal(rr.Body.Bytes(), &response)
|
||||
assert.NoError(t, err, "Error creating event %v", err)
|
||||
|
||||
assert.NotEmpty(t, response.Data, "No event created")
|
||||
@@ -90,7 +92,9 @@ func TestGetScheduledMessageEventWithMock(t *testing.T) {
|
||||
messageStore := mock.NewMockMessageStore()
|
||||
schMsgStore := mock.NewMockScheduledMessageStore()
|
||||
schMsgEventStore := mock.NewMockScheduledMessageEventStore()
|
||||
handler := NewScheduledMessageEventHandler(schMsgEventStore, schMsgStore)
|
||||
apiApp, err := GetApp()
|
||||
assert.NoError(t, err, "Error getting app")
|
||||
handler := NewScheduledMessageEventHandler(apiApp, schMsgEventStore, schMsgStore)
|
||||
|
||||
recipientId := uuid.New()
|
||||
messageId := uuid.New()
|
||||
@@ -123,7 +127,7 @@ func TestGetScheduledMessageEventWithMock(t *testing.T) {
|
||||
assert.Equal(t, http.StatusOK, rr.Code)
|
||||
|
||||
var response GetScheduledMessageEventResponse
|
||||
err := json.Unmarshal(rr.Body.Bytes(), &response)
|
||||
err = json.Unmarshal(rr.Body.Bytes(), &response)
|
||||
assert.NoError(t, err, "Error creating event %v", err)
|
||||
|
||||
assert.NotEmpty(t, response.Data, "No event created")
|
||||
@@ -139,7 +143,9 @@ func TestDeleteScheduledMessageEventWithMock(t *testing.T) {
|
||||
messageStore := mock.NewMockMessageStore()
|
||||
schMsgStore := mock.NewMockScheduledMessageStore()
|
||||
schMsgEventStore := mock.NewMockScheduledMessageEventStore()
|
||||
handler := NewScheduledMessageEventHandler(schMsgEventStore, schMsgStore)
|
||||
apiApp, err := GetApp()
|
||||
assert.NoError(t, err, "Error getting app")
|
||||
handler := NewScheduledMessageEventHandler(apiApp, schMsgEventStore, schMsgStore)
|
||||
|
||||
con := testContact(recipientId, testUserId)
|
||||
msg := testMessage(messageId, testUserId)
|
||||
@@ -167,7 +173,7 @@ func TestDeleteScheduledMessageEventWithMock(t *testing.T) {
|
||||
assert.Equal(t, http.StatusOK, rr.Code)
|
||||
|
||||
var response DeleteScheduledMessageEventResponse
|
||||
err := json.Unmarshal(rr.Body.Bytes(), &response)
|
||||
err = json.Unmarshal(rr.Body.Bytes(), &response)
|
||||
assert.NoError(t, err, "Error creating event %v", err)
|
||||
|
||||
assert.NotEmpty(t, response.Data, "No event created")
|
||||
|
||||
@@ -26,7 +26,9 @@ type CreateScheduledMessageRequest struct {
|
||||
func TestCreateScheduledMessageWithMock(t *testing.T) {
|
||||
now := time.Now()
|
||||
mockStore := mock.NewMockScheduledMessageStore()
|
||||
handler := NewScheduledMessageHandler(mockStore)
|
||||
apiApp, err := GetApp()
|
||||
assert.NoError(t, err, "Error getting app")
|
||||
handler := NewScheduledMessageHandler(apiApp, mockStore)
|
||||
|
||||
testUserId := uuid.New()
|
||||
testBody := testCreateScheduledMessageRequest(testUserId, now)
|
||||
@@ -40,7 +42,7 @@ func TestCreateScheduledMessageWithMock(t *testing.T) {
|
||||
assert.Equal(t, http.StatusCreated, rr.Code)
|
||||
|
||||
var response AddScheduledMessageResponse
|
||||
err := json.Unmarshal(rr.Body.Bytes(), &response)
|
||||
err = json.Unmarshal(rr.Body.Bytes(), &response)
|
||||
assert.NoError(t, err, "Error Creating message %v", err)
|
||||
|
||||
assert.NotEmpty(t, response.Data, "No Message created")
|
||||
@@ -68,13 +70,15 @@ func TestGetScheduledMessageWithMock(t *testing.T) {
|
||||
req, _ := http.NewRequest("GET", url, nil)
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
handler := NewScheduledMessageHandler(mockStore)
|
||||
apiApp, err := GetApp()
|
||||
assert.NoError(t, err, "Error getting app")
|
||||
handler := NewScheduledMessageHandler(apiApp, mockStore)
|
||||
handler.GetScheduledMessage(rr, req)
|
||||
|
||||
assert.Equal(t, http.StatusOK, rr.Code)
|
||||
|
||||
var response GetScheduledMessageResponse
|
||||
err := json.Unmarshal(rr.Body.Bytes(), &response)
|
||||
err = json.Unmarshal(rr.Body.Bytes(), &response)
|
||||
assert.NoError(t, err, "Error parsing response %v", err)
|
||||
}
|
||||
|
||||
@@ -114,13 +118,15 @@ func TestFetchScheduledMessageWithMock(t *testing.T) {
|
||||
req, _ := http.NewRequest("GET", endpoint.FetchNextScheduledMessageEndpoint, nil)
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
handler := NewScheduledMessageHandler(mockStore)
|
||||
apiApp, err := GetApp()
|
||||
assert.NoError(t, err, "Error getting app")
|
||||
handler := NewScheduledMessageHandler(apiApp, mockStore)
|
||||
handler.FetchNextMessage(rr, req)
|
||||
|
||||
assert.Equal(t, http.StatusOK, rr.Code)
|
||||
|
||||
var response FetchNextMessageResponse
|
||||
err := json.Unmarshal(rr.Body.Bytes(), &response)
|
||||
err = json.Unmarshal(rr.Body.Bytes(), &response)
|
||||
assert.NoError(t, err, "Error fetching scheduled message: %v", err)
|
||||
|
||||
assert.NotEmpty(t, response.Data, "No data")
|
||||
|
||||
@@ -2,8 +2,10 @@ package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"git.kundeng.us/phoenix/textsender-models/tx0/message"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
@@ -20,11 +22,15 @@ func NewMessageEventResponseStore(db *pgxpool.Pool) *PGMessageEventResponseStore
|
||||
}
|
||||
|
||||
func (m *PGMessageEventResponseStore) Create(ctx context.Context, mer *message.MessageEventResponse) error {
|
||||
query := `
|
||||
INSERT INTO message_event_responses (scheduled_message_event_id, response, user_id, sent)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING id
|
||||
`
|
||||
var query string
|
||||
queryBase := "INSERT INTO message_event_responses"
|
||||
queryReturn := "RETURNING id"
|
||||
|
||||
return m.db.QueryRow(ctx, query, mer.ScheduledMessageEventId, mer.Response, mer.UserId, mer.Sent).Scan(&mer.Id)
|
||||
if mer.ScheduledMessageEventId == uuid.Nil {
|
||||
query = fmt.Sprintf("%s (response, user_id, sent) VALUES ($1, $2, $3) %s", queryBase, queryReturn)
|
||||
return m.db.QueryRow(ctx, query, mer.Response, mer.UserId, mer.Sent).Scan(&mer.Id)
|
||||
} else {
|
||||
query = fmt.Sprintf("%s (scheduled_message_event_id, response, user_id, sent) %s", queryBase, queryReturn)
|
||||
return m.db.QueryRow(ctx, query, mer.ScheduledMessageEventId, mer.Response, mer.UserId, mer.Sent).Scan(&mer.Id)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,12 +42,15 @@ func (m *MockMessageEventResponseStore) Create(ctx context.Context, mer *message
|
||||
|
||||
if len(mer.Response) == 0 {
|
||||
return fmt.Errorf("Response is empty")
|
||||
} else if mer.ScheduledMessageEventId == uuid.Nil {
|
||||
return fmt.Errorf("Scheduled message event Id is nil")
|
||||
} else if mer.UserId == uuid.Nil {
|
||||
return fmt.Errorf("User Id is nil")
|
||||
} else {
|
||||
key := MessageEventResponseKey{ScheduledMessageEventId: mer.ScheduledMessageEventId, UserId: mer.UserId}
|
||||
if mer.ScheduledMessageEventId == uuid.Nil {
|
||||
key.ScheduledMessageEventId = uuid.Nil
|
||||
} else {
|
||||
key.ScheduledMessageEventId = mer.ScheduledMessageEventId
|
||||
}
|
||||
sent := time.Now()
|
||||
mer.Sent = sent
|
||||
|
||||
|
||||
@@ -36,7 +36,7 @@ CREATE TABLE IF NOT EXISTS scheduled_message_events (
|
||||
|
||||
CREATE TABLE IF NOT EXISTS message_event_responses (
|
||||
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
||||
scheduled_message_event_id UUID NOT NULL,
|
||||
scheduled_message_event_id UUID NULL,
|
||||
response JSONB NOT NULL,
|
||||
user_id UUID NOT NULL,
|
||||
sent timestamptz NOT NULL
|
||||
|
||||
Reference in New Issue
Block a user