119 lines
3.2 KiB
JavaScript

/**
* AGC Document Search - API Service
* Handles communication with the backend API
*/
const apiService = {
baseUrl: "http://localhost:8000",
/**
* Check API connection
*/
async checkConnection() {
try {
const response = await fetch(`${this.baseUrl}/ping`);
return response.ok;
} catch (error) {
console.error("API connection failed:", error);
return false;
}
},
/**
* Get all document types
*/
async getDocumentTypes() {
try {
const response = await fetch(`${this.baseUrl}/document-types`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error("Error fetching document types:", error);
throw error;
}
},
/**
* Get documents with optional filters
* @param {Object} filters - Optional filters (doc_type, title_filter)
*/
async getDocuments(filters = {}) {
try {
// Build query params
const params = new URLSearchParams();
if (filters.doc_type) params.append("doc_type", filters.doc_type);
if (filters.title_filter)
params.append("title_filter", filters.title_filter);
const response = await fetch(`${this.baseUrl}/documents?${params}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error("Error fetching documents:", error);
throw error;
}
},
/**
* Get document by ID
* @param {string|number} documentId - The document ID
*/
async getDocument(documentId) {
try {
// Handle numeric IDs by converting them to our doc format if needed
let formattedId = documentId;
if (
typeof documentId === "number" ||
(!isNaN(parseInt(documentId)) && !documentId.startsWith("doc"))
) {
const numId = parseInt(documentId);
formattedId = `doc${numId}`;
console.log(`Converted numeric ID to document ID: ${formattedId}`);
}
console.log(`Fetching document with ID: ${formattedId}`);
const response = await fetch(`${this.baseUrl}/document/${formattedId}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error(`Error fetching document ${documentId}:`, error);
throw error;
}
},
/**
* Search documents
* @param {string} query - Search query
* @param {boolean} profileSearch - Whether to use profile search
*/
async searchDocuments(query, profileSearch = false) {
try {
const response = await fetch(`${this.baseUrl}/search`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
query: query,
profile_search: profileSearch,
}),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error("Error searching documents:", error);
throw error;
}
},
};