diff --git a/packages/googlecloud/functions/getanswer/main.py b/packages/googlecloud/functions/getanswer/main.py index cad32cab..4e999863 100644 --- a/packages/googlecloud/functions/getanswer/main.py +++ b/packages/googlecloud/functions/getanswer/main.py @@ -22,9 +22,9 @@ supabase_key = os.environ.get("SUPABASE_SERVICE_KEY_STAGING") supabase = create_client(supabase_url, supabase_key) -def update_supabase(response, query, response_type): +def update_supabase(response, query, response_type, card_id): try: - response = supabase.table('cards').insert({'title': query, 'card_type': response_type, 'responses': response}).execute() + response = supabase.table('cards').update({'title': query, 'card_type': response_type, 'responses': response}).eq('id', card_id).execute() logging.info("Data successfully inserted into Supabase") except Exception as e: logging.error(f"Failed to update Supabase: {e}") @@ -68,6 +68,7 @@ def getanswer(request): query = parse_field(request_json, "query") response_type = parse_field(request_json, "response_type") + card_id = parse_field(request_json, "card_id") else: raise ValueError("Unknown content type: {}".format(content_type)) @@ -76,7 +77,7 @@ def getanswer(request): answer = answer_query(query, response_type, voting_roll_df, db_general, db_in_depth) # Update Supabase instead of returning the answer to the client - update_supabase(answer, query, response_type) + update_supabase(answer, query, response_type, card_id) end = time.time() elapsed = math.ceil(end - start) diff --git a/packages/web/components/NewQuery.tsx b/packages/web/components/NewQuery.tsx index 7e514b47..700cd45b 100644 --- a/packages/web/components/NewQuery.tsx +++ b/packages/web/components/NewQuery.tsx @@ -65,8 +65,8 @@ export default function NewQuery() { // Start processing question const answerResp = await fetch(apiEndpoint, { method: "POST", - // Pass responseMode to your API endpoint - body: JSON.stringify({ query, response_type: cardType }), + // Pass responseMode to your API endpoint + body: JSON.stringify({ query, response_type: cardType, card_id: newCard.id }), mode: "cors", headers: { "Content-Type": "application/json", @@ -117,26 +117,31 @@ export default function NewQuery() { if (!card) { return; } - + const channel = (supabase.channel(`cards:id=eq.${card.id}`) as any) .on( "postgres_changes", { - event: "INSERT", + event: "UPDATE", schema: "public", }, (payload: SupabaseRealtimePayload) => { - if (payload.new.id === card.id) { - setCard((prevCard) => ({ ...prevCard, ...payload.new })); + if (payload.new.responses !== payload.old.responses) { + setCard(prevCard => { + if (!prevCard) { + return null; + } + return { ...prevCard, responses: payload.new.responses }; + }); } - } - ) + }) .subscribe(); - + return () => { channel.unsubscribe(); }; }, [card]); + const submitQuery = async (e?: React.FormEvent) => { e?.preventDefault();