/
rpc_create_game.go
78 lines (67 loc) · 2.12 KB
/
rpc_create_game.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package gapi
import (
"context"
"log"
db "github.com/PlatosCodes/desserted/backend/db/sqlc"
"github.com/PlatosCodes/desserted/backend/pb"
"github.com/lib/pq"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/timestamppb"
)
func (server *Server) CreateGame(ctx context.Context, req *pb.CreateGameRequest) (*pb.CreateGameResponse, error) {
authPayload, err := server.authorizeUser(ctx)
if err != nil {
return nil, unauthenticatedError(err)
}
creatorID := req.GetCreatedBy()
if creatorID < 1 {
return nil, status.Errorf(codes.InvalidArgument, "not a valid user ID: %d", req.GetCreatedBy())
}
if authPayload.UserID != req.GetCreatedBy() {
return nil, status.Errorf(codes.PermissionDenied, "cannot create game for another user")
}
game, err := server.Store.CreateGame(ctx, creatorID)
if err != nil {
if pqErr, ok := err.(*pq.Error); ok {
switch pqErr.Code.Name() {
case "unique_violation":
return nil, status.Errorf(codes.AlreadyExists, "username already exists: %s", err)
}
}
return nil, status.Errorf(codes.Internal, "internal server error: %s", err)
}
err = server.Store.AddPlayerToGame(ctx, db.AddPlayerToGameParams{
PlayerID: creatorID,
GameID: game.GameID,
})
if err != nil {
if pqErr, ok := err.(*pq.Error); ok {
switch pqErr.Code.Name() {
case "unique_violation":
return nil, status.Errorf(codes.AlreadyExists, "player has already joined game: %s", err)
}
}
return nil, status.Errorf(codes.Internal, "internal server error: %s", err)
}
var endTime *timestamppb.Timestamp
if game.EndTime.Valid {
endTime = timestamppb.New(game.EndTime.Time)
} else {
endTime = nil
}
rsp := &pb.CreateGameResponse{
Game: &pb.Game{
GameId: game.GameID,
CreatedBy: game.CreatedBy,
NumberOfPlayers: game.NumberOfPlayers,
CurrentTurn: game.CurrentTurn,
CurrentPlayerNumber: game.CurrentPlayerNumber.Int32,
Status: game.Status,
StartTime: timestamppb.New(game.StartTime),
EndTime: endTime,
},
}
log.Println("RESPONSE: ", rsp)
return rsp, nil
}