-
Notifications
You must be signed in to change notification settings - Fork 0
Usage
Çağan Seyrek edited this page Feb 24, 2025
·
4 revisions
First create a requester.ts file in your project. Then we can initialize the EasyRequester in that file.
import { EasyRequester } from "easy-requester";
const requester: EasyRequester = new EasyRequester({
onNewRequest: "enqueue-new",
acceptStatusCodes: [403, 404],
isDebugMode: true,
});
export default requester;This constructor accepts the configuration used across all requests. This configuration is called the Client Config.
You can explore the configs in more detail in the configuring page.
Then, we can import the requester instance to send requests. Below is the full config object passed to the requester:
import requester from "./path/to/requester.ts";
const response = requester.setRequestConfig({
url: {
protocol: "https",
baseUrl: "example.com/api",
port: "3000",
endpoint: {
route: "auth",
subroute: "user",
action: "register",
},
query: {
foo: "bar",
},
},
method: "POST",
header: {
contentType: "application/json",
responseLang: "en",
headers: {
// custom headers,
},
},
auth: {
accessToken: "token",
includeCookies: true,
},
});But in most cases, a simpler config like one below should be enough:
import requester from "./path/to/requester.ts";
const response = requester.setRequestConfig({
url: {
protocol: "https",
baseUrl: "example.com/api",
endpoint: {
route: "auth",
subroute: "user",
action: "register",
},
},
method: "POST",
auth: { accessToken: "token" },
});After setting the request config, we can send the request with the payload like this:
import requester from "./path/to/requester.ts";
async function fetchSometing() {
const response = await requester
.setRequestConfig({
...config,
})
.sendRequest<TResponse, TPayload>({
...someDataToSend,
});
return response;
}The generic TPayload represents the type of data we pass to the method, and the generic TResponse type extends BaseResponse, mentioned earlier.