47 lines
1.5 KiB
GDScript
47 lines
1.5 KiB
GDScript
extends Node
|
|
## HTTP istemcisi — Stepstead API'sine istek atar.
|
|
|
|
signal request_completed(method: String, path: String, status: int, body: Variant)
|
|
|
|
func request(method: String, path: String, body: Variant = null, auth: bool = true) -> Dictionary:
|
|
var http := HTTPRequest.new()
|
|
add_child(http)
|
|
var url := Config.get_api_base() + path
|
|
var headers := ["Content-Type: application/json", "Accept: application/json"]
|
|
if auth and Auth.token != "":
|
|
headers.append("Authorization: Bearer " + Auth.token)
|
|
|
|
var method_id: int = HTTPClient.METHOD_GET
|
|
match method.to_upper():
|
|
"GET": method_id = HTTPClient.METHOD_GET
|
|
"POST": method_id = HTTPClient.METHOD_POST
|
|
"PUT": method_id = HTTPClient.METHOD_PUT
|
|
"DELETE": method_id = HTTPClient.METHOD_DELETE
|
|
"PATCH": method_id = HTTPClient.METHOD_PATCH
|
|
|
|
var body_str := ""
|
|
if body != null:
|
|
body_str = JSON.stringify(body)
|
|
|
|
var err := http.request(url, headers, method_id, body_str)
|
|
if err != OK:
|
|
http.queue_free()
|
|
return {"ok": false, "status": 0, "error": "request_failed", "body": null}
|
|
|
|
var result: Array = await http.request_completed
|
|
http.queue_free()
|
|
|
|
var status: int = result[1]
|
|
var raw_body: PackedByteArray = result[3]
|
|
var parsed: Variant = null
|
|
if raw_body.size() > 0:
|
|
var text := raw_body.get_string_from_utf8()
|
|
var json := JSON.new()
|
|
if json.parse(text) == OK:
|
|
parsed = json.data
|
|
else:
|
|
parsed = text
|
|
|
|
var ok := status >= 200 and status < 300
|
|
request_completed.emit(method.to_upper(), path, status, parsed)
|
|
return {"ok": ok, "status": status, "body": parsed}
|