UNPKG

@wscsports/blaze-rtn-sdk

Version:
107 lines (98 loc) 3.11 kB
import { NativeModules, NativeEventEmitter } from 'react-native'; const { RTNBlazeAsyncBridge } = NativeModules; const BlazeAsyncBridgeNativeModule = RTNBlazeAsyncBridge; class BlazeAsyncBridgeWrapper { methodHandlers = {}; bridgeAsyncFunctionName = 'BlazeAsyncBridge.jsRequest'; eventSubscription = null; // Singleton instance // Private constructor for singleton constructor() { this.eventEmitter = new NativeEventEmitter(BlazeAsyncBridgeNativeModule); // Subscribe to events from the native module this.eventSubscription = this.eventEmitter.addListener(this.bridgeAsyncFunctionName, this.handleJSRequest); } // Method to get singleton instance static getInstance() { if (!this.instance) { this.instance = new BlazeAsyncBridgeWrapper(); } return this.instance; } registerJSMethod(methodName, handler) { this.methodHandlers[methodName] = handler; } unregisterJSMethod(methodName) { delete this.methodHandlers[methodName]; } /** * Clear all registered handlers - useful for hot reload (internal use only) */ clearHandlers() { this.methodHandlers = {}; } /** * Handle a JS method request from native * @param event The event data containing method name, parameters, and callback ID */ handleJSRequest = async event => { const { methodName, params, callbackId } = event; const handler = this.methodHandlers[methodName]; if (!handler) { this.resolveJSResponse({ callbackId, success: false, errorMessage: `No handler registered for method: ${methodName}` }); return; } try { // Parse JSON string to get the typed object let parsedParams; try { parsedParams = JSON.parse(params); } catch (parseError) { this.resolveJSResponse({ callbackId, success: false, errorMessage: `Failed to parse JSON params: ${parseError instanceof Error ? parseError.message : String(parseError)}` }); return; } // Call the handler with the parsed typed parameters const result = await handler(parsedParams, callbackId); // Serialize result to JSON string for consistent cross-platform handling const jsonData = result !== undefined ? JSON.stringify(result) : null; this.resolveJSResponse({ callbackId, success: true, data: jsonData }); } catch (error) { this.resolveJSResponse({ callbackId, success: false, errorMessage: error instanceof Error ? JSON.stringify(error) : String(error) }); } }; /** * Send a response back to native code * @param response The response data */ resolveJSResponse(response) { BlazeAsyncBridgeNativeModule.resolveJSResponse(response); } } export const BlazeAsyncBridge = BlazeAsyncBridgeWrapper.getInstance(); // Hot reload handling - clear handlers only, keep event subscription intact if (__DEV__) { BlazeAsyncBridgeWrapper.getInstance().clearHandlers(); } //# sourceMappingURL=BlazeAsyncBridge.js.map