Last active
July 20, 2019 11:34
-
-
Save NovemberDev/868f8fb8908fb76c43aaad28982f13e5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extends Node | |
var API = "http://localhost:5000/api" | |
var current_request = {} | |
var request_queue = [] | |
var is_busy = false | |
var http | |
func _ready(): | |
http = HTTPRequest.new() | |
http.connect("request_completed", self, "on_request_completed") | |
add_child(http) | |
func enqueue_get(endpoint: String, callback: FuncRef): | |
enqueue_request(endpoint, null, HTTPClient.METHOD_GET, callback) | |
func enqueue_put(endpoint: String, data, callback: FuncRef): | |
enqueue_request(endpoint, data, HTTPClient.METHOD_PUT, callback) | |
func enqueue_post(endpoint: String, data, callback: FuncRef): | |
enqueue_request(endpoint, data, HTTPClient.METHOD_POST, callback) | |
func enqueue_request(endpoint: String, data, method, callback: FuncRef): | |
if data == null: | |
data = {} | |
request_queue.push_back({ | |
endpoint = endpoint, | |
callback = callback, | |
data = JSON.print(data), | |
method = method | |
}) | |
if !is_busy: | |
do_requests() | |
func on_request_completed(result, response_code, headers, body): | |
if response_code != 200: | |
print("response was " + str(response_code)) | |
var res = body.get_string_from_utf8() | |
if res != "": | |
res = JSON.parse(res).result | |
else: | |
res = null | |
if current_request.callback != null: | |
current_request.callback.call_func(res) | |
do_requests() | |
func do_requests(): | |
if request_queue.size() > 0: | |
current_request = request_queue.pop_back() | |
var headers = [ "Content-Type: application/json" ] | |
if Globals.token != null: | |
if Globals.token.length() > 0: | |
headers.push_front("Authorization: Bearer " + Globals.token) | |
http.request(API + current_request.endpoint, headers, false, current_request.method, current_request.data) | |
is_busy = true | |
else: | |
is_busy = false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment