saas_app/src/shared/services/api/Api.ts

63 lines
2.1 KiB
TypeScript

import TokenGet from '@/shared/actions/token/TokenGet';
import ApiSchema from '@/shared/services/api/schemas/ApiSchema';
import ApiInterface from './interfaces/ApiInterface';
export default class API {
private ApiSchema: ApiSchema;
constructor() {
// Classe validadora das informações
this.ApiSchema = new ApiSchema();
}
public async send(data: ApiInterface) {
// Define os dados para envio
const _data = data;
try {
// Verifica se todos os dados estão corretos
this.ApiSchema.url = process.env.NEXT_PUBLIC_ORIUS_APP_API_URL + ':' + process.env.NEXT_PUBLIC_ORIUS_APP_API_PORT + '/';
this.ApiSchema.prefix = process.env.NEXT_PUBLIC_ORIUS_APP_API_PREFIX;
this.ApiSchema.endpoint = _data.endpoint;
this.ApiSchema.contentType = process.env.NEXT_PUBLIC_ORIUS_APP_API_CONTENT_TYPE;
this.ApiSchema.token = await TokenGet();
// Verifica se existem erros
if (this.ApiSchema.errors.length > 0) {
throw new Error(`Erros no schema: ${this.ApiSchema.errors.join(', ')}`);
}
// Verifica se existe body para envio
const filteredBody = _data.body
? Object.fromEntries(Object.entries(_data.body).filter(([_, v]) => v != null && v !== ''))
: null;
// Realiza a requisição
const response = await fetch(
`${this.ApiSchema.url}${this.ApiSchema.prefix}${this.ApiSchema.endpoint}`,
{
method: _data.method,
headers: {
Accept: `${this.ApiSchema.contentType}`,
'Content-Type': `${this.ApiSchema.contentType}`,
Authorization: `Bearer ${this.ApiSchema.token}`,
},
credentials: 'include',
...(filteredBody && { body: JSON.stringify(filteredBody) }),
},
);
// Converte a reposta para json
const responseData = await response.json();
// Obtem o status da requisição
responseData.status = response.status;
return responseData;
} catch (error) {
console.error('Erro ao enviar requisição:', error);
throw error;
}
}
}