Skip to content

Commit

Permalink
debug 1
Browse files Browse the repository at this point in the history
  • Loading branch information
Firebird1029 committed Mar 16, 2024
1 parent 12906d0 commit 6ce0bd6
Show file tree
Hide file tree
Showing 5 changed files with 103 additions and 102 deletions.
99 changes: 93 additions & 6 deletions api/index.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,98 @@
"""Main code to start the API server."""
"""Server code for the backend API."""

# don't lint TODOs
# pylint: disable=fixme

from server import app
from flask import Flask, request
from gotrue.errors import AuthApiError
from flask_restful import Resource, Api, abort
from postgrest.exceptions import APIError
from db import supabase

if __name__ == "__main__":
app.secret_key = "super secret key" # TODO change key, move to separate file
app.config["SESSION_TYPE"] = "filesystem" # TODO change to something else in future
app.run()
# Setup Flask app and API
# TODO setup CORS
app = Flask(__name__)
app.secret_key = "super secret key" # TODO change key, move to separate file
app.config["SESSION_TYPE"] = "filesystem" # TODO change to something else in future
api = Api(app)


class Ping(Resource):
"""API route to check if the server is running."""

def get(self):
"""Return pong for a successful ping."""
return "pong"


api.add_resource(Ping, "/api/ping")


def check_auth(req, user_id):
"""Check if the user is authorized to perform the action."""
session = req["session"]["data"]["session"]
access_token = session["access_token"]
refresh_token = session["refresh_token"]

try:
# set auth session
supabase.auth.set_session(access_token, refresh_token)

# confirm that the session user matches the SQL row user
res = supabase.auth.get_user(access_token)
user = res.user
if user.id != user_id:
abort(403, message="You are not authorized to perform this action.")
except AuthApiError as e:
abort(403, message=e.message)


class NewGame(Resource):
"""New Game"""

def post(self):
"""Create a new game."""
req = request.get_json()
check_auth(req, req["user_id"])

try:
name, game_type, details = req["name"], req["type"], req["details"]

# insert row into games table in Supabase
res = (
supabase.table("games")
.insert(
{
"owner": req["user_id"],
"name": name,
"type": game_type,
"details": details,
}
)
.execute()
)

return {"success": True, "data": res.data}
except APIError as e:
return {
"success": False,
"message": e.message,
}, 500


api.add_resource(NewGame, "/api/g/create")


class Game(Resource):
"""Existing Game"""

def get(self, url_tag):
"""Get a game by its URL tag."""
try:
res = supabase.table("games").select("*").eq("url_tag", url_tag).execute()
return {"success": True, "data": res.data, "count": len(res.data)}
except APIError as e:
return {"success": False, "message": e.message, "count": 0}, 500


api.add_resource(Game, "/api/g/<string:url_tag>")
96 changes: 0 additions & 96 deletions api/server.py

This file was deleted.

2 changes: 2 additions & 0 deletions src/app/g/[slug]/page.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,10 @@ export default function GamePage({ params: { slug } }) {
const [game, setGame] = useState(null);

useEffect(() => {
console.log("slug:", slug);
getGame(slug)
.then((res) => {
console.log("TEST", res);
if (res.success) {
if (res.count > 0) {
setGame(res.data[0]); // return game that matches url tag
Expand Down
5 changes: 5 additions & 0 deletions src/services/apiService.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,19 @@ const supabase = createClient();

// Get Game
async function getGame(gameUrlTag) {
console.log(1);
try {
const res = await api.get(`/g/${gameUrlTag}`);
console.log(2);
if (res.data && res.data.success) {
// successful data
console.log(3);
return res.data;
}
console.log(4);
throw new Error("Failed to retrieve game. Please try again.");
} catch (e) {
console.log(5);
return {
success: false,
message: e.response ? e.response.data.message : e.message || e,
Expand Down
3 changes: 3 additions & 0 deletions vercel.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"rewrites": [{ "source": "/api/(.*)", "destination": "/api/index" }]
}

0 comments on commit 6ce0bd6

Please sign in to comment.