Skip to content

Instantly share code, notes, and snippets.

@florabtw
Created July 4, 2019 04:02
Show Gist options
  • Save florabtw/4d94970859c679a3884bfe7d00709f52 to your computer and use it in GitHub Desktop.
Save florabtw/4d94970859c679a3884bfe7d00709f52 to your computer and use it in GitHub Desktop.
Sound of Text - Browser client
const soundoftext = (() => {
const API_URL = 'https://api.soundoftext.com';
const urls = {
base: 'https://api.soundoftext.com',
request: () => `${urls.base}/sounds`,
status: id => `${urls.base}/sounds/${id}`,
};
const bodies = {
request: ({engine = 'Google', text, voice}) =>
JSON.stringify({engine, data: {text, voice}}),
};
const options = {
default: {
headers: {
'Content-Type': 'application/json',
'User-Agent': 'SoundOfTextClient',
},
},
request: ({text, voice}) => ({
...options.default,
method: 'POST',
body: bodies.request({text, voice}),
}),
status: () => ({...options.default, method: 'GET'}),
};
const request = (url, options) =>
fetch(url, options)
.then(res => res.json())
.then(res => (res.message ? Promise.reject(res.message) : res));
const retry = (func, timeout) =>
new Promise(resolve => setTimeout(() => resolve(func()), timeout));
const location = ({id, timeout = 1000}) =>
operations.status({id}).then(res => {
if (res.status == 'Error') throw res.message;
if (res.status == 'Done') return res.location;
if (timeout > 30 * 1000) throw 'Operation timed out';
return retry(() => location({id, timeout: timeout * 2}), timeout);
});
const create = ({text, voice}) =>
operations.request({text, voice}).then(operations.location);
const operations = {
create,
location,
request: ({text, voice}) =>
request(urls.request(), options.request({text, voice})),
status: ({id}) => request(urls.status(id), options.status()),
};
const client = {sounds: operations};
return client;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment