refactor: centralize file API URL construction and path resolution (#194)

- Extract getFileApiUrl helper with options interface for type-safe URL building
- Handle paths containing '.' and '..' segments via query parameters
- Remove duplicate URL construction logic from FileBrowser, FilePreview, and FileTree components
- Add getSpecialRoutePathFromRequest helper in backend for consistent path extraction
This commit is contained in:
Chris Scott authored and GitHub committed 2026-04-23 17:21:44 -04:00
1 parent 31755c23f8
commit 7a7090101c
5 files changed
+58 -54

No files matched your search

+12 -3
View File
@@ -13,6 +13,16 @@ function getFilePathFromRequest(c: Context, fallbackPath: string): string {
return c.req.query('path') ?? decodeFilePath(fallbackPath)
}
function getSpecialRoutePathFromRequest(c: Context, routeName: string): string | undefined {
const queryPath = c.req.query('path')
if (queryPath !== undefined) {
return queryPath
}
const match = c.req.path.match(new RegExp(`/api/files/(.+?)/${routeName}$`))
return match?.[1] ? decodeFilePath(match[1]) : undefined
}
export function createFileRoutes() {
const app = new Hono()
@@ -20,8 +30,7 @@ export function createFileRoutes() {
const path = c.req.path
if (path.endsWith('/download-zip')) {
const match = path.match(/\/api\/files\/(.+?)\/download-zip$/)
const userPath = match?.[1] ? decodeFilePath(match[1]) : undefined
const userPath = getSpecialRoutePathFromRequest(c, 'download-zip')
if (!userPath) {
return c.json({ error: 'No path provided' }, 400)
@@ -69,7 +78,7 @@ export function createFileRoutes() {
}
if (path.endsWith('/ignored-paths')) {
const userPath = decodeFilePath(path.replace(/\/api\/files\/(.+?)\/ignored-paths$/, '$1'))
const userPath = getSpecialRoutePathFromRequest(c, 'ignored-paths')
if (!userPath || userPath === '/ignored-paths') {
return c.json({ error: 'No path provided' }, 400)
+34 -10
View File
@@ -3,12 +3,34 @@ import { fetchWrapper, fetchWrapperBlob } from './fetchWrapper'
import { API_BASE_URL } from '@/config'
import type { FileInfo, ChunkedFileInfo, PatchOperation } from '@/types/files'
function getFileApiUrl(path: string): string {
if (path.includes('..')) {
return `${API_BASE_URL}/api/files/?path=${encodeURIComponent(path)}`
interface FileApiUrlOptions {
route?: string
params?: Record<string, string | number | boolean | undefined>
}
function pathRequiresQuery(path: string): boolean {
return path.split('/').some(segment => segment === '.' || segment === '..')
}
export function getFileApiUrl(path: string, options: FileApiUrlOptions = {}): string {
const searchParams = new URLSearchParams()
Object.entries(options.params ?? {}).forEach(([key, value]) => {
if (value !== undefined) {
searchParams.append(key, String(value))
}
})
const routePath = options.route ? `/${options.route}` : ''
if (pathRequiresQuery(path)) {
searchParams.set('path', path)
const query = searchParams.toString()
return `${API_BASE_URL}/api/files${routePath}${query ? `?${query}` : ''}`
}
return `${API_BASE_URL}/api/files/${path.split('/').map(encodeURIComponent).join('/')}`
const encodedPath = path.split('/').map(encodeURIComponent).join('/')
const query = searchParams.toString()
return `${API_BASE_URL}/api/files/${encodedPath}${routePath}${query ? `?${query}` : ''}`
}
async function fetchFile(path: string): Promise<FileInfo> {
@@ -38,7 +60,7 @@ export async function applyFilePatches(path: string, patches: PatchOperation[]):
}
export async function getIgnoredPaths(path: string): Promise<{ ignoredPaths: string[] }> {
return fetchWrapper(`${API_BASE_URL}/api/files/${path}/ignored-paths`)
return fetchWrapper(getFileApiUrl(path, { route: 'ignored-paths' }))
}
export interface DownloadOptions {
@@ -47,11 +69,13 @@ export interface DownloadOptions {
}
export async function downloadDirectoryAsZip(path: string, options?: DownloadOptions): Promise<void> {
const params = new URLSearchParams()
if (options?.includeGit) params.append('includeGit', 'true')
if (options?.includePaths?.length) params.append('includePaths', options.includePaths.join(','))
const url = `${API_BASE_URL}/api/files/${path}/download-zip${params.toString() ? '?' + params.toString() : ''}`
const url = getFileApiUrl(path, {
route: 'download-zip',
params: {
includeGit: options?.includeGit || undefined,
includePaths: options?.includePaths?.length ? options.includePaths.join(',') : undefined,
},
})
const blob = await fetchWrapperBlob(url)
const urlObj = window.URL.createObjectURL(blob)
@@ -10,9 +10,8 @@ import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/u
import { Progress } from '@/components/ui/progress'
import { FolderOpen, Upload, RefreshCw, X } from 'lucide-react'
import type { FileInfo } from '@/types/files'
import { API_BASE_URL } from '@/config'
import { useMobile } from '@/hooks/useMobile'
import { useFile } from '@/api/files'
import { getFileApiUrl, useFile } from '@/api/files'
export interface FileBrowserHandle {
goBack: () => void
@@ -156,19 +155,6 @@ useEffect(() => {
}
}, [initialFileError])
const getFileApiUrl = useCallback((path: string) => {
if (path.includes('..')) {
return `${API_BASE_URL}/api/files/?path=${encodeURIComponent(path)}`
}
const encodedPath = path
.split('/')
.map(segment => encodeURIComponent(segment))
.join('/')
return `${API_BASE_URL}/api/files/${encodedPath}`
}, [])
const loadFiles = useCallback(async (path: string) => {
setLoading(true)
setError(null)
@@ -188,7 +174,7 @@ useEffect(() => {
} finally {
setLoading(false)
}
}, [getFileApiUrl, onDirectoryLoad])
}, [onDirectoryLoad])
const normalizePath = useCallback((path: string) => {
const normalized = path
@@ -276,7 +262,7 @@ useEffect(() => {
} finally {
setLoading(false)
}
}, [getFileApiUrl, onFileSelect, isMobile, onPreviewStateChange])
}, [onFileSelect, isMobile, onPreviewStateChange])
const handleCloseModal = useCallback(() => {
setIsPreviewModalOpen(false)
@@ -312,7 +298,7 @@ useEffect(() => {
} catch (err) {
return err instanceof Error ? err.message : 'Upload failed'
}
}, [currentPath, getFileApiUrl])
}, [currentPath])
const handleUploadItems = useCallback(async (items: UploadItem[]) => {
if (items.length === 0) return
@@ -382,7 +368,7 @@ useEffect(() => {
} catch (err) {
setError(err instanceof Error ? err.message : 'Create failed')
}
}, [currentPath, getFileApiUrl, loadFiles])
}, [currentPath, loadFiles])
const handleDelete = useCallback(async (path: string) => {
try {
@@ -399,7 +385,7 @@ useEffect(() => {
} catch (err) {
setError(err instanceof Error ? err.message : 'Delete failed')
}
}, [currentPath, getFileApiUrl, loadFiles])
}, [currentPath, loadFiles])
const handleRename = useCallback(async (oldPath: string, newPath: string) => {
try {
@@ -417,7 +403,7 @@ useEffect(() => {
} catch (err) {
setError(err instanceof Error ? err.message : 'Rename failed')
}
}, [currentPath, getFileApiUrl, loadFiles])
}, [currentPath, loadFiles])
const handleDragEnter = (e: React.DragEvent) => {
e.preventDefault()
@@ -2,27 +2,14 @@ import { useState, useCallback, useRef, useEffect, memo } from 'react'
import { Button } from '@/components/ui/button'
import { Download, X, Edit3, Save, X as XIcon, WrapText, Eye, Code } from 'lucide-react'
import type { FileInfo } from '@/types/files'
import { API_BASE_URL } from '@/config'
import { getFileApiUrl } from '@/api/files'
import { VirtualizedTextView, type VirtualizedTextViewHandle } from '@/components/ui/virtualized-text-view'
import { MarkdownRenderer } from './MarkdownRenderer'
const API_BASE = API_BASE_URL
const VIRTUALIZATION_THRESHOLD_BYTES = 50_000
const MARKDOWN_PREVIEW_SIZE_LIMIT = 1_000_000
function getFileApiUrl(path: string, query?: string): string {
const separator = query ? (path.includes('..') ? '&' : '?') : ''
const suffix = query ? `${separator}${query}` : ''
if (path.includes('..')) {
return `${API_BASE}/api/files/?path=${encodeURIComponent(path)}${suffix}`
}
return `${API_BASE}/api/files/${path.split('/').map(encodeURIComponent).join('/')}${suffix}`
}
interface FilePreviewProps {
file: FileInfo
hideHeader?: boolean
@@ -106,7 +93,7 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
const handleDownload = () => {
const link = document.createElement('a')
link.href = getFileApiUrl(file.path, 'download=true')
link.href = getFileApiUrl(file.path, { params: { download: true } })
link.download = file.name
document.body.appendChild(link)
link.click()
@@ -200,7 +187,7 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
return (
<div className="flex justify-center p-4">
<img
src={getFileApiUrl(file.path, 'raw=true')}
src={getFileApiUrl(file.path, { params: { raw: true } })}
alt={file.name}
className="max-w-full h-auto object-contain rounded"
/>
@@ -3,7 +3,7 @@ import { useMobile } from '@/hooks/useMobile'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { DeleteDialog } from '@/components/ui/delete-dialog'
import { API_BASE_URL } from '@/config'
import { getFileApiUrl } from '@/api/files'
import {
File,
Folder,
@@ -95,9 +95,7 @@ function TreeNode({ file, level, onFileSelect, onDirectoryClick, selectedFile, o
const handleDownload = () => {
if (file.isDirectory) return
const downloadUrl = file.path.includes('..')
? `${API_BASE_URL}/api/files/?path=${encodeURIComponent(file.path)}&download=true`
: `${API_BASE_URL}/api/files/${file.path.split('/').map(encodeURIComponent).join('/')}?download=true`
const downloadUrl = getFileApiUrl(file.path, { params: { download: true } })
const link = document.createElement('a')
link.href = downloadUrl
link.download = file.name