add groups field on front

This commit is contained in:
rick 2022-10-21 20:09:10 +02:00
parent 6b4acb5913
commit ba2d42be9e
Signed by: Rick
GPG key ID: 4A6223D66294EB20
8 changed files with 216 additions and 128 deletions

35
controllers/game.go Normal file
View file

@ -0,0 +1,35 @@
package controllers
import (
"cds/dao"
"fmt"
"github.com/gofiber/fiber/v2"
"go.mongodb.org/mongo-driver/mongo"
)
// @Summary Renvoie les informations sur un jeu.
// @Produce json
// @Success 200 {object} models.Game
// @Failure 403
// @Failure 404
// @Failure 500
// @Router /games/{id} [get]
func GetGameById(c *fiber.Ctx) error {
token := c.Cookies("token", "")
if token == "" {
return c.SendStatus(fiber.StatusForbidden)
} else {
id := c.Params("id")
game, err := dao.GetGameById(id)
if err == mongo.ErrNoDocuments {
return c.SendStatus(fiber.StatusNotFound)
} else if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
"error": fmt.Sprint(err),
})
} else {
return c.Status(fiber.StatusOK).JSON(game)
}
}
}

View file

@ -15,3 +15,5 @@ wasm-bindgen-futures = "0.4"
gloo-storage = "0.2.2"
patternfly-yew = "0.2.0"
wasm-logger = "0.2.0"
log = "0.4.17"

View file

