Created first roundtrip from swift to js

This commit is contained in:
Michael Bykovski 2017-07-10 14:38:46 +02:00
parent 5c160eee16
commit e02ff2b04a
3 changed files with 65 additions and 34 deletions

View File

@ -9,6 +9,8 @@
override func pluginInitialize() { override func pluginInitialize() {
self.webServer = GCDWebServer() self.webServer = GCDWebServer()
self.onRequestCommand = nil self.onRequestCommand = nil
self.responses = [:]
self.initHTTPRequestHandlers()
} }
func requestToRequestDict(requestUUID: String, request: GCDWebServerDataRequest) -> Dictionary<String, Any> { func requestToRequestDict(requestUUID: String, request: GCDWebServerDataRequest) -> Dictionary<String, Any> {
@ -22,44 +24,58 @@
] ]
} }
func processRequest(request: GCDWebServerRequest) -> GCDWebServerResponse { func processRequest(request: GCDWebServerRequest, completionBlock: GCDWebServerCompletionBlock) {
var timeout = 0 var timeout = 0
// Fetch data as GCDWebserverDataRequest // Fetch data as GCDWebserverDataRequest
let dataRequest = request as! GCDWebServerDataRequest
let requestUUID = UUID().uuidString let requestUUID = UUID().uuidString
// Transform it into an dictionary for the javascript plugin // Transform it into an dictionary for the javascript plugin
let requestDict = self.requestToRequestDict(requestUUID: requestUUID, request: dataRequest) let requestDict = self.requestToRequestDict(requestUUID: requestUUID, request: request as! GCDWebServerDataRequest)
// Do a call to the onRequestCommand to inform the JS plugin // Do a call to the onRequestCommand to inform the JS plugin
if (self.onRequestCommand != nil) { if (self.onRequestCommand != nil) {
print("Sending to JS Context")
let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: requestDict)
pluginResult?.setKeepCallbackAs(true)
self.commandDelegate.send( self.commandDelegate.send(
CDVPluginResult(status: CDVCommandStatus_OK, messageAs: requestDict), pluginResult,
callbackId: self.onRequestCommand?.callbackId callbackId: self.onRequestCommand?.callbackId
) )
} }
// Here we have to wait until the javascript block fetches the message and do a response // Here we have to wait until the javascript block fetches the message and do a response
while self.responses[requestUUID] == nil && timeout < self.TIMEOUT { while self.responses[requestUUID] == nil {
timeout += 2000 timeout += 2000
usleep(2000) usleep(2000)
} }
let response = GCDWebServerResponse() let responseDict = self.responses[requestUUID] as! Dictionary<AnyHashable, Any>
return response let response = GCDWebServerDataResponse(text: responseDict["body"] as! String)
response?.statusCode = responseDict["status"] as! Int
for (key, value) in (responseDict["headers"] as! Dictionary<String, String>) {
response?.setValue(value, forAdditionalHeader: key)
}
completionBlock(response!)
} }
func onRequest(_ command: CDVInvokedUrlCommand) { func onRequest(_ command: CDVInvokedUrlCommand) {
self.onRequestCommand = command self.onRequestCommand = command
let pluginResult = CDVPluginResult(status: CDVCommandStatus_NO_RESULT)
pluginResult?.setKeepCallbackAs(true)
self.commandDelegate.send(
pluginResult,
callbackId: self.onRequestCommand?.callbackId
)
} }
func initHTTPRequestHandlers() { func initHTTPRequestHandlers() {
for methodType in ["GET", "POST", "PUT", "PATCH", "DELETE"] { self.webServer.addHandler(
self.webServer.addDefaultHandler( match: {
forMethod: methodType, (requestMethod, requestURL, requestHeaders, urlPath, urlQuery) -> GCDWebServerRequest? in
request: GCDWebServerDataRequest.self, return GCDWebServerDataRequest(method: requestMethod, url: requestURL, headers: requestHeaders, path: urlPath, query: urlQuery)
processBlock: self.processRequest },
) asyncProcessBlock: self.processRequest
} )
} }
func sendResponse(_ command: CDVInvokedUrlCommand) { func sendResponse(_ command: CDVInvokedUrlCommand) {

View File

@ -1,3 +1,4 @@
cordova.define("cordova-plugin-webserver-tests.tests", function(require, exports, module) {
exports.defineAutoTests = function() { exports.defineAutoTests = function() {
describe('Webserver (window.webserver)', function () { describe('Webserver (window.webserver)', function () {
@ -35,12 +36,21 @@ exports.defineManualTests = function(contentEl, createActionButton) {
createActionButton('Start bljad Webserver', function() { createActionButton('Start bljad Webserver', function() {
console.log("Starting webserver..."); console.log("Starting webserver...");
console.log(webserver);
webserver.onRequest( webserver.onRequest(
function(request) { function(request) {
console.log(request); console.log('Received request');
webserver.sendResponse(request.requestId, {}); console.log('Sending response');
webserver.sendResponse(
request["requestId"],
{
status: 200,
headers: {
'Content-Type': 'application/json',
'TestHeader': 'Just a testheader'
},
body: '{"hello":"from js!"}'
}
);
} }
); );
@ -81,3 +91,5 @@ exports.defineManualTests = function(contentEl, createActionButton) {
); );
}); });
}; };
});

View File

@ -1,6 +1,7 @@
var WEBSERVER_CLASS = "Webserver"; cordova.define("cordova-plugin-webserver.webserver", function(require, exports, module) {
var WEBSERVER_CLASS = "Webserver";
exports.start = function(success_callback, error_callback, port) { exports.start = function(success_callback, error_callback, port) {
cordova.exec( cordova.exec(
success_callback, success_callback,
error_callback, error_callback,
@ -8,34 +9,34 @@ exports.start = function(success_callback, error_callback, port) {
"start", "start",
[port] [port]
); );
}; };
exports.onRequest = function(success_callback) { exports.onRequest = function(success_callback) {
cordova.exec( cordova.exec(
success_callback, success_callback,
function(error) {console.error(error);} function(error) {console.error(error)},
WEBSERVER_CLASS, WEBSERVER_CLASS,
"onRequest", "onRequest",
[] []
); );
}; };
exports.sendResponse = function( exports.sendResponse = function(
responseId, requestId,
params, params,
success_callback, success_callback,
error_callback error_callback
) { ) {
cordova.exec( cordova.exec(
success_callback, success_callback,
error_callback, error_callback,
WEBSERVER_CLASS, WEBSERVER_CLASS,
"send", "sendResponse",
[requestId, params] [requestId, params]
); );
}; };
exports.stop = function(success_callback, error_callback) { exports.stop = function(success_callback, error_callback) {
cordova.exec( cordova.exec(
success_callback, success_callback,
error_callback, error_callback,
@ -43,4 +44,6 @@ exports.stop = function(success_callback, error_callback) {
"stop", "stop",
[] []
); );
}; };
});