Browse Source

api /resources/:userid working

master
arnaucube 5 years ago
parent
commit
c07b4edd62
7 changed files with 78 additions and 19 deletions
  1. +3
    -1
      cmd/server.go
  2. +20
    -0
      endpoint/handlers.go
  3. +3
    -0
      endpoint/serve.go
  4. +12
    -11
      models/user.go
  5. +6
    -0
      services/gamesrv/gamesrv.go
  6. +21
    -3
      services/usersrv/usersrv.go
  7. +13
    -4
      test/test.py

+ 3
- 1
cmd/server.go

@ -4,6 +4,7 @@ import (
"github.com/arnaucube/gogame/config" "github.com/arnaucube/gogame/config"
"github.com/arnaucube/gogame/database" "github.com/arnaucube/gogame/database"
"github.com/arnaucube/gogame/endpoint" "github.com/arnaucube/gogame/endpoint"
"github.com/arnaucube/gogame/services/gamesrv"
"github.com/arnaucube/gogame/services/usersrv" "github.com/arnaucube/gogame/services/usersrv"
"github.com/urfave/cli" "github.com/urfave/cli"
) )
@ -28,7 +29,8 @@ func start(c *cli.Context) error {
} }
// services // services
userservice := usersrv.New(db)
gameservice := gamesrv.New(db)
userservice := usersrv.New(db, gameservice)
if err != nil { if err != nil {
return err return err
} }

+ 20
- 0
endpoint/handlers.go

@ -60,3 +60,23 @@ func handleLogin(c *gin.Context) {
"user": user, "user": user,
}) })
} }
func handleGetResources(c *gin.Context) {
userid := c.Param("userid")
user, err := userservice.GetUserById(userid)
if err != nil {
fail(c, err, "error on getting user")
return
}
resources, err := user.GetResources()
if err != nil {
fail(c, err, "error on getting user")
return
}
c.JSON(200, gin.H{
"user": user,
"resources": resources,
})
}

+ 3
- 0
endpoint/serve.go

@ -19,6 +19,9 @@ func newApiService() *gin.Engine {
api.GET("/info", handleInfo) api.GET("/info", handleInfo)
api.POST("/register", handleRegister) api.POST("/register", handleRegister)
api.POST("/login", handleLogin) api.POST("/login", handleLogin)
// TODO add jwt checker
api.GET("/resources/:userid", handleGetResources)
return api return api
} }

+ 12
- 11
models/user.go

