Utils (@pim.sk/utils)

get

Async wrapper around fetch. Supports GET/POST, automatic JSON parsing, parallel requests via Promise.all, and data payload via object.
import get from '@pim.sk/utils/get.mjs'

Usage

get( url )

Fetches a resource and returns parsed JSON by default. Use with async/await inside a module script.

const data = await get("./my-data.json")
// → [{ a:1, b:"one" }, { a:2, b:"two" }, { a:3, b:"three" }]

Without async — .then()

get() returns a Promise — use .then() when async/await is not available.

get("./my-data.json").then(data => {
    output.textContent = JSON.stringify(data)
})

Promise.all — parallel requests

Fetch multiple resources simultaneously. All requests run in parallel and resolve together.

// my-data.json   → [{ a:1 }, { a:2 }, { a:3 }]
// my-data-2.json → [{ a:4 }, { a:5 }, { a:6 }]
const [data1, data2] = await Promise.all([
    get("./my-data.json"),
    get("./my-data-2.json"),
])
output.textContent = JSON.stringify([...data1, ...data2])

option: method — GET / POST

Default method is POST. Pass "GET" or "POST" as a string option.

method = "POST"  // default
method = "GET"
get("./my-data.json", "GET")   // GET request
get("./my-data.json")          // POST request (default)

option: vystup — json / text / object

"json" (default) auto-parses the response. "text" returns the raw string. "object" returns the fetch Response instance.

vystup = "json"    // default — parsed object / array
vystup = "text"    // raw response string
vystup = "object"  // fetch Response instance
await get("./my-data.json")            // → object (parsed)
await get("./my-data.json", "text")    // → string
await get("./my-data.json", "object")  // → Response

option: data — { key: value }

Pass a data payload as an object. Sent as JSON body (POST). The server reads it via mpws::getRequest().

// my-data.php
$opt = (object) mpws::getRequest();
if( $opt->a === "typeA" ){
    $data = [
        ["a"=>1, "b"=>"one"],
        ["a"=>2, "b"=>"two"],
        ["a"=>3, "b"=>"three"],
    ];
}
await get("./my-data.php", { a: "typeA" })
// → { status: true, data: [{ a:1, b:"one" }, ...] }
v 1.1.2