Skip to content

Commit

Permalink
implement Readable by passing option (#43)
Browse files Browse the repository at this point in the history
  • Loading branch information
cm-ayf authored May 27, 2024
1 parent dafb14b commit 6eeb117
Showing 1 changed file with 31 additions and 54 deletions.
85 changes: 31 additions & 54 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,59 +21,6 @@ exports.OM_SYRINX_VERSION = OM_SYRINX_VERSION;

const { setTimeout } = require("node:timers/promises");

class SyrinxStream extends Readable {
/**
* @param {import("./native").Syrinx} syrinx
* @param {boolean} objectMode
* @param {string} inputText
* @param {import("./native").SynthesisOption} option
*/
constructor(syrinx, objectMode, inputText, option) {
super({ objectMode });
/**
* @type {import("./native").Syrinx}
* @private
*/
this._syrinx = syrinx;
/**
* @type {string}
* @private
*/
this._inputText = inputText;
/**
* @type {import("./native").SynthesisOption}
* @private
*/
this._option = option;
}

/**
* @param {(error?: Error | null) => void} callback
*/
async _construct(callback) {
/** @type {[import("./native").PreparedSynthesizer, null] | [null, Error]} */
const [synthesizer, error] = await this._syrinx
.prepare(this._inputText, this._option)
.then(
(s) => [s, null],
(e) => [null, e],
);
callback(error);

await synthesizer?.synthesize((err, result) => {
if (err) this.emit("error", err);
else this.push(result);
});

// The last push sometimes occurs after the Promise resolution,
// so we need to make sure that the last push occurs before the stream ends.
await setTimeout();
this.push(null);
}

_read() {}
}

class Syrinx {
/**
* @param {import("./native").SyrinxConfig} config
Expand Down Expand Up @@ -117,7 +64,37 @@ class Syrinx {
* @returns {Readable}
*/
synthesize(inputText, option) {
return new SyrinxStream(this._inner, this._objectMode, inputText, option);
const { _inner } = this;

return new Readable({
objectMode: this._objectMode,

/**
* @param {(error?: Error | null) => void} callback
*/
async construct(callback) {
/** @type {[import("./native").PreparedSynthesizer, null] | [null, Error]} */
const [synthesizer, error] = await _inner
.prepare(inputText, option)
.then(
(s) => [s, null],
(e) => [null, e],
);
callback(error);

await synthesizer?.synthesize((err, result) => {
if (err) this.emit("error", err);
else this.push(result);
});

// The last push sometimes occurs after the Promise resolution,
// so we need to make sure that the last push occurs before the stream ends.
await setTimeout();
this.push(null);
},

read() {},
});
}
}

Expand Down

0 comments on commit 6eeb117

Please sign in to comment.