2

Is it possible to write JavaScript code to make HTTP requests such that the the same code can be used on multiple runtimes, with a suitable utility library? In this case, it would be desirable if the code could work on node.js, Google App Script and as a Google Chrome extension or ChromeOS app.

The problem is that these different runtimes have different kinds of APIs and different capabilities to accomodate programming styles. App Script provides URLFetchApp, which is synchronous. Chrome and other browsers support XMLHttpRequst, which is asynchronous. Node.js supports both asynchronous and synchronous programming, and varying styles can be combined using fibers, for example. However, fibers are not supported on other runtimes. Google App Script, on the other hand, does not seem to support plugging in asynchronous code using async/await.

It seems that it is not possible to write code that supports all these runtimes without some kind of pre-processing the code.

Juho Östman
  • 1,544
  • 1
  • 12
  • 20
  • 1
    This is not a great type of Q for stack overflow, but look at `axios` – Joe Mar 14 '19 at 12:57
  • You need some kind of wrapper that has adapters for all APIs you intend to support. Likely promise-based. You may want to stick to Fetch where possible since it's standardized. Sync code can be converted to async but not vice versa. If some of APIs don't support async then either have two forks or try workarounds like https://stackoverflow.com/questions/49114450/google-apps-script-async-function-execution-on-server-side – Estus Flask Mar 14 '19 at 14:14

1 Answers1

1

It is possible, following those steps:

  • When serving the HTTP request abstraction you should check which HTTP methods are provided in the current environment
  • Import request abstraction normalized(IE to be always async and always return a promise)
  • The request abstraction should provide the same interface to its functionality(GET/POST/DELETE/PUT/PATCH)
Mosè Raguzzini
  • 15,399
  • 1
  • 31
  • 43
  • This works for node.js and browser support but not Google App Script, unless it can be made to support asynchronous code. – Juho Östman Mar 14 '19 at 13:10
  • 1
    You can wrap IE UrlFetchApp in your own ES6 promise structure and get it async anyway. Take a look at http://ramblings.mcpher.com/Home/excelquirks/gassnips/promisesandappsscript – Mosè Raguzzini Mar 14 '19 at 13:17
  • @Mose That would need client side scripting to say the least. – TheMaster Mar 14 '19 at 13:46