diff --git a/types/custom-functions-runtime/custom-functions-runtime-tests.ts b/types/custom-functions-runtime/custom-functions-runtime-tests.ts index 335e5a1f95..d0733305ce 100644 --- a/types/custom-functions-runtime/custom-functions-runtime-tests.ts +++ b/types/custom-functions-runtime/custom-functions-runtime-tests.ts @@ -7,27 +7,61 @@ CustomFunctionMappings = { addTen: ADD10 }; -async function getStockValues(ticker: string, handler: CustomFunctions.StreamingHandler) { - const dollars = await (await fetch(`myService.com/prices/${ticker}`)).json(); - handler.setResult(dollars); +async function getStockValues(ticker: string): Promise { + const response = await fetch(`myService.com/prices/${ticker}`); + return (await response.json())['price']; } -async function getStockValuesOneTime(ticker: string, handler: CustomFunctions.CancelableHandler) { +async function getStockValuesCancellable( + ticker: string, + handler: CustomFunctions.CancelableHandler +): Promise { let shouldStop = false; - handler.onCanceled = () => shouldStop = true; + handler.onCanceled = () => (shouldStop = true); await pause(1000); if (shouldStop) { return null; } - const dollars = await (await fetch(`myService.com/prices/${ticker}`)).json(); - return dollars; + const response = await fetch(`myService.com/prices/${ticker}`); + return (await response.json())['price']; } -async function getStockValuesNowWithNoCancelling(ticker: string) { - const dollars = await (await fetch(`myService.com/prices/${ticker}`)).json(); - return dollars; +async function stockPriceStream( + ticker: string, + handler: CustomFunctions.StreamingHandler +) { + var updateFrequency = 10 /* milliseconds*/; + var isPending = false; + + var timer = setInterval(function() { + // If there is already a pending request, skip this iteration: + if (isPending) { + return; + } + + var url = `myService.com/prices/${ticker}`; + isPending = true; + + fetch(url) + .then(function(response) { + return response.json(); + }) + .then(function(data) { + handler.setResult(data.price); + }) + .catch(function(error) { + handler.setResult(new Error(error)); + }) + .then(function() { + isPending = false; + }); + }, updateFrequency); + + handler.onCanceled = () => { + clearInterval(timer); + }; } declare function pause(ms: number): Promise;