81 lines
2.4 KiB
JavaScript
81 lines
2.4 KiB
JavaScript
import { useCallback } from 'react';
|
|
import { API_URL } from '../config/authConstants';
|
|
|
|
/**
|
|
* Хук для изменения статуса поста (ACTIVE/CLOSED).
|
|
* Используется для отметки "Вещь найдена".
|
|
*/
|
|
export function usePostStatus() {
|
|
/**
|
|
* Изменяет статус поста на CLOSED (вещь найдена).
|
|
* @param {number} postId - ID поста
|
|
* @param {string} token - JWT токен авторизации
|
|
* @returns {Promise<boolean>} - true если операция успешна
|
|
*/
|
|
const markAsFound = useCallback(async (postId, token) => {
|
|
if (!token) {
|
|
console.warn('Cannot mark post as found: no token');
|
|
return false;
|
|
}
|
|
|
|
try {
|
|
// Используем PATCH endpoint для обновления статуса
|
|
const response = await fetch(`${API_URL}/api/v1/posts/${postId}/status`, {
|
|
method: 'PATCH',
|
|
headers: {
|
|
'Authorization': `Bearer ${token}`,
|
|
'Content-Type': 'application/json',
|
|
},
|
|
body: JSON.stringify({ status: 'CLOSED' }),
|
|
});
|
|
|
|
if (!response.ok) {
|
|
throw new Error(`Failed to update status: ${response.status}`);
|
|
}
|
|
|
|
return true;
|
|
} catch (error) {
|
|
console.error('Error marking post as found:', error);
|
|
return false;
|
|
}
|
|
}, []);
|
|
|
|
/**
|
|
* Возвращает статус поста в ACTIVE (если нужно reopen).
|
|
* @param {number} postId - ID поста
|
|
* @param {string} token - JWT токен авторизации
|
|
* @returns {Promise<boolean>} - true если операция успешна
|
|
*/
|
|
const reopenPost = useCallback(async (postId, token) => {
|
|
if (!token) {
|
|
console.warn('Cannot reopen post: no token');
|
|
return false;
|
|
}
|
|
|
|
try {
|
|
const response = await fetch(`${API_URL}/api/v1/posts/${postId}/status`, {
|
|
method: 'PATCH',
|
|
headers: {
|
|
'Authorization': `Bearer ${token}`,
|
|
'Content-Type': 'application/json',
|
|
},
|
|
body: JSON.stringify({ status: 'ACTIVE' }),
|
|
});
|
|
|
|
if (!response.ok) {
|
|
throw new Error(`Failed to update status: ${response.status}`);
|
|
}
|
|
|
|
return true;
|
|
} catch (error) {
|
|
console.error('Error reopening post:', error);
|
|
return false;
|
|
}
|
|
}, []);
|
|
|
|
return {
|
|
markAsFound,
|
|
reopenPost,
|
|
};
|
|
}
|