noteJS-react/src/utils/filePaths.ts

77 lines
2.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* Утилиты для формирования правильных путей к файлам и изображениям
*/
/**
* Формирует правильный URL для изображения заметки
* @param filePath - путь к файлу, возвращаемый сервером
* @param noteId - ID заметки
* @param imageId - ID изображения
* @returns Правильный URL для доступа к изображению
*/
export function getImageUrl(
filePath: string,
noteId: number,
imageId: number
): string {
// Если путь уже является полным URL (начинается с http:// или https://)
if (filePath.startsWith("http://") || filePath.startsWith("https://")) {
return filePath;
}
// Если путь начинается с /api, возвращаем как есть
if (filePath.startsWith("/api")) {
return filePath;
}
// Если путь начинается с /uploads, возвращаем как есть (не добавляем /api)
if (filePath.startsWith("/uploads")) {
return filePath;
}
// Если путь начинается с /, добавляем /api
if (filePath.startsWith("/")) {
return `/api${filePath}`;
}
// Используем endpoint API для получения изображения
return `/api/notes/${noteId}/images/${imageId}`;
}
/**
* Формирует правильный URL для файла заметки
* @param filePath - путь к файлу, возвращаемый сервером
* @param noteId - ID заметки
* @param fileId - ID файла
* @returns Правильный URL для доступа к файлу
*/
export function getFileUrl(
filePath: string,
noteId: number,
fileId: number
): string {
// Если путь уже является полным URL (начинается с http:// или https://)
if (filePath.startsWith("http://") || filePath.startsWith("https://")) {
return filePath;
}
// Если путь начинается с /api, возвращаем как есть
if (filePath.startsWith("/api")) {
return filePath;
}
// Если путь начинается с /uploads, возвращаем как есть (не добавляем /api)
if (filePath.startsWith("/uploads")) {
return filePath;
}
// Если путь начинается с /, добавляем /api
if (filePath.startsWith("/")) {
return `/api${filePath}`;
}
// Используем endpoint API для получения файла
return `/api/notes/${noteId}/files/${fileId}`;
}