File size: 7,461 Bytes
25f22bf |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 |
import apiClient from './apiClient';
class PostService {
/**
* Get all posts for the current user
* @param {Object} params - Query parameters
* @param {boolean} params.published - Filter by published status
* @returns {Promise} Promise that resolves to the posts data
*/
async getAll(params = {}) {
try {
const response = await apiClient.get('/posts', { params });
if (import.meta.env.VITE_NODE_ENV === 'development') {
console.log('π [Post] Retrieved posts:', response.data);
}
return response;
} catch (error) {
if (import.meta.env.VITE_NODE_ENV === 'development') {
console.error('π [Post] Get posts error:', error.response?.data || error.message);
}
throw error;
}
}
/**
* Generate a new post using AI asynchronously
* @returns {Promise} Promise that resolves to the generated post content
*/
async generate() {
try {
// Step 1: Start the generation process and get job ID
const startResponse = await apiClient.post('/posts/generate', {});
if (import.meta.env.VITE_NODE_ENV === 'development') {
console.log('π [Post] AI post generation started:', startResponse.data);
}
const jobId = startResponse.data.job_id;
// Step 2: Poll for the result
const generatedContent = await this.pollForJobResult(jobId);
// Ensure we return a default value if content is null/undefined
const finalContent = generatedContent !== undefined && generatedContent !== null ? generatedContent : "Generated content will appear here...";
return { data: { success: true, content: finalContent } };
} catch (error) {
if (import.meta.env.VITE_NODE_ENV === 'development') {
console.error('π [Post] Generate post error:', error.response?.data || error.message);
}
throw error;
}
}
/**
* Poll for job result
* @param {string} jobId - Job ID to poll
* @returns {Promise} Promise that resolves to the generated content
*/
async pollForJobResult(jobId) {
const pollInterval = 6000; // 6 seconds to match backend logs
const maxAttempts = 60; // 6 minutes (60 * 6 seconds = 360 seconds)
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
const response = await apiClient.get(`/posts/jobs/${jobId}`);
const jobData = response.data;
if (import.meta.env.VITE_NODE_ENV === 'development') {
console.log(`π [Post] Job status check ${attempt}/${maxAttempts}:`, jobData);
}
switch (jobData.status) {
case 'completed':
// Log the raw job data for debugging
if (import.meta.env.VITE_NODE_ENV === 'development') {
console.log('π [Post] Raw job data:', jobData);
}
// Extract content, handling cases where it might be a list
let content = jobData.content;
// If content is an array, take the first element
if (Array.isArray(content)) {
content = content[0] || '';
}
// Ensure we return the content even if it's an empty string
return content !== undefined ? content : '';
case 'failed':
throw new Error(jobData.error || 'Job failed');
case 'processing':
case 'pending':
// Wait before next poll
await new Promise(resolve => setTimeout(resolve, pollInterval));
break;
default:
throw new Error(`Unknown job status: ${jobData.status}`);
}
} catch (error) {
if (error.response?.status === 404) {
throw new Error('Job not found');
}
throw error;
}
}
// If we've reached here, we've exceeded the max attempts
throw new Error('Job polling timed out after 6 minutes. Please check back later.');
}
/**
* Create a new post
* @param {Object} postData - Post data
* @param {string} postData.social_account_id - Social account ID
* @param {string} postData.text_content - Post text content
* @param {string} [postData.image_content_url] - Image URL (optional)
* @param {string} [postData.scheduled_at] - Scheduled time (optional)
* @returns {Promise} Promise that resolves to the create post response
*/
async create(postData) {
try {
if (import.meta.env.VITE_NODE_ENV === 'development') {
console.log('π [Post] Creating post with data:', postData);
}
const response = await apiClient.post('/posts', {
social_account_id: postData.social_account_id,
text_content: postData.text_content,
image_content_url: postData.image_content_url,
scheduled_at: postData.scheduled_at
});
if (import.meta.env.VITE_NODE_ENV === 'development') {
console.log('π [Post] Post created:', response.data);
}
return response;
} catch (error) {
if (import.meta.env.VITE_NODE_ENV === 'development') {
console.error('π [Post] Create post error:', error.response?.data || error.message);
console.error('π [Post] Error details:', {
status: error.response?.status,
statusText: error.response?.statusText,
headers: error.response?.headers,
data: error.response?.data
});
}
throw error;
}
}
/**
* Publish a post directly to social media
* @param {Object} publishData - Publish data
* @param {string} publishData.social_account_id - Social account ID
* @param {string} publishData.text_content - Post text content
* @returns {Promise} Promise that resolves to the publish post response
*/
async publishDirect(publishData) {
try {
if (import.meta.env.VITE_NODE_ENV === 'development') {
console.log('π [Post] Publishing post directly to social media with data:', publishData);
}
const response = await apiClient.post('/posts/publish-direct', publishData);
if (import.meta.env.VITE_NODE_ENV === 'development') {
console.log('π [Post] Post published directly:', response.data);
}
return response;
} catch (error) {
if (import.meta.env.VITE_NODE_ENV === 'development') {
console.error('π [Post] Publish post directly error:', error.response?.data || error.message);
console.error('π [Post] Error details:', {
status: error.response?.status,
statusText: error.response?.statusText,
headers: error.response?.headers,
data: error.response?.data
});
}
throw error;
}
}
/**
* Delete a post
* @param {string} postId - Post ID
* @returns {Promise} Promise that resolves to the delete post response
*/
async delete(postId) {
try {
const response = await apiClient.delete(`/posts/${postId}`);
if (import.meta.env.VITE_NODE_ENV === 'development') {
console.log('π [Post] Post deleted:', response.data);
}
return response;
} catch (error) {
if (import.meta.env.VITE_NODE_ENV === 'development') {
console.error('π [Post] Delete post error:', error.response?.data || error.message);
}
throw error;
}
}
}
export default new PostService(); |