Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Request Validation #14

Merged
merged 17 commits into from
Feb 11, 2022
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 10 additions & 10 deletions internal/datastore/mongo_store.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import (
"log"
"os"

"github.com/SimplQ/simplQ-golang/internal/models"
"github.com/SimplQ/simplQ-golang/internal/models/db"

"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
Expand Down Expand Up @@ -48,7 +48,7 @@ func NewMongoDB() *MongoDB {
return &new_mongodb
}

func (mongodb MongoDB) CreateQueue(queue models.Queue) (models.QueueId, error) {
func (mongodb MongoDB) CreateQueue(queue db.Queue) (db.QueueId, error) {
// Set id to empty so its generated by mongoDB
queue.Id = ""

Expand All @@ -60,11 +60,11 @@ func (mongodb MongoDB) CreateQueue(queue models.Queue) (models.QueueId, error) {

stringId := result.InsertedID.(primitive.ObjectID).Hex()

return models.QueueId(stringId), nil
return db.QueueId(stringId), nil
}

func (mongodb MongoDB) ReadQueue(id models.QueueId) (models.Queue, error) {
result := models.Queue{}
func (mongodb MongoDB) ReadQueue(id db.QueueId) (db.Queue, error) {
result := db.Queue{}

// convert id string to ObjectId
queueId, _ := primitive.ObjectIDFromHex(string(id))
Expand All @@ -78,7 +78,7 @@ func (mongodb MongoDB) ReadQueue(id models.QueueId) (models.Queue, error) {
return result, nil
}

func (mongodb MongoDB) SetIsPaused(id models.QueueId, isPaused bool) error {
func (mongodb MongoDB) SetIsPaused(id db.QueueId, isPaused bool) error {
queueId, _ := primitive.ObjectIDFromHex(string(id))
result, err := mongodb.Queue.UpdateOne(
context.TODO(),
Expand All @@ -98,7 +98,7 @@ func (mongodb MongoDB) SetIsPaused(id models.QueueId, isPaused bool) error {

}

func (mongodb MongoDB) DeleteQueue(id models.QueueId) error {
func (mongodb MongoDB) DeleteQueue(id db.QueueId) error {
queueId, _ := primitive.ObjectIDFromHex(string(id))
result, err := mongodb.Queue.DeleteOne(
context.TODO(),
Expand All @@ -114,14 +114,14 @@ func (mongodb MongoDB) DeleteQueue(id models.QueueId) error {
return nil
}

func (mongodb MongoDB) AddTokenToQueue(models.QueueId, models.Token) {
func (mongodb MongoDB) AddTokenToQueue(db.QueueId, db.Token) {
panic("Not implemented")
}

func (mongodb MongoDB) ReadToken(models.TokenId) {
func (mongodb MongoDB) ReadToken(db.TokenId) {
panic("Not implemented")
}

func (mongodb MongoDB) RemoveToken(models.TokenId) {
func (mongodb MongoDB) RemoveToken(db.TokenId) {
panic("Not implemented")
}
16 changes: 8 additions & 8 deletions internal/datastore/store.go
Original file line number Diff line number Diff line change
@@ -1,30 +1,30 @@
package datastore

import (
"github.com/SimplQ/simplQ-golang/internal/models"
"github.com/SimplQ/simplQ-golang/internal/models/db"
)

type QueueStore interface {
// Create a new queue and return the queue ID.
CreateQueue(models.Queue) (models.QueueId, error)
CreateQueue(db.Queue) (db.QueueId, error)

// Read a queue by id.
ReadQueue(models.QueueId) (models.Queue, error)
ReadQueue(db.QueueId) (db.Queue, error)

// Set the queue pause status to true/false
SetIsPaused(models.QueueId, bool) error
SetIsPaused(db.QueueId, bool) error

// Set the queue delete status to new value.
DeleteQueue(models.QueueId) error
DeleteQueue(db.QueueId) error

// Add a new token to the queue.
AddTokenToQueue(models.QueueId, models.Token)
AddTokenToQueue(db.QueueId, db.Token)

// Read token by id.
ReadToken(models.TokenId)
ReadToken(db.TokenId)

// Delete token
RemoveToken(models.TokenId)
RemoveToken(db.TokenId)
}

var Store QueueStore = NewMongoDB()
37 changes: 25 additions & 12 deletions internal/handler/queue.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ import (
"time"

"github.com/SimplQ/simplQ-golang/internal/datastore"
"github.com/SimplQ/simplQ-golang/internal/models"
"github.com/SimplQ/simplQ-golang/internal/models/api"
"github.com/SimplQ/simplQ-golang/internal/models/db"
"github.com/go-chi/chi/v5"
)

Expand All @@ -23,7 +24,7 @@ func GetQueue(w http.ResponseWriter, r *http.Request) {
http.Error(w, fmt.Sprintf("Invalid Id: %s", id), http.StatusBadRequest)
return
}
queue, err := datastore.Store.ReadQueue(models.QueueId(id))
queue, err := datastore.Store.ReadQueue(db.QueueId(id))
if err != nil {
http.Error(w, fmt.Sprint(err), http.StatusInternalServerError)
return
Expand All @@ -34,25 +35,37 @@ func GetQueue(w http.ResponseWriter, r *http.Request) {
func CreateQueue(w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body)

var q models.Queue
err := decoder.Decode(&q)
var queueRequest api.CreateQueueRequest
err := decoder.Decode(&queueRequest)

if err != nil {
http.Error(w, fmt.Sprint(err), http.StatusBadRequest)
}

// Validation
validationErr, ok := queueRequest.Validate()

if !ok {
http.Error(w, validationErr.Message, http.StatusBadRequest)
return
}

// Initialize values
// Only consider queue name from the body of the request
q.CreationTime = time.Now()
q.IsDeleted = false
q.IsPaused = false
q.Tokens = make([]models.Token, 0)
queue := db.Queue{
QueueName: queueRequest.QueueName,
CreationTime: time.Now(),
IsDeleted: false,
IsPaused: false,
Tokens: make([]db.Token, 0),
}

insertedId, err := datastore.Store.CreateQueue(q)
insertedId, err := datastore.Store.CreateQueue(queue)
if err != nil {
http.Error(w, fmt.Sprint(err), http.StatusInternalServerError)
return
}

log.Printf("Inserted %s", insertedId)
w.WriteHeader(http.StatusCreated)
fmt.Fprintf(w, "Queue created with Id: %s", insertedId)
Expand All @@ -64,7 +77,7 @@ func PauseQueue(w http.ResponseWriter, r *http.Request) {
http.Error(w, fmt.Sprintf("Invalid Id: %s", id), http.StatusBadRequest)
return
}
err := datastore.Store.SetIsPaused(models.QueueId(id), true) // Set IsPaused = true
err := datastore.Store.SetIsPaused(db.QueueId(id), true) // Set IsPaused = true
if err != nil {
http.Error(w, fmt.Sprint(err), http.StatusInternalServerError)
return
Expand All @@ -79,7 +92,7 @@ func ResumeQueue(w http.ResponseWriter, r *http.Request) {
http.Error(w, fmt.Sprintf("Invalid Id: %s", id), http.StatusBadRequest)
return
}
err := datastore.Store.SetIsPaused(models.QueueId(id), false) // Set IsPaused = false
err := datastore.Store.SetIsPaused(db.QueueId(id), false) // Set IsPaused = false
if err != nil {
http.Error(w, fmt.Sprint(err), http.StatusInternalServerError)
return
Expand All @@ -94,7 +107,7 @@ func DeleteQueue(w http.ResponseWriter, r *http.Request) {
http.Error(w, fmt.Sprintf("Invalid Id: %s", id), http.StatusBadRequest)
return
}
err := datastore.Store.DeleteQueue(models.QueueId(id))
err := datastore.Store.DeleteQueue(db.QueueId(id))
if err != nil {
http.Error(w, fmt.Sprint(err), http.StatusInternalServerError)
return
Expand Down
24 changes: 24 additions & 0 deletions internal/models/api/common.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// Package internal/models/api defines models to be used for API requests.
package api
aneeshsharma marked this conversation as resolved.
Show resolved Hide resolved

// Structure ValidationError is used to describe an error that occurs in a
// validation.
//
// Members
//
// Field - name of the field which had an error.
// Message - description of the error.
type ValidationError struct {
Field string
Message string
}

// Interface Validator defines how to define a validator for a request.
type Validator interface {
aneeshsharma marked this conversation as resolved.
Show resolved Hide resolved
// Method Validate validates the request data.
// Returns ValidationError, false if the request data is invalid.
// Returns ValidationError, true if the request data is valid.
// If ValidationError, true is returned ValidationError is empty and
// should be ignored.
Validate() (ValidationError, bool)
}
41 changes: 41 additions & 0 deletions internal/models/api/queue.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// Package internal/models/api defines models to be used for API requests.
package api

import (
"fmt"

"github.com/SimplQ/simplQ-golang/internal/models/db"
)

// CreateQueueRequest is a model to structure a create queue request.
//
// Members
//
// QueueName - Name of the queue to be created.
type CreateQueueRequest struct {
QueueName string
}

// CreateQueueResponse is a model to strcuture the response of a create queue
// request.
type CreateQueueResponse db.Queue

// Minimum length of a queue name.
const MIN_LENGTH = 4

// Maximum length of a queue name.
const MAX_LENGTH = 20

// Validate function for CreateQueueRequest validates if the queue name is within
// the defined range.
func (req CreateQueueRequest) Validate() (ValidationError, bool) {
if len(req.QueueName) < MIN_LENGTH || len(req.QueueName) > MAX_LENGTH {
message := fmt.Sprintf("Queue name length should be greater than %d characters and less than %d charaacters", MIN_LENGTH, MAX_LENGTH)
return ValidationError{
Field: "QueueName",
Message: message,
}, false
}

return ValidationError{}, true
}
2 changes: 1 addition & 1 deletion internal/models/common.go → internal/models/db/common.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
package models
package db

type Id string
2 changes: 1 addition & 1 deletion internal/models/queue.go → internal/models/db/queue.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package models
package db

import (
"time"
Expand Down
2 changes: 1 addition & 1 deletion internal/models/token.go → internal/models/db/token.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package models
package db

import (
"time"
Expand Down