|
9 | 9 |
|
10 | 10 | using System; |
11 | 11 | using JavaScriptEngineSwitcher.Core; |
| 12 | +using JavaScriptEngineSwitcher.Core.Helpers; |
| 13 | +using Newtonsoft.Json; |
12 | 14 | using React.Exceptions; |
13 | 15 |
|
14 | 16 | namespace React |
@@ -63,5 +65,39 @@ Func<Exception, TException> exceptionFactory |
63 | 65 | throw new ReactException("Mathematics is broken. 1 + 1 = " + result); |
64 | 66 | } |
65 | 67 | } |
| 68 | + |
| 69 | + /// <summary> |
| 70 | + /// Calls a JavaScript function using the specified engine. If <typeparamref name="T"/> is |
| 71 | + /// not a scalar type, the function is assumed to return a string of JSON that can be |
| 72 | + /// parsed as that type. |
| 73 | + /// </summary> |
| 74 | + /// <typeparam name="T">Type returned by function</typeparam> |
| 75 | + /// <param name="engine">Engine to execute function with</param> |
| 76 | + /// <param name="function">Name of the function to execute</param> |
| 77 | + /// <param name="args">Arguments to pass to function</param> |
| 78 | + /// <returns>Value returned by function</returns> |
| 79 | + public static T CallFunctionReturningJson<T>(this IJsEngine engine, string function, params object[] args) |
| 80 | + { |
| 81 | + if (ValidationHelpers.IsSupportedType(typeof(T))) |
| 82 | + { |
| 83 | + // Type is supported directly (ie. a scalar type like string/int/bool) |
| 84 | + // Just execute the function directly. |
| 85 | + return engine.CallFunction<T>(function, args); |
| 86 | + } |
| 87 | + // The type is not a scalar type. Assume the function will return its result as |
| 88 | + // JSON. |
| 89 | + var resultJson = engine.CallFunction<string>(function, args); |
| 90 | + try |
| 91 | + { |
| 92 | + return JsonConvert.DeserializeObject<T>(resultJson); |
| 93 | + } |
| 94 | + catch (JsonReaderException ex) |
| 95 | + { |
| 96 | + throw new ReactException(string.Format( |
| 97 | + "{0} did not return valid JSON: {1}.\n\n{2}", |
| 98 | + function, ex.Message, resultJson |
| 99 | + )); |
| 100 | + } |
| 101 | + } |
66 | 102 | } |
67 | 103 | } |
0 commit comments