You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

79 lines
2.5 KiB

extends HTTPRequest
const Response = preload("../util/Response.gd")
var _callback : Callable
var auth_token: String
var base_address: String
# Called when the node enters the scene tree for the first time.
func _ready():
pass # Replace with function body.
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
pass
func post_http_request(url: String, request_data: String) -> Response:
return await _send_http_request_sync(url, HTTPClient.METHOD_POST, request_data)
func patch_http_request(url: String, request_data: String) -> Response:
return await _send_http_request_sync(url, HTTPClient.METHOD_PATCH, request_data)
func get_http_request(url: String, callback : Callable) -> bool:
return _send_http_request(url, HTTPClient.METHOD_GET, callback)
func get_http_request_sync(url: String) -> Response:
return await _send_http_request_sync(url, HTTPClient.METHOD_GET)
func _send_http_request_sync(url: String, method: HTTPClient.Method, request_data: String = "") -> Response:
var result: Response = Response.new()
result.status = FAILED
result.code = HTTPClient.ResponseCode.RESPONSE_BAD_REQUEST
result.data = {}
var lambda = func(response):
result.status = response.status
result.code = response.code
result.data = response.data
if !_send_http_request(url, method, lambda, request_data):
return result
await request_completed
return result
func _send_http_request(url: String, method: HTTPClient.Method, callback : Callable, request_data : String = "") -> bool:
_callback = callback
var _url = "{address}/{url}".format({"address": base_address, "url": url})
print_debug("%s request on %s with: %s" % [method, _url, request_data])
var headers = ["X-AUTH-TOKEN: %s" % auth_token, "accept: application/json"]
if method == HTTPClient.METHOD_PATCH:
headers.append("Content-Type: application/merge-patch+json")
elif method == HTTPClient.METHOD_POST:
headers.append("Content-Type: application/json")
var error = request(_url, headers, method, request_data)
return error == OK
func _on_request_completed(result, response_code, headers, body):
var response : Response = Response.new()
response.status = FAILED
response.code = response_code
response.data = {}
## Where to get the response to?
if result == HTTPRequest.RESULT_SUCCESS and response_code / 100 == 2:
response.status = OK
var json = JSON.new()
json.parse(body.get_string_from_utf8())
response.data = json.get_data()
_callback.call(response)