mpackagejs
Version:
mpackagejs - biblioteca javascript
74 lines (59 loc) • 2.09 kB
JavaScript
import { BaseManager } from "../managers/BaseManager";
export class BaseRequest {
baseURL = BaseManager.getUrlBase();
apikey = BaseManager.getApiKey();
token = undefined;
constructor(baseURL = undefined, apikey = undefined, token = undefined) {
this.baseURL = baseURL ?? this.baseURL;
this.apikey = apikey ?? this.apikey;
this.token = token ?? this.token;
}
setUrlBase(baseURL) {
this.baseURL = baseURL;
}
setApiKey(apikey) {
this.apikey = apikey;
}
setToken(token) {
this.token = token;
}
async request(endpoint, method = "GET", body = null) {
const options = {
method,
headers: {
"Content-Type": "application/json",
"Authorization": this.token ? `Bearer ${this.token}` : null,
"ApiKey": this.apikey ? `${this.apikey}` : null,
},
};
if (body) {
options.body = JSON.stringify(body);
}
try {
const response = await fetch(`${this.baseURL}${endpoint}`, options);
if (!response.ok) {
throw new Error(`Erro: ${response.status} - ${response.statusText}`);
}
return await response.json();
} catch (error) {
console.error("Erro na requisição:", error);
throw error;
}
}
get(endpoint) {
return this.request(endpoint);
}
post(endpoint, body) {
return this.request(endpoint, "POST", body);
}
put(endpoint, body) {
return this.request(endpoint, "PUT", body);
}
delete(endpoint) {
return this.request(endpoint, "DELETE");
}
}
// Exemplo de uso:
// const api = new HttpRequest("https://jsonplaceholder.typicode.com");
// api.get("/posts/1").then(console.log).catch(console.error);
// api.post("/posts", { title: "Novo Post", body: "Conteúdo do post", userId: 1 }).then(console.log).catch(console.error);