Skip to content

Commit

Permalink
Merge pull request #10 from aaronarduino/master
Browse files Browse the repository at this point in the history
completed issue #6 - handles dup subscriptions
  • Loading branch information
jcbwlkr committed Mar 31, 2016
2 parents 4e0cc1e + ba8aa49 commit 6b89c34
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
15 changes: 13 additions & 2 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
"strings"
"time"

_ "github.com/lib/pq"
pq "github.com/lib/pq"
)

var db *sql.DB
Expand Down Expand Up @@ -44,6 +44,13 @@ func twilioIncomingHandler(rw http.ResponseWriter, r *http.Request) {
switch body {
case "sign up", "sign-up", "signup", "subscribe":
if _, err := db.Exec("insert into subscriptions (number) values ($1)", from); err != nil {

if err, ok := err.(*pq.Error); ok {
if err.Code.Name() == "unique_violation" {
respondMessage(rw, "You've all ready been subscribed to voting reminders! Text STOP to unsubscribe.")
return
}
}
respondError(rw, err)
return
}
Expand All @@ -62,14 +69,18 @@ func twilioIncomingHandler(rw http.ResponseWriter, r *http.Request) {
respondError(rw, err)
return
}
rw.Write([]byte(message))
respondMessage(rw, message)
}

func respondError(rw http.ResponseWriter, err error) {
log.Print(err)
rw.WriteHeader(http.StatusBadRequest)
}

func respondMessage(rw http.ResponseWriter, message string) {
rw.Write([]byte(message))
}

func logMessage(from string, to string, message string) error {
_, err := db.Exec("insert into message_log (from_number, to_number, body, created_at) values ($1, $2, $3, $4)", from, to, message, time.Now())
return err
Expand Down
4 changes: 4 additions & 0 deletions schema.sql
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
create table subscriptions (
id serial,
number varchar(12) not null
CONSTRAINT subscriptions_number_key UNIQUE (number)
);

create table message_log (
Expand All @@ -10,3 +11,6 @@ create table message_log (
body text not null,
created_at timestamp not null
);

ALTER TABLE subscriptions
ADD CONSTRAINT subscriptions_number_key UNIQUE (number)

0 comments on commit 6b89c34

Please sign in to comment.