1.0.21 • Published 12 months ago
@web-atoms/fetch-builder v1.0.21
Fetch Builder
Simple Fluent Interface to call fetch
Why?
To make REST API easier. Lets have following examples.
Download Text
const text = await FetchBuilder.get("https://someurl.com")
.asText();
Post Json body and retrieve Json
const result = await FetchBuilder.post("https://someapi.com")
.header("x-api-key", someKey)
.jsonBody({
name: "bla bla bla",
email: "bla@bla.bla"
})
.asJson<IResult>();
Reuse builder
This is important as you can configure builder once with default headers.
const client = FetchBuilder
.url("https://somewhere.com/")
.header("x-api-key", someKey);
const result = await client.post("/api/orders/create")
.jsonBody({
productId: 3
})
.asJson<IResult>();
Log Failed Requests
This will log only failed requests.
const client = FetchBuilder
.url("https://somewhere.com/")
.header("x-api-key", someKey)
.logWhenFailed(console.error);
const result = await client.post("/api/orders/create")
.jsonBody({
productId: 3
})
.asJson<IResult>();
Query String
const client = FetchBuilder
.url("https://somewhere.com/")
.header("x-api-key", someKey)
.logWhenFailed(console.error);
const result = await client.get("/api/orders/reports")
.query("year-start", 2015)
.query("year-end", 2022)
.query("search-text", "social mail") // <-- this will be encoded
.asJson();