88 lines
2.4 KiB
TypeScript
88 lines
2.4 KiB
TypeScript
import { databases } from '@/lib/appwrite';
|
|
import { Query } from '@/lib/appwrite';
|
|
|
|
const API_BASE_URL = '';
|
|
|
|
export interface ProdutoData {
|
|
'preco-original'?: number;
|
|
'preco-atual'?: number;
|
|
'catalogo-produto-id'?: string;
|
|
'empresa-id'?: string;
|
|
empresas?: string;
|
|
quantidade?: number;
|
|
[key: string]: any;
|
|
}
|
|
|
|
export interface ApiResponse<T = any> {
|
|
success: boolean;
|
|
data?: T;
|
|
error?: string;
|
|
details?: any;
|
|
documents?: T[];
|
|
total?: number;
|
|
}
|
|
|
|
export interface PaginatedResponse<T> extends ApiResponse<T> {
|
|
documents: T[];
|
|
total: number;
|
|
}
|
|
|
|
class ProdutoService {
|
|
private async makeRequest<T>(endpoint: string, options: RequestInit = {}): Promise<ApiResponse<T>> {
|
|
try {
|
|
const response = await fetch(`${API_BASE_URL}${endpoint}`, {
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
...(options.headers || {})
|
|
},
|
|
...options
|
|
});
|
|
|
|
return await response.json();
|
|
} catch {
|
|
return { success: false, error: 'Erro de conexão com o servidor' };
|
|
}
|
|
}
|
|
|
|
async listar(page = 1, limit = 10): Promise<PaginatedResponse<any>> {
|
|
try {
|
|
const databaseId = process.env.NEXT_PUBLIC_APPWRITE_DATABASE_ID!;
|
|
const collectionId = process.env.NEXT_PUBLIC_APPWRITE_COLLECTION_PRODUTOS_ID!;
|
|
const offset = (page - 1) * limit;
|
|
const response = await databases.listDocuments(databaseId, collectionId, [
|
|
Query.limit(limit),
|
|
Query.offset(offset)
|
|
]);
|
|
|
|
return { success: true, documents: response.documents, total: response.total };
|
|
} catch {
|
|
return { success: true, documents: [], total: 0 };
|
|
}
|
|
}
|
|
|
|
async listarPorEmpresa(_empresaId: string, page = 1, limit = 10, _search = ''): Promise<PaginatedResponse<any>> {
|
|
return this.listar(page, limit);
|
|
}
|
|
|
|
async criar(data: ProdutoData): Promise<ApiResponse> {
|
|
return this.makeRequest('/api/produtos', {
|
|
method: 'POST',
|
|
body: JSON.stringify({ documentId: 'unique()', data })
|
|
});
|
|
}
|
|
|
|
async atualizar(id: string, data: ProdutoData): Promise<ApiResponse> {
|
|
return this.makeRequest(`/api/produtos/${id}`, {
|
|
method: 'PATCH',
|
|
body: JSON.stringify({ data })
|
|
});
|
|
}
|
|
|
|
async deletar(id: string): Promise<ApiResponse> {
|
|
return this.makeRequest(`/api/produtos/${id}`, {
|
|
method: 'DELETE'
|
|
});
|
|
}
|
|
}
|
|
|
|
export const produtoService = new ProdutoService();
|