Commit 7c9cd786 authored by Enrico Bollen's avatar Enrico Bollen 💬
Browse files

Merge branch 'testing' into 'dev'

Testing

See merge request !31
parents c41e86a4 98095269
Pipeline #1852 failed with stages
in 54 seconds
......@@ -9,7 +9,7 @@ import (
"github.com/gorilla/mux"
m "git.coco.study/fvitt/good2go/api/rest/middlewares"
h "git.coco.study/fvitt/good2go/api/rest/subrouters"
h "git.coco.study/fvitt/good2go/api/rest/routes"
)
func getPort() string {
......@@ -31,8 +31,8 @@ func Init() {
r.Use(m.SentryHandler)
// Register all the Routers
h.BuildingRouter.AttachRouter(r)
h.AppointmentRouter.AttachRouter(r)
h.RoomRouter.AttachRouter(r)
h.HomeRouter.AttachRouter(r)
// Create a new server
......
package restapi
import (
"encoding/json"
"fmt"
"net/http"
u "git.coco.study/fvitt/good2go/api/rest/utils"
"git.coco.study/fvitt/good2go/internal/model"
s "git.coco.study/fvitt/good2go/internal/services"
"github.com/gorilla/mux"
)
......@@ -14,6 +19,26 @@ var (
)
func createAppointment(res http.ResponseWriter, req *http.Request) {
type appointmentDTO struct {
RoomID int
}
var r model.Room
err := json.NewDecoder(req.Body).Decode(&r)
if err != nil {
http.Error(res, err.Error(), http.StatusBadRequest)
return
}
room, err := s.RoomService.CreateRoom(&r)
if err != nil {
fmt.Println(err)
}
err = u.SendJSON(res).Encode(room)
if err != nil {
fmt.Println(err)
}
}
func getAppointment(res http.ResponseWriter, req *http.Request) {
......
......@@ -5,6 +5,7 @@ import (
"fmt"
"log"
"net/http"
"strconv"
u "git.coco.study/fvitt/good2go/api/rest/utils"
"git.coco.study/fvitt/good2go/internal/model"
......@@ -16,23 +17,21 @@ type roomRouter struct{}
var (
// RoomRouter Handles requests to /room
RoomRouter = &buildingRouter{}
RoomRouter = &roomRouter{}
)
func createRoom(res http.ResponseWriter, req *http.Request) {
type roomDTO struct {
buildingID string
room model.Room
var r model.Room
err := json.NewDecoder(req.Body).Decode(&r)
if err != nil {
http.Error(res, err.Error(), http.StatusBadRequest)
return
}
var r roomDTO
err := json.NewDecoder(req.Body).Decode(&roomDTO{})
room, err := s.RoomService.CreateRoom(&r)
if err != nil {
http.Error(res, err.Error(), http.StatusBadRequest)
return
}
room, err := s.BuildingService.CreateRoom(r.buildingID, &r.room)
err = u.SendJSON(res).Encode(room)
if err != nil {
......@@ -42,9 +41,11 @@ func createRoom(res http.ResponseWriter, req *http.Request) {
func getRoom(res http.ResponseWriter, req *http.Request) {
roomID := mux.Vars(req)["roomID"]
roomNumberString := mux.Vars(req)["roomNumber"]
room, roomErr := s.BuildingService.GetRoom(roomID)
roomNumber, _ := strconv.Atoi(roomNumberString)
room, roomErr := s.RoomService.GetRoomByNumber(roomNumber)
if roomErr == nil {
u.SendJSON(res).Encode(room)
......@@ -55,7 +56,7 @@ func getRoom(res http.ResponseWriter, req *http.Request) {
func getAllRooms(res http.ResponseWriter, req *http.Request) {
rooms := s.BuildingService.GetAllRooms()
rooms := s.RoomService.GetAllRooms()
err := u.SendJSON(res).Encode(rooms)
if err != nil {
......@@ -65,7 +66,8 @@ func getAllRooms(res http.ResponseWriter, req *http.Request) {
func updateRoom(res http.ResponseWriter, req *http.Request) {
roomID := mux.Vars(req)["roomID"]
roomNumberString := mux.Vars(req)["roomNumber"]
roomNumber, _ := strconv.Atoi(roomNumberString)
var r model.Room
parseBodyErr := json.NewDecoder(req.Body).Decode(&r)
......@@ -74,7 +76,7 @@ func updateRoom(res http.ResponseWriter, req *http.Request) {
return
}
room, err := s.BuildingService.UpdateRoomCapacity(roomID, r.Capacity)
room, err := s.RoomService.UpdateRoomCapacity(roomNumber, r.Capacity)
if err == nil {
err := u.SendJSON(res).Encode(room)
......@@ -88,32 +90,35 @@ func updateRoom(res http.ResponseWriter, req *http.Request) {
func deleteRoom(res http.ResponseWriter, req *http.Request) {
roomID := mux.Vars(req)["roomID"]
roomNumberString := mux.Vars(req)["roomNumber"]
roomNumber, _ := strconv.Atoi(roomNumberString)
err := s.BuildingService.DeleteRoom(roomID)
err := s.RoomService.DeleteRoom(roomNumber)
if err != nil {
http.Error(res, err.Error(), http.StatusBadRequest)
log.Fatal(err)
}
res.Write([]byte("deleted room with number " + roomNumberString))
res.WriteHeader(http.StatusOK)
}
// AttachRouter initialize Router
func (a roomRouter) AttachRouter(router *mux.Router) {
r := router.PathPrefix("/rooms").Subrouter().StrictSlash(true)
//todo addd single room route
multipleR := router.PathPrefix("/rooms").Subrouter().StrictSlash(true)
singleR := router.PathPrefix("/room").Subrouter().StrictSlash(true)
// CREATE
r.HandleFunc("/", createRoom).Methods("POST")
singleR.HandleFunc("/", createRoom).Methods("POST")
// READ
r.HandleFunc("/{roomID}", getRoom).Methods("GET")
r.HandleFunc("/", getAllRooms).Methods("GET")
singleR.HandleFunc("/{roomNumber}", getRoom).Methods("GET")
multipleR.HandleFunc("/", getAllRooms).Methods("GET")
// UPDATE
r.HandleFunc("/{roomID}", updateRoom).Methods("PUT")
singleR.HandleFunc("/{roomNumber}", updateRoom).Methods("PUT")
// DELETE
r.HandleFunc("/{roomID}", deleteRoom).Methods("DELETE")
singleR.HandleFunc("/{roomNumber}", deleteRoom).Methods("DELETE")
}
......@@ -10,6 +10,9 @@ import (
)
func main() {
log.SetFlags(log.LstdFlags | log.Lshortfile)
// Sentry
initSentry()
// Flush buffered events before the program terminates.
......
......@@ -20,38 +20,16 @@ func Disconnect() {
func CreateSampleData() {
// Get all buildings
buildings, err := ownMongo.BuildingRepo.GetAllBuildings()
if err != nil {
log.Fatal(err)
}
var building *model.Building
// Only create sample data if no sample data exists
if len(buildings) == 0 {
// Add Building
building = &model.Building{}
building, err := services.BuildingService.CreateBuilding(building.New("08:00", "10h", []string{"mon", "tue", "wed", "thu", "fri", "sat"}))
if err != nil {
log.Fatal(err)
log.Print(building)
}
} else {
building = buildings[0]
}
rooms := building.GetRooms()
rooms := ownMongo.RoomRepo.GetAllRooms()
log.Print("INIT", rooms, len(rooms))
if len(rooms) == 0 {
services.BuildingService.CreateRoom(building.ID.Hex(), &model.Room{
services.RoomService.CreateRoom(&model.Room{
Number: 420,
Capacity: 69,
})
}
}
package repositories
import (
"context"
"log"
"time"
......@@ -18,28 +19,25 @@ type BuildingRepository interface {
UpdateBuilding(id interface{}, building *model.Building) (*mongo.UpdateResult, error)
}
func (repo *Repository) findBuildingByID(buildingID string) (*model.Building, error) {
func (repo *Repository) GetBuildingById(buildingID string) (*model.Building, error) {
ctx, cancel := utils.CreateTimeoutCTX(5 * time.Second)
defer cancel()
//ctx, cancel := utils.CreateTimeoutCTX(5 * time.Second)
// defer cancel()
id, err := primitive.ObjectIDFromHex(buildingID)
if err != nil {
return nil, err
}
res, err := repo.Col.Find(ctx, bson.M{"_id": id})
if err != nil {
return nil, err
}
res := repo.Col.FindOne(context.TODO(), bson.M{"_id": id})
building := model.Building{}
err = res.Decode(&building)
Building := model.Building{}
err = res.Decode(&Building)
if err != nil {
return nil, err
}
return &building, err
return &Building, err
}
......@@ -54,10 +52,7 @@ func (repo *Repository) CreateBuilding(building *model.Building) (*model.Buildin
}
// Get
res, err := repo.Col.Find(ctx, bson.M{"_id": insertedRes.InsertedID})
if err != nil {
return nil, err
}
res := repo.Col.FindOne(ctx, bson.M{"_id": insertedRes.InsertedID})
// Decode
result := model.Building{}
......@@ -69,33 +64,16 @@ func (repo *Repository) CreateBuilding(building *model.Building) (*model.Buildin
return &result, nil
}
func (repo *Repository) UpdateBuilding(id interface{}, building *model.Building) (*mongo.UpdateResult, error) {
func (repo *Repository) UpdateBuilding(building *model.Building) (*mongo.UpdateResult, error) {
ctx, cancel := utils.CreateTimeoutCTX(time.Second * 10)
defer cancel()
res, err := repo.Col.ReplaceOne(ctx, bson.M{"_id": id}, &building)
res, err := repo.Col.ReplaceOne(ctx, bson.M{"_id": &building.ID}, &building)
if err != nil {
return nil, err
}
return res, nil
}
func (repo *Repository) GetBuildingById(id string) (*model.Building, error) {
return repo.findBuildingByID(id)
}
func (repo *Repository) GetBuilding(filter *bson.M) (*model.Building, error) {
ctx, cancel := utils.CreateTimeoutCTX(time.Second * 10)
defer cancel()
res := repo.Col.FindOne(ctx, filter)
building := model.Building{}
err := res.Decode(&building)
if err != nil {
return nil, err
}
return &building, nil
}
func (repo *Repository) GetAllBuildings() ([]*model.Building, error) {
ctx, cancel := utils.CreateTimeoutCTX(time.Second * 10)
......
......@@ -17,34 +17,11 @@ import (
type RoomRepository interface {
CreateRoom(r *model.Room) (*model.Room, error)
UpdateRoom(r *model.Room)
GetRoom(document interface{}) (room *model.Room, err error)
GetAllRooms() []model.Room
ConnectTo(c *mongo.Collection) *Repository
}
func (repo *Repository) findByRoomNumber(roomNumber int) (*model.Room, error) {
ctx, cancel := utils.CreateTimeoutCTX(5 * time.Second)
defer cancel()
// Find
result, err := repo.Col.Find(ctx, bson.M{"number": roomNumber})
if err != nil {
return &model.Room{}, err
}
// Decode
var r model.Room
err = result.Decode(&r)
if err != nil {
return &model.Room{}, err
}
return &r, nil
}
func (repo *Repository) findByID(roomID string) (*model.Room, error) {
func (repo *Repository) GetRoomByID(roomID string) (*model.Room, error) {
id, err := primitive.ObjectIDFromHex(roomID)
if err != nil {
......@@ -55,10 +32,7 @@ func (repo *Repository) findByID(roomID string) (*model.Room, error) {
defer cancel()
// Find
result, err := repo.Col.Find(ctx, bson.M{"_id": id})
if err != nil {
return &model.Room{}, err
}
result := repo.Col.FindOne(ctx, bson.M{"_id": id})
// Decode
var r model.Room
......@@ -82,10 +56,7 @@ func (repo *Repository) insertOne(document interface{}) (*model.Room, error) {
}
// Find
result, err := repo.Col.Find(ctx, bson.M{"_id": insertResult.InsertedID})
if err != nil {
return &model.Room{}, err
}
result := repo.Col.FindOne(ctx, bson.M{"_id": insertResult.InsertedID})
// Decode
var r model.Room
......@@ -109,10 +80,7 @@ func (repo *Repository) updateOne(document interface{}) (*model.Room, error) {
}
// Find
result, err := repo.Col.Find(ctx, bson.M{"_id": insertedResult.UpsertedID})
if err != nil {
return &model.Room{}, err
}
result := repo.Col.FindOne(ctx, bson.M{"_id": insertedResult.UpsertedID})
// Decode
var r model.Room
......@@ -126,40 +94,13 @@ func (repo *Repository) updateOne(document interface{}) (*model.Room, error) {
}
func (repo *Repository) findOne(document interface{}) (*model.Room, error) {
ctx, cancel := utils.CreateTimeoutCTX(5 * time.Second)
defer cancel()
result := repo.Col.FindOne(ctx, document)
var room model.Room
err := result.Decode(&room)
return &room, err
}
func (repo *Repository) deleteByID(id primitive.ObjectID) error {
ctx, cancel := utils.CreateTimeoutCTX(5 * time.Second)
defer cancel()
_, err := repo.Col.DeleteOne(ctx, bson.M{"_id": id})
return err
}
func (repo *Repository) GetRoomByID(id string) (*model.Room, error) {
return repo.findByID(id)
}
func (repo *Repository) CreateRoom(r *model.Room) (*model.Room, error) {
log.Print("Create room ", r.Number)
//Check if room with same room number exists
existingRoom, err := repo.GetRoom(bson.M{"number": r.Number})
if err == nil {
t := strconv.Itoa(r.Number)
return existingRoom, errors.New("Room with number " + t + " already exists")
existingRoom, err := repo.GetRoomByNumber(r.Number)
if existingRoom != nil {
return existingRoom, errors.New("Room with number " + strconv.Itoa(r.Number) + " already exists")
}
room, err := repo.insertOne(bson.M{
......@@ -181,13 +122,35 @@ func (repo *Repository) UpdateRoom(r *model.Room) (*model.Room, error) {
return repo.updateOne(r)
}
func (repo *Repository) GetRoom(document interface{}) (room *model.Room, err error) {
log.Print("Finding room by ", document)
return repo.findOne(document)
func (repo *Repository) DeleteRoom(roomNumber int) (err error) {
ctx, cancel := utils.CreateTimeoutCTX(5 * time.Second)
defer cancel()
_, err = repo.Col.DeleteOne(ctx, bson.M{"number": roomNumber})
if err != nil {
return err
}
return nil
}
func (repo *Repository) DeleteRoom(roomID string) (room *model.Room, err error) {
return repo.findByID(roomID)
func (repo *Repository) GetRoomByNumber(roomNumber int) (*model.Room, error) {
ctx, cancel := utils.CreateTimeoutCTX(5 * time.Second)
defer cancel()
// Find
result := repo.Col.FindOne(ctx, bson.M{"number": roomNumber})
// Decode
var r model.Room
err := result.Decode(&r)
if err != nil {
return &model.Room{}, err
}
return &r, nil
}
func (repo *Repository) GetAllRooms() []*model.Room {
......
......@@ -5,7 +5,6 @@ import (
"testing"
"git.coco.study/fvitt/good2go/internal/model"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
)
......@@ -25,7 +24,7 @@ func Test_roomRepository_CreateRoom(t *testing.T) {
fmt.Println(err)
}
room, err := repo.findByRoomNumber(100)
room, err := repo.GetRoomByNumber(100)
if err != nil {
t.Error(err)
}
......@@ -43,7 +42,7 @@ func Test_roomRepository_UpdateRoom(t *testing.T) {
Capacity: 22,
})
room, err := repo.findByRoomNumber(100)
room, err := repo.GetRoomByNumber(100)
if err != nil {
t.Error(err)
}
......@@ -54,23 +53,6 @@ func Test_roomRepository_UpdateRoom(t *testing.T) {
}
func Test_roomRepository_GetRoom(t *testing.T) {
_, err := repo.CreateRoom(&model.Room{Number: 420, Capacity: 22})
if err != nil {
fmt.Println(err)
panic(err)
}
_, err = repo.GetRoom(bson.M{
"number": 420,
})
if err != nil {
t.Error(err)
}
}
func Test_roomRepository_GetAllRooms(t *testing.T) {
rooms := repo.GetAllRooms()
......
......@@ -14,6 +14,8 @@ services:
mongo:
image: mongo:latest
container_name: mongo
ports:
- 27017:27017
volumes:
- dbdata:/data/db
environment:
......
package model
import (
"fmt"
"testing"
)
func TestBuilding_New(t *testing.T) {
building1 := newBuilding()
fmt.Println(building1)
if building1.OpeningHour.Hour() != 8 {
t.Error("Opening: Expected 8, got: ", building1.OpeningHour.Hour())
}
if building1.ClosingHour.Hour() != 18 {
t.Error("Closing: Expected 18, got: ", building1.ClosingHour.Hour())
}
if !building1.ClosingHour.After(building1.OpeningHour) {
t.Error("Closing Hour not after opening hour\n", building1.ClosingHour, "\n", building1.OpeningHour)
}
}
func TestBuilding_CreateRoom(t *testing.T) {
building1 := newBuilding()
const roomNumber int = 520
const capacity int = 35
building1.CreateRoom(roomNumber, capacity)
if len(building1.Rooms) != 1 {
t.Error("\n\nRooms slice still empty\nDid not add room to slide\nlen: ", len(building1.Rooms))
}
got := building1.Rooms[0]
if got.Number != roomNumber {
t.Error("\nRoom Number does not match\nExpected: ", roomNumber, "\n got: ", got.Number)
}
if got.Capacity != capacity {
t.Error("\nRoom Capacity does not match\nExpected: ", capacity, "\n got: ", got.Capacity)
}
}
func TestBuilding_DeleteRoom(t *testing.T) {
building1 := newBuilding()
// Add one – remove one
building1.CreateRoom(200, 50)
building1.DeleteRoom(200)
if len(building1.Rooms) > 0 {
t.Error("Room not deleted")
}