jstransformers / jstransformer

Normalize the API of any JSTransformer.
http://npm.im/jstransformer
MIT License
152 stars 12 forks source link

Support sync rendering even of async transforms #210

Open ForbesLindesay opened 7 years ago

ForbesLindesay commented 7 years ago

We could use sync-rpc to render transforms that only support async, synchronously. It would be relatively slow, but if you need it then at least it would work.

The code would look something like:

worker.js

const jstransformer = require('./');

function init(transformName) {
  const t = jstransformer(require('jstransformer-' + transformName));
  return function render({str, options, locals}) {
    // sync-rpc converts this promise into a synchronous result
    return t.renderAsync(str, options, locals);
  }
}

module.exports = init;

index.js

const syncRPC = require('sync-rpc');

// ...

Transformer.prototype.render = function (str, options, locals) {
  if (!this.can('render') && this.can('renderAsync')) {
    if (!this._syncWorker) {
      this._syncWorker = syncRPC(require.resolve('./worker.js'), this.name);
    }
    return this._syncWorker({str, options, locals});
  }

  // ... normal sync implementation here ...
}

// ...