@ -65,7 +65,7 @@ func (u *User) StoreInDb() error {
userDb := UserDb{ userDb := UserDb{
Id: u.Id, Id: u.Id,
Name: u.Name, Name: u.Name,
LastUpdated: u.LastUpdated,
LastUpdated: time.Now(),
Resources: u.Resources, Resources: u.Resources,
} }
err := u.db.Users.Update(bson.M{"_id": u.Id}, userDb) err := u.db.Users.Update(bson.M{"_id": u.Id}, userDb)
@ -85,16 +85,16 @@ func (u *User) GetFromDb() error {
func (u *User) GetPlanets() ([]Planet, error) { func (u *User) GetPlanets() ([]Planet, error) {
var planets []Planet var planets []Planet
err := u.db.Users.Find(bson.M{"OwnerId": u.Id}).All(&planets)
err := u.db.Planets.Find(bson.M{"ownerid": u.Id}).All(&planets)
if err != nil { if err != nil {
return planets, err return planets, err
} }
return planets, nil return planets, nil
} }
// GetResources updates the values of resources and returns the value
// GetResources updates the values of resources and returns the value, also updates the user.Resources
// Resource types: metal, crystal, deuterium, energy // Resource types: metal, crystal, deuterium, energy
func (u *User) GetResources() (*User, error) {
func (u *User) GetResources() (*Resources, error) {
// get current values // get current values
err := u.GetFromDb() err := u.GetFromDb()
if err != nil { if err != nil {
@ -112,16 +112,17 @@ func (u *User) GetResources() (*User, error) {
} }
// get Resource-Plant level in each planet // get Resource-Plant level in each planet
// and calculate growth = ResourcePlant.Level for each planet
var metalGrowth, crystalGrowth, deuteriumGrowth, energyGrowth int64 var metalGrowth, crystalGrowth, deuteriumGrowth, energyGrowth int64
for _, planet := range planets { for _, planet := range planets {
// calculate growth = ResourcePlant.Level for each planet
fmt.Println("planet", planet)
// TODO find correct formulas // TODO find correct formulas
metalGrowth = metalGrowth + (planet.Buildings.MetalMine * int64(delta))
crystalGrowth = crystalGrowth + (planet.Buildings.CrystalMine * int64(delta))
deuteriumGrowth = deuteriumGrowth + (planet.Buildings.DeuteriumMine * int64(delta))
energyGrowth = energyGrowth + (planet.Buildings.EnergyMine * int64(delta))
metalGrowth = metalGrowth + ((1 + planet.Buildings.MetalMine) * int64(delta))
crystalGrowth = crystalGrowth + ((1 * planet.Buildings.CrystalMine) * int64(delta))
deuteriumGrowth = deuteriumGrowth + ((1 * planet.Buildings.DeuteriumMine) * int64(delta))
energyGrowth = energyGrowth + ((1 * planet.Buildings.EnergyMine) * int64(delta))
} }
// calculate newAmount = oldAmount + (growth & DeltaTime)
// calculate newAmount = oldAmount + growth
u.Resources.Metal = u.Resources.Metal + metalGrowth u.Resources.Metal = u.Resources.Metal + metalGrowth
u.Resources.Crystal = u.Resources.Crystal + crystalGrowth u.Resources.Crystal = u.Resources.Crystal + crystalGrowth
u.Resources.Deuterium = u.Resources.Deuterium + deuteriumGrowth u.Resources.Deuterium = u.Resources.Deuterium + deuteriumGrowth
@ -134,5 +135,5 @@ func (u *User) GetResources() (*User, error) {
} }
// return user // return user
return u, nil
return &u.Resources, nil
} }

+ 6
- 0
services/gamesrv/gamesrv.go

@ -29,6 +29,12 @@ func (srv Service) CreatePlanet(userId bson.ObjectId) (*models.SolarSystem, *mod
Size: size, Size: size,
Name: name, Name: name,
OwnerId: userId, OwnerId: userId,
Buildings: models.BuildingsList{
MetalMine: 1,
CrystalMine: 1,
DeuteriumMine: 1,
EnergyMine: 1,
},
} }
err := srv.db.Planets.Insert(newPlanet) err := srv.db.Planets.Insert(newPlanet)
if err != nil { if err != nil {

+ 21
- 3
services/usersrv/usersrv.go

@ -6,18 +6,21 @@ import (
"github.com/arnaucube/gogame/database" "github.com/arnaucube/gogame/database"
"github.com/arnaucube/gogame/models" "github.com/arnaucube/gogame/models"
"github.com/arnaucube/gogame/services/gamesrv"
jwt "github.com/dgrijalva/jwt-go" jwt "github.com/dgrijalva/jwt-go"
"golang.org/x/crypto/bcrypt" "golang.org/x/crypto/bcrypt"
"gopkg.in/mgo.v2/bson" "gopkg.in/mgo.v2/bson"
) )
type Service struct { type Service struct {
db *database.Db
db *database.Db
gamesrv *gamesrv.Service
} }
func New(db *database.Db) *Service {
func New(db *database.Db, gameservice *gamesrv.Service) *Service {
return &Service{ return &Service{
db,
db: db,
gamesrv: gameservice,
} }
} }
@ -42,6 +45,12 @@ func (srv Service) Register(name, password, email string) (*models.User, error)
return nil, err return nil, err
} }
user, err := models.NewUser(srv.db, name, hashedPassword, email) user, err := models.NewUser(srv.db, name, hashedPassword, email)
if err != nil {
return nil, err
}
_, _, err = srv.gamesrv.CreatePlanet(user.Id)
return user, err return user, err
} }
@ -73,6 +82,15 @@ func (srv Service) Login(email, password string) (*string, *models.User, error)
return &tokenString, user, err return &tokenString, user, err
} }
func (srv Service) GetUserById(userid string) (*models.User, error) {
var userDb models.UserDb
err := srv.db.Users.Find(bson.M{"_id": bson.ObjectIdHex(userid)}).One(&userDb)
if err != nil {
return nil, err
}
return models.UserDbToUser(srv.db, userDb), nil
}
// func (srv Service) GetUser(id bson.ObjectId) (*models.User, error) { // func (srv Service) GetUser(id bson.ObjectId) (*models.User, error) {
// // update user stats // // update user stats
// user := getUserFromDB // user := getUserFromDB

+ 13
- 4
test/test.py

@ -7,10 +7,9 @@ import requests
import provoj import provoj
import time import time
import subprocess
subprocess.check_call(["mongo", "gogame", "--eval", "'db.dropDatabase()'"])
import os
os.system("mongo gogame --eval 'db.dropDatabase()'")
time.sleep(1)
URL = "http://127.0.0.1:5000" URL = "http://127.0.0.1:5000"
@ -26,7 +25,6 @@ t.rStatus("post /register", r)
jsonR = r.json() jsonR = r.json()
print(jsonR) print(jsonR)
time.sleep(1)
loginData = { loginData = {
"email": "user00@email.com", "email": "user00@email.com",
@ -37,6 +35,17 @@ t.rStatus("post /login", r)
jsonR = r.json() jsonR = r.json()
print(jsonR) print(jsonR)
userid = jsonR["user"]["id"]
r = requests.get(URL + "/resources/"+ userid)
t.rStatus("get /resources", r)
jsonR = r.json()
print(jsonR)
time.sleep(4)
r = requests.get(URL + "/resources/"+ userid)
t.rStatus("get /resources", r)
jsonR = r.json()
print(jsonR)
t.printScores() t.printScores()

Loading…
Cancel
Save