habulaj commited on
Commit
917d393
·
verified ·
1 Parent(s): f28d898

Update routes/users.py

Browse files
Files changed (1) hide show
  1. routes/users.py +62 -9
routes/users.py CHANGED
@@ -135,28 +135,81 @@ async def get_user_name(
135
  user_token: str = Header(None, alias="User-key")
136
  ):
137
  """
138
- Endpoint para obter o nome de um usuário específico a partir do ID.
 
139
  """
140
  try:
141
  await verify_admin_token(user_token)
142
 
143
- query = f"{SUPABASE_URL}/rest/v1/User?select=name&id=eq.{user_id}"
 
 
 
 
 
144
  headers = SUPABASE_HEADERS.copy()
145
  headers["Accept"] = "application/json; charset=utf-8"
146
 
147
  async with aiohttp.ClientSession() as session:
148
- async with session.get(query, headers=headers) as response:
149
- if response.status != 200:
150
- raise HTTPException(status_code=500, detail="Erro ao consultar o Supabase")
 
 
 
 
 
 
 
 
151
 
152
- data = await response.json()
153
- if not data:
154
  raise HTTPException(status_code=404, detail="Usuário não encontrado")
155
 
156
- return {"name": data[0]["name"]}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157
 
158
  except HTTPException as he:
159
  raise he
160
  except Exception as e:
161
- logger.error(f"❌ Erro ao buscar usuário: {str(e)}")
162
  raise HTTPException(status_code=500, detail="Erro interno do servidor")
 
135
  user_token: str = Header(None, alias="User-key")
136
  ):
137
  """
138
+ Endpoint para obter informações de um usuário específico a partir do ID,
139
+ incluindo seus feeds e uma imagem de portfólio para cada feed.
140
  """
141
  try:
142
  await verify_admin_token(user_token)
143
 
144
+ # Buscar informações básicas do usuário
145
+ user_query = f"{SUPABASE_URL}/rest/v1/User?select=name,avatar,role&id=eq.{user_id}"
146
+
147
+ # Buscar feeds do usuário
148
+ feeds_query = f"{SUPABASE_URL}/rest/v1/Feeds?select=id,portfolios,created_at,description,urls,user_id&user_id=eq.{user_id}&order=created_at.desc"
149
+
150
  headers = SUPABASE_HEADERS.copy()
151
  headers["Accept"] = "application/json; charset=utf-8"
152
 
153
  async with aiohttp.ClientSession() as session:
154
+ # Fazer as requisições em paralelo
155
+ user_task = session.get(user_query, headers=headers)
156
+ feeds_task = session.get(feeds_query, headers=headers)
157
+
158
+ async with user_task as user_response, feeds_task as feeds_response:
159
+ if user_response.status != 200 or feeds_response.status != 200:
160
+ status = user_response.status if user_response.status != 200 else feeds_response.status
161
+ raise HTTPException(status_code=status, detail="Erro ao consultar o Supabase")
162
+
163
+ user_data = await user_response.json()
164
+ feeds_data = await feeds_response.json()
165
 
166
+ if not user_data:
 
167
  raise HTTPException(status_code=404, detail="Usuário não encontrado")
168
 
169
+ # Processar feeds para buscar imagens de portfólio
170
+ feeds_with_images = []
171
+ for feed in feeds_data:
172
+ feed_info = {
173
+ "id": feed["id"],
174
+ "created_at": feed["created_at"],
175
+ "description": feed["description"],
176
+ "urls": feed["urls"],
177
+ "portfolios": feed["portfolios"]
178
+ }
179
+
180
+ # Verificar se há portfolios associados
181
+ if feed["portfolios"] and len(feed["portfolios"]) > 0:
182
+ # Pegar o primeiro portfolio do array
183
+ first_portfolio_id = feed["portfolios"][0]
184
+
185
+ # Buscar informações da imagem deste portfolio
186
+ portfolio_query = f"{SUPABASE_URL}/rest/v1/Portfolio?select=image_url,blurhash,width,height&id=eq.{first_portfolio_id}"
187
+
188
+ async with session.get(portfolio_query, headers=headers) as portfolio_response:
189
+ if portfolio_response.status == 200:
190
+ portfolio_data = await portfolio_response.json()
191
+
192
+ if portfolio_data and len(portfolio_data) > 0:
193
+ feed_info["thumbnail"] = {
194
+ "image_url": portfolio_data[0]["image_url"],
195
+ "blurhash": portfolio_data[0]["blurhash"],
196
+ "width": portfolio_data[0]["width"],
197
+ "height": portfolio_data[0]["height"]
198
+ }
199
+
200
+ feeds_with_images.append(feed_info)
201
+
202
+ # Construir a resposta completa
203
+ response = {
204
+ "user": user_data[0],
205
+ "feeds": feeds_with_images,
206
+ "feeds_count": len(feeds_with_images)
207
+ }
208
+
209
+ return response
210
 
211
  except HTTPException as he:
212
  raise he
213
  except Exception as e:
214
+ logger.error(f"❌ Erro ao buscar usuário e feeds: {str(e)}")
215
  raise HTTPException(status_code=500, detail="Erro interno do servidor")