@ -16,6 +16,8 @@ struct User {
level: u32,
money: u32,
moneylimit: u32,
steamid: String,
discordid: String,
discordname: String,
}
@ -34,14 +36,11 @@ enum Route {
#[function_component(About)]
fn about() -> Html {
let _history = use_history().unwrap();
//LocalStorage::set("test", "coucou");
let test: String = LocalStorage::get("test").unwrap_or(String::from("nop"));
//let onclick = Callback::once(move |_| history.push(Route::Home));
html! {
<>
<h1>{ "À propos" }</h1>
<p>{ test }</p>
//<a {onclick}>{ "Index" }</a>
</>
}
}
@ -135,18 +134,28 @@ impl Component for Home {
});
}
let onclick = ctx.link().callback(|_| TestMessage::Test);
//let onclick = ctx.link().callback(|_| TestMessage::Test);
html! {
<>
<ToastViewer />
if let Some(user) = &self.user {
<h1>{ format!("Bienvenue {} !", user.discordname) }</h1>
if user.discordid.is_empty() {
<p><a href="/login/discord">{ "SE CONNECTER VIA DISCORD ICI" }</a></p>
}
if user.steamid.is_empty() {
<p><a href="/login/steam">{ "SE CONNECTER VIA STEAM ICI" }</a></p>
}
<div>
<ListGroups id={user.id.clone()} />
</div>
} else {
<p><a href="/login/discord">{ "SE CONNECTER VIA DISCORD ICI" }</a></p>
<p><a href="/login/steam">{ "SE CONNECTER VIA STEAM ICI" }</a></p>
}
<button {onclick}>{"test"}</button>
//<button {onclick}>{"test"}</button>
</>
}
}
@ -193,103 +202,159 @@ impl Component for Home {
}
}
/*
#[function_component(Home)]
fn home() -> Html {
// check if the cookie is set
let state = use_state(|| StatusConnection::NotConnected);
//let connected = use_state_eq(|| false);
{
let state = state.clone();
use_effect(move || {
//let connected = connected.clone();
wasm_bindgen_futures::spawn_local(async move {
if let Ok(resp) = Request::get("/api/users/current").send().await {
if resp.ok() {
let json: Result<User, Error> = resp.json().await;
if let Ok(json) = json {
LocalStorage::set("auth", json);
state.set(StatusConnection::UpdateConnection);
} else if let Err(err) = json {
LocalStorage::delete("auth");
state.set(StatusConnection::Error(err.to_string()));
}
} else {
state.set(StatusConnection::NotConnected);
}
}
});
|| ()
});
}
/*
let client = Client::new();
if let Ok(resp) = client.get("/users/current").send() {
if resp.status() == StatusCode::OK {
if let Ok(json) = resp.json::<User>() {
LocalStorage::set("auth", json);
}
}
}
*/
let _user: Result<User, StorageError> = LocalStorage::get("auth");
if let Ok(user) = LocalStorage::get("auth") {
if *state == StatusConnection::UpdateConnection {
let state = state.clone();
state.set(StatusConnection::Connected(user));
}
}
match &*state {
StatusConnection::NotConnected => {
html! {
<>
<p><a href="/login/discord">{ "SE CONNECTER VIA DISCORD ICI" }</a></p>
<p><a href="/login/steam">{ "SE CONNECTER VIA STEAM ICI" }</a></p>
</>
}
},
StatusConnection::UpdateConnection => {
html!{ <p>{ "Connexion en cours..." }</p> }
},
StatusConnection::Connected(user) => html!{ <h1>{ format!("Bienvenue {} !", user.discordname) }</h1> },
StatusConnection::Error(err) => {
html! {
<>
<h1>{ "Erreur !!" }</h1>
<p>{ err }</p>
</>
}
}
}
/*
let tmp: Result<User, StorageError> = LocalStorage::get("auth");
if let Ok(o) = tmp {
} else {
let check_auth = use_state(|| None::<User>);
wasm_bindgen_futures::spawn_local(async move {
if let Ok(resp) = Request::get("/users/current").send().await {
if let Ok(user) = resp.json().await {
check_auth.set(Some(user))
}
};
});
if let Some(user) = (*check_auth).clone() {
LocalStorage::set("auth", user);
}
//html! { "Vous êtes connecté !" }
}
*/
#[derive(Deserialize, Serialize)]
struct Game {
name: String,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
struct Group {
pub name: String,
pub game: String,
}
impl Group {
pub async fn get_game_name(&mut self) {
match Request::get(&format!("/api/games/{}", self.game))
.send()
.await
{
Ok(resp) => {
if resp.ok() {
let json: Result<Game, Error> = resp.json().await;
match json {
Ok(json) => self.game = json.name,
Err(err) => log::info!("{}", err.to_string()),
}
}
}
Err(err) => (),
}
}
}
struct ListGroups {
idUser: String,
groups: Vec<Group>,
nb_show: usize,
}
#[derive(PartialEq, Properties)]
struct PropGroups {
id: String,
}
#[derive(PartialEq)]
enum MsgListGroups {
Done(Vec<Group>),
Info(String, String),
Error(String, String),
More,
}
impl Component for ListGroups {
type Message = MsgListGroups;
type Properties = PropGroups;
fn create(ctx: &Context<Self>) -> Self {
Self {
idUser: ctx.props().id.clone(),
groups: Vec::new(),
nb_show: 0,
}
}
fn view(&self, ctx: &Context<Self>) -> Html {
if self.groups.len() == 0 {
let id = self.idUser.clone();
ctx.link().send_future(async move {
match Request::get(&format!("/api/users/{}/groups", id))
.send()
.await
{
Ok(resp) => {
if resp.ok() {
let json: Result<Vec<Group>, Error> = resp.json().await;
match json {
Ok(mut json) => {
for item in json.iter_mut() {
item.get_game_name().await;
}
return MsgListGroups::Done(json);
}
Err(err) => {
log::info!("{}", err.to_string());
()
}
}
}
}
Err(err) => (),
};
MsgListGroups::Info(String::from("Ok"), String::new())
});
}
let onclick = ctx.link().callback(|_| MsgListGroups::More);
html! {
<>
<ToastViewer />
if self.groups.len() > 0 {
{
self.groups[..self.nb_show].iter().map(|group| { html!{
<p>{ group.name.clone() }</p>
} }).collect::<Html>()
}
if self.nb_show < self.groups.len() {
<button onclick={onclick}>{ "Plus de groupes" }</button>
}
} else {
<p>{ "Vous n'êtes dans aucun groupe." }</p>
}
//<p>{ "coucou" }</p>
</>
}
}
fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
MsgListGroups::Info(title, body) => {
if let Some(parent) = ctx.link().get_parent() {
(parent.clone())
.downcast::<Home>()
.send_message(TestMessage::Toast(ToastType::Info(ToastFields {
title,
body,
})))
}
}
MsgListGroups::Error(title, body) => {
if let Some(parent) = ctx.link().get_parent() {
(parent.clone())
.downcast::<Home>()
.send_message(TestMessage::Toast(ToastType::Error(ToastFields {
title,
body,
})))
}
}
MsgListGroups::Done(groups) => {
self.groups = groups;
return true;
}
MsgListGroups::More => {
self.nb_show += 3;
if self.nb_show > self.groups.len() {
self.nb_show -= self.nb_show - self.groups.len();
}
return true;
}
}
false
}
}
*/
fn switch(route: &Route) -> Html {
match route {
@ -307,39 +372,13 @@ fn app() -> Html {
<Switch<Route> render={Switch::render(switch)} />
</BrowserRouter>
}
/*
html! {
<div>
<h1>{ "Chasseurs De Succès" }</h1>
<h2>{ "Bienvenue sur le site pour gérer les groupes de chasses" }</h2>
</div>
}
*/
}
fn main() {
wasm_logger::init(wasm_logger::Config::default());
yew::start_app::<App>();
}
/*
#[derive(Clone, Deserialize, PartialEq, Serialize)]
struct Group {
name: String,
}
struct ListGroups {
list: Vec<Group>,
}
impl Component for ListGroups {
fn create(_ctx: &Context<Self>) -> Self {
Self {
}
}
}
*/
#[function_component(Test)]
fn test() -> Html {
let test = use_state(|| String::from(""));

View file

@ -27,6 +27,7 @@ func setupRoutes(app *fiber.App) {
api := app.Group("/api")
routes.GroupRoute(api.Group("/groups"))
routes.UserRoute(api.Group("/users"))
routes.GameRoute(api.Group("/games"))
app.Get("/swagger/*", swagger.HandlerDefault)
app.Get("/login/:provider", goth_fiber.BeginAuthHandler)

View file

@ -8,7 +8,7 @@ type Game struct {
HasAchievements bool `bson:"hasAchievements"`
IsCoop bool `bson:"isCoop"`
IsMulti bool `bson:"isMulti"`
Name string `bson:"name"`
Name string `bson:"name" json:"name"`
}
func NewGame() *Game {

View file

@ -4,11 +4,11 @@ import "go.mongodb.org/mongo-driver/bson/primitive"
type Group struct {
Id primitive.ObjectID `bson:"_id", omitempty`
Name string `bson:"name"`
Name string `bson:"name" json:"name"`
Desc string `bson:"desc"`
NbMax int `bson:"nbMax"`
Members []primitive.ObjectID `bson:"members"`
Game primitive.ObjectID `bson:"game"`
Game primitive.ObjectID `bson:"game" json:"game"`
}
func NewGroup() *Group {

View file

@ -11,8 +11,8 @@ type User struct {
Level uint `bson:"level" json:"level"`
Money uint `bson:"money" json:"money"`
MoneyLimit uint `bson:"moneyLimit" json:"moneylimit"`
DiscordId string `bson:"userId,omitempty" json:"userid"`
SteamId string `bson:"steamId,omitempty" json:"steamid"`
DiscordId string `bson:"userId" json:"discordid"`
SteamId string `bson:"steamId" json:"steamid"`
DiscordName string `bson:"username,omitempty" json:"discordname"`
}

11
routes/game.go Normal file
View file

@ -0,0 +1,11 @@
package routes
import (
"cds/controllers"
"github.com/gofiber/fiber/v2"
)
func GameRoute(route fiber.Router) {
route.Get("/:id", controllers.GetGameById)
}