counterfact icon indicating copy to clipboard operation
counterfact copied to clipboard

add a $.delay() function

Open pmcelhaney opened this issue 1 year ago • 2 comments

It would be nice to have a function that simulates lag.

export const GET: HTTPGet = async ($) => {
   // wait 2 seconds;
   await $.delay(2000);
   return $.response[200].json("ok"); 
}

It's a matter of adding a function to the return value of the the endpoint function in src/server/resgistry.ts

         query: castParameters(requestData.query, parameterTypes.query),
+
+        delay: async (milliseconds: number) =>
+          // eslint-disable-next-line promise/avoid-new
+          await new Promise((resolve) => {
+            setTimeout(resolve, milliseconds);
+          }),
       });

For type safety, the new property would need to be added to the RequestData type of the same file.

Extra credit

  1. Add a unit test.
  2. Add an optional second argument, so that delay(1000, 4000) will create a random delay between 1 and 4 seconds.
  3. Make it work even if we forget to put await before $.delay(...).
  4. Add an optional third argument, which is a probability distribution function.

pmcelhaney avatar Jan 17 '24 16:01 pmcelhaney

Should we also add a --delay argument to the CLI that would apply to all endpoints?

In my experience it tends to be a couple of specific endpoints that are notably slow. But I'm sure someone's going to look for a command line argument. Give the people what they want?

pmcelhaney avatar Feb 22 '24 02:02 pmcelhaney

I'd say adding it to $ is sufficient rather than delaying the entire thing. If we want to test an overall delay in the browser we can use the DevTools in Chrome (or whatever) to throttle everything.

dethell avatar Feb 22 '24 14:02 dethell