72 lines
2.1 KiB
TypeScript
72 lines
2.1 KiB
TypeScript
import Json from "@/actions/json/Json";
|
|
import ApiInterface from "./interfaces/ApiInterface";
|
|
|
|
import TokenGet from "@/actions/token/TokenGet";
|
|
import ApiSchema from "@/services/api/schemas/ApiSchema";
|
|
import IConfig from "@/interfaces/IConfig";
|
|
|
|
export default class API {
|
|
private ApiSchema: ApiSchema;
|
|
private config: IConfig;
|
|
|
|
constructor() {
|
|
// Classe validadora das informações
|
|
this.ApiSchema = new ApiSchema();
|
|
|
|
// Obtem as configurações da aplicação
|
|
this.config = Json.execute();
|
|
}
|
|
|
|
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 = this.config.api.url;
|
|
this.ApiSchema.prefix = this.config.api.prefix;
|
|
this.ApiSchema.endpoint = _data.endpoint;
|
|
this.ApiSchema.contentType = this.config.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}`,
|
|
},
|
|
...(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;
|
|
}
|
|
}
|
|
}
|