Repository navigation
feat: RSS-SE-22 implement request execution in viewer - #32
FierceSloth merged 7 commits into
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (6)
📝 WalkthroughWalkthroughВ форму Try It Out добавлены построение HTTP-запроса, отправка через прокси, отображение ответа и генерация curl-команды. ChangesВыполнение запросов Try It Out
Estimated code review effort: 3 (Moderate) | ~25 minutes Sequence Diagram(s)sequenceDiagram
participant User
participant TryItOutForm
participant fetchViaProxy
participant EndpointServer
User->>TryItOutForm: Отправка формы
TryItOutForm->>fetchViaProxy: Сформированные URL, headers и body
fetchViaProxy->>EndpointServer: HTTP-запрос
EndpointServer-->>fetchViaProxy: Статус, заголовки и тело
fetchViaProxy-->>TryItOutForm: Ответ
TryItOutForm-->>User: Результат и curl-команда
Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (1)
src/widgets/swagger-viewer/ui/swagger-viewer.tsx (1)
31-52: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winДублирование получения первого сервера схемы.
serverUrlвычисляется на строке 31, но блок "Base Server" (строки 47-52) заново обращается кschema.servers?.[0]/schema.servers[0].urlвместо использования уже посчитанногоserverUrl. Стоит унифицировать, чтобы не было двух независимых источников одного и того же значения.♻️ Пример правки
- {schema.servers?.[0] && ( + {serverUrl && ( <div className={styles.serverBlock}> <p className={styles.serverLabel}>Base Server</p> - <Badge color="green">{schema.servers[0].url}</Badge> + <Badge color="green">{serverUrl}</Badge> </div> )}🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/widgets/swagger-viewer/ui/swagger-viewer.tsx` around lines 31 - 52, Use the existing serverUrl value in the Base Server rendering within the Swagger viewer component instead of repeatedly accessing schema.servers?.[0] and schema.servers[0].url. Update the conditional and displayed badge to rely on serverUrl while preserving the current behavior when no server URL exists.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@messages/en.json`:
- Around line 51-53: Добавьте ключи локализации status, headers и body в оба
файла переводов, затем в try-it-out-form.tsx замените литералы Status, Headers и
Body на вызовы t(...) с соответствующими ключами, сохранив существующие
локализованные заголовок и состояние выполнения.
In `@src/entities/endpoint/ui/try-it-out-form/try-it-out-form.tsx`:
- Around line 149-164: Локализуйте метки результата в JSX-блоке `result`:
замените захардкоженные `Status:`, `Headers` и `Body` на вызовы существующей
функции `t`, добавив или используя соответствующие ключи переводов в формате
проекта. Сохраните отображение значения `result.status` и содержимого заголовков
и тела без изменений.
- Around line 88-94: Update the catch block in the try-it-out submission flow to
preserve and surface the caught error message, while localizing the fallback
text through the component’s existing t(...) translation mechanism. Replace the
hard-coded English body and retain status 0 and empty headers for failures,
including buildUrl and network errors.
- Around line 56-79: Добавьте проверку targetUrl в обработчик fetchViaProxy
перед выполнением исходящего запроса: разрешайте только хосты из явного
allowlist либо блокируйте localhost, loopback, private и metadata-подсети для
HTTP(S). Отклоняйте запрещённые адреса до сетевого запроса, сохраняя текущую
передачу разрешённых targetUrl.
---
Nitpick comments:
In `@src/widgets/swagger-viewer/ui/swagger-viewer.tsx`:
- Around line 31-52: Use the existing serverUrl value in the Base Server
rendering within the Swagger viewer component instead of repeatedly accessing
schema.servers?.[0] and schema.servers[0].url. Update the conditional and
displayed badge to rely on serverUrl while preserving the current behavior when
no server URL exists.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 813947ef-c891-417e-8497-ae1958c840f9
📒 Files selected for processing (11)
messages/en.jsonmessages/ru.jsonsrc/entities/endpoint/ui/endpoint-list/endpoint-list.tsxsrc/entities/endpoint/ui/try-it-out-form/build-headers.tssrc/entities/endpoint/ui/try-it-out-form/build-url.tssrc/entities/endpoint/ui/try-it-out-form/format-response-body.tssrc/entities/endpoint/ui/try-it-out-form/get-form-string-value.tssrc/entities/endpoint/ui/try-it-out-form/get-parameter-field-name.tssrc/entities/endpoint/ui/try-it-out-form/try-it-out-form.module.scsssrc/entities/endpoint/ui/try-it-out-form/try-it-out-form.tsxsrc/widgets/swagger-viewer/ui/swagger-viewer.tsx
| "invalidJson": "Invalid JSON format", | ||
| "response": "Response", | ||
| "executing": "Executing..." |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Добавьте локализацию всех подписей панели ответа.
try-it-out-form.tsx всё ещё выводит Status, Headers и Body как литералы. Поэтому добавленные ключи локализуют только заголовок и состояние выполнения, а русская версия панели останется частично на английском. Добавьте ключи status, headers и body в оба файла локализации и используйте t(...).
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@messages/en.json` around lines 51 - 53, Добавьте ключи локализации status,
headers и body в оба файла переводов, затем в try-it-out-form.tsx замените
литералы Status, Headers и Body на вызовы t(...) с соответствующими ключами,
сохранив существующие локализованные заголовок и состояние выполнения.
| const targetUrl = buildUrl({ | ||
| serverUrl, | ||
| path: endpoint.path, | ||
| parameters, | ||
| formData, | ||
| }); | ||
|
|
||
| const headers = buildHeaders({ | ||
| parameters, | ||
| formData, | ||
| contentType, | ||
| }); | ||
|
|
||
| const requestBodyValue = getFormStringValue(formData, 'requestBody').trim(); | ||
|
|
||
| const method = endpoint.method.toUpperCase(); | ||
|
|
||
| const shouldSendBody = method !== 'GET' && method !== 'HEAD' && requestBodyValue.length > 0; | ||
|
|
||
| const response = await fetchViaProxy(targetUrl, { | ||
| method, | ||
| headers, | ||
| body: shouldSendBody ? requestBodyValue : undefined, | ||
| }); |
There was a problem hiding this comment.
🔒 Security & Privacy | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Найти и изучить реализацию проксирующего роута
fd -i 'proxy' --type f
rg -n -C6 'targetUrl' --type=tsRepository: FierceSloth/swagger-editor-app
Length of output: 277
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '\n== file list ==\n'
git ls-files 'app/api/proxy/*' 'proxy.ts' 'src/shared/api/proxy-client.ts' 'src/shared/api/proxy-client.test.ts'
printf '\n== outline: app/api/proxy/getProxyHeaders.ts ==\n'
ast-grep outline app/api/proxy/getProxyHeaders.ts --view expanded || true
printf '\n== outline: proxy.ts ==\n'
ast-grep outline proxy.ts --view expanded || true
printf '\n== outline: src/shared/api/proxy-client.ts ==\n'
ast-grep outline src/shared/api/proxy-client.ts --view expanded || true
printf '\n== outline: src/shared/api/proxy-client.test.ts ==\n'
ast-grep outline src/shared/api/proxy-client.test.ts --view expanded || true
printf '\n== search targetUrl / proxy route ==\n'
rg -n -C4 'targetUrl|proxy' app api src/shared -g '!**/node_modules/**' || trueRepository: FierceSloth/swagger-editor-app
Length of output: 6802
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '\n== app/api/proxy/route.ts ==\n'
cat -n app/api/proxy/route.ts
printf '\n== app/api/proxy/getProxyHeaders.ts ==\n'
cat -n app/api/proxy/getProxyHeaders.ts
printf '\n== src/shared/api/proxy-client.ts ==\n'
cat -n src/shared/api/proxy-client.tsRepository: FierceSloth/swagger-editor-app
Length of output: 3577
Ограничить /api/proxy списком допустимых хостов
Сейчас роут принимает любой http(s) targetUrl и может проксировать запросы на внутренние адреса/metadata endpoints. Нужен allowlist или явная блокировка приватных/локальных подсетей.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/entities/endpoint/ui/try-it-out-form/try-it-out-form.tsx` around lines 56
- 79, Добавьте проверку targetUrl в обработчик fetchViaProxy перед выполнением
исходящего запроса: разрешайте только хосты из явного allowlist либо блокируйте
localhost, loopback, private и metadata-подсети для HTTP(S). Отклоняйте
запрещённые адреса до сетевого запроса, сохраняя текущую передачу разрешённых
targetUrl.
| } catch { | ||
| setResult({ | ||
| status: 0, | ||
| headers: {}, | ||
| body: 'Request failed. Please try again.', | ||
| }); | ||
| } finally { |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Общий catch теряет причину сбоя и не локализован.
Любая ошибка (включая buildUrl's Error('Server URL is missing'), сетевые сбои и т.п.) сводится к одинаковому статусу 0 и жёстко закодированной английской строке 'Request failed. Please try again.', хотя остальные тексты в компоненте локализуются через t(...). Это скрывает реальную причину сбоя от пользователя и не будет переведено на русский.
💬 Пример правки
} catch {
setResult({
status: 0,
headers: {},
- body: 'Request failed. Please try again.',
+ body: t('requestFailed'),
});
} finally {📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| } catch { | |
| setResult({ | |
| status: 0, | |
| headers: {}, | |
| body: 'Request failed. Please try again.', | |
| }); | |
| } finally { | |
| } catch { | |
| setResult({ | |
| status: 0, | |
| headers: {}, | |
| body: t('requestFailed'), | |
| }); | |
| } finally { |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/entities/endpoint/ui/try-it-out-form/try-it-out-form.tsx` around lines 88
- 94, Update the catch block in the try-it-out submission flow to preserve and
surface the caught error message, while localizing the fallback text through the
component’s existing t(...) translation mechanism. Replace the hard-coded
English body and retain status 0 and empty headers for failures, including
buildUrl and network errors.
| {result && ( | ||
| <div className={styles.result}> | ||
| <div className={styles.titleBlock}> | ||
| <h4 className={styles.resultTitle}>{t('response')}</h4> | ||
| <div>Status: {result.status}</div> | ||
| </div> | ||
| <div className={styles.block}> | ||
| <p className={styles.responseLabel}>Headers</p> | ||
| <CodeEditor value={JSON.stringify(result.headers, null, 2)} format="json" readonly transparent hideLines /> | ||
| </div> | ||
| <div className={styles.block}> | ||
| <p className={styles.responseLabel}>Body</p> | ||
| <CodeEditor value={result.body} format="json" readonly transparent hideLines /> | ||
| </div> | ||
| </div> | ||
| )} |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Метки результата не локализованы.
"Status: ", "Headers", "Body" (строки 153, 156, 160) захардкожены на английском, в то время как заголовок t('response') и кнопки уже используют next-intl. Судя по описанию PR, локализация состояний выполнения и результата — часть этой задачи; эти три строки, видимо, были пропущены.
💬 Пример правки
- <div>Status: {result.status}</div>
+ <div>{t('status')}: {result.status}</div>
...
- <p className={styles.responseLabel}>Headers</p>
+ <p className={styles.responseLabel}>{t('headers')}</p>
...
- <p className={styles.responseLabel}>Body</p>
+ <p className={styles.responseLabel}>{t('body')}</p>📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| {result && ( | |
| <div className={styles.result}> | |
| <div className={styles.titleBlock}> | |
| <h4 className={styles.resultTitle}>{t('response')}</h4> | |
| <div>Status: {result.status}</div> | |
| </div> | |
| <div className={styles.block}> | |
| <p className={styles.responseLabel}>Headers</p> | |
| <CodeEditor value={JSON.stringify(result.headers, null, 2)} format="json" readonly transparent hideLines /> | |
| </div> | |
| <div className={styles.block}> | |
| <p className={styles.responseLabel}>Body</p> | |
| <CodeEditor value={result.body} format="json" readonly transparent hideLines /> | |
| </div> | |
| </div> | |
| )} | |
| {result && ( | |
| <div className={styles.result}> | |
| <div className={styles.titleBlock}> | |
| <h4 className={styles.resultTitle}>{t('response')}</h4> | |
| <div>{t('status')}: {result.status}</div> | |
| </div> | |
| <div className={styles.block}> | |
| <p className={styles.responseLabel}>{t('headers')}</p> | |
| <CodeEditor value={JSON.stringify(result.headers, null, 2)} format="json" readonly transparent hideLines /> | |
| </div> | |
| <div className={styles.block}> | |
| <p className={styles.responseLabel}>{t('body')}</p> | |
| <CodeEditor value={result.body} format="json" readonly transparent hideLines /> | |
| </div> | |
| </div> | |
| )} |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/entities/endpoint/ui/try-it-out-form/try-it-out-form.tsx` around lines
149 - 164, Локализуйте метки результата в JSX-блоке `result`: замените
захардкоженные `Status:`, `Headers` и `Body` на вызовы существующей функции `t`,
добавив или используя соответствующие ключи переводов в формате проекта.
Сохраните отображение значения `result.status` и содержимого заголовков и тела
без изменений.
- The logic for generating a cURL string based on the data entered in Try-It-Out. A button with copy-to-clipboard functionality.
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/entities/endpoint/ui/try-it-out-form/try-it-out-form.tsx`:
- Around line 74-82: В потоке формирования запроса вокруг requestBodyValue и
shouldSendBody добавьте проверку тела для заголовка application/json до
выполнения сетевого запроса. Парсите непустое JSON-тело и при ошибке валидации
отклоняйте запрос локально с сообщением t('invalidJson'); корректный JSON и
другие типы содержимого должны сохранять текущий путь отправки.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 8f7c5836-bfca-4154-829c-f4c278e3cb0a
📒 Files selected for processing (5)
messages/en.jsonmessages/ru.jsonsrc/entities/endpoint/ui/try-it-out-form/generate-curl-command.tssrc/entities/endpoint/ui/try-it-out-form/try-it-out-form.module.scsssrc/entities/endpoint/ui/try-it-out-form/try-it-out-form.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
- src/entities/endpoint/ui/try-it-out-form/try-it-out-form.module.scss
| const requestBodyValue = getFormStringValue(formData, 'requestBody').trim(); | ||
| const method = endpoint.method.toUpperCase(); | ||
| const shouldSendBody = method !== 'GET' && method !== 'HEAD' && requestBodyValue.length > 0; | ||
|
|
||
| return { | ||
| targetUrl, | ||
| method, | ||
| headers, | ||
| body: shouldSendBody ? requestBodyValue : undefined, |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Проверяйте JSON до выполнения запроса.
Для application/json произвольный текст из формы уходит и в прокси, и в сгенерированный cURL. Некорректный JSON нужно отклонять до сетевого вызова, с локализованным сообщением t('invalidJson').
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/entities/endpoint/ui/try-it-out-form/try-it-out-form.tsx` around lines 74
- 82, В потоке формирования запроса вокруг requestBodyValue и shouldSendBody
добавьте проверку тела для заголовка application/json до выполнения сетевого
запроса. Парсите непустое JSON-тело и при ошибке валидации отклоняйте запрос
локально с сообщением t('invalidJson'); корректный JSON и другие типы
содержимого должны сохранять текущий путь отправки.
📋 Trello Task ID
⚡️ Summary
Write a short report on the work done here. What problem does this PR solve?
🛠 Type of change
feat(New feature)fix(Bug fix)refactor(Code improvement / Refactoring without changing logic)style(Formatting, CSS)docs(Documentation)chore(Configs, Build)test(Testing)📷 Screenshots / GIFs
REQUIRED for UI changes. Attach images or GIFs here. If no UI changes, delete this section.
Summary by CodeRabbit
serverUrl, path/query параметров, заголовков и тела (кромеGET/HEAD), а затем отображает статус, заголовки и форматированное тело ответа.curlи копирование в буфер обмена с подтверждением.curl(RU/EN).serverUrlавтоматически берется из спецификации API и используется при построении целевого URL.curlв «Try It Out», а также небольшое улучшение стилей accordion.