neon-sprawl/client/scripts/cooldown_snapshot_client.gd

64 lines
1.8 KiB
GDScript

extends Node
## NEO-32: prototype HTTP client for [code]GET /game/players/{id}/cooldown-snapshot[/code].
signal snapshot_received(snapshot: Dictionary)
@export var base_url: String = "http://127.0.0.1:5253"
@export var dev_player_id: String = "dev-local-1"
@export var injected_http: Node = null
var _http: Node
var _busy: bool = false
func _ready() -> void:
if injected_http != null:
_http = injected_http
else:
_http = HTTPRequest.new()
add_child(_http)
if _http is HTTPRequest:
(_http as HTTPRequest).timeout = 30.0
@warning_ignore("unsafe_method_access")
_http.request_completed.connect(_on_request_completed)
func request_sync_from_server() -> void:
if _busy:
return
_busy = true
var url := "%s/game/players/%s/cooldown-snapshot" % [_base_root(), _player_path_segment()]
var err: Error = _http.request(url)
if err != OK:
push_warning("CooldownSnapshotClient: GET failed to start (%s)" % err)
_busy = false
func _base_root() -> String:
return base_url.strip_edges().rstrip("/")
func _player_path_segment() -> String:
return dev_player_id.strip_edges()
func _on_request_completed(
result: int, response_code: int, _headers: PackedStringArray, body: PackedByteArray
) -> void:
_busy = false
if result != HTTPRequest.RESULT_SUCCESS:
push_warning("CooldownSnapshotClient: HTTP failed (result=%s)" % result)
return
if response_code == 404:
push_warning("CooldownSnapshotClient: HTTP 404 (player unknown)")
return
if response_code < 200 or response_code >= 300:
push_warning("CooldownSnapshotClient: HTTP %s" % response_code)
return
var text := body.get_string_from_utf8()
var parsed: Variant = JSON.parse_string(text)
if not parsed is Dictionary:
push_warning("CooldownSnapshotClient: non-JSON body")
return
snapshot_received.emit(parsed as Dictionary)