Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,14 @@ Disclaimer: This project is still under heavy development and the API is likely

# API

The client returns promises from `init`, `renderComponent`,
`renderComponents`, `getComponentsInfo`, and `renderTemplate` when the callback
is omitted. The promise resolves with the callback's first success value and
rejects with its error value: `renderComponent` and `renderTemplate` resolve to
HTML, while `renderComponents` resolves to the HTML array. Existing callback
forms keep their original return values and timing, and emit one
`DeprecationWarning` per process.

* [new Client()](#new-clientoptions)
* [Client#init()](#clientinitoptions-callback)
* [Client#getComponentsInfo()](#clientgetcomponentsinfocomponents-callback)
Expand Down
115 changes: 92 additions & 23 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,29 @@ const validator = require('./validator');
const Warmup = require('./warmup');
const _ = require('./utils/helpers');

const warningStoreKey = Symbol.for('opencomponents.deprecation-warnings');
const callbackWarningId = 'node-oc-client-callback-api';

const warnAboutCallbacks = () => {
const warned = process[warningStoreKey] || new Set();
process[warningStoreKey] = warned;
if (warned.has(callbackWarningId)) {
return;
}

warned.add(callbackWarningId);
process.emitWarning(
'The callback API of the Node.js oc-client is deprecated and will be removed in OpenComponents v1 - use the returned promises instead.',
'DeprecationWarning'
);
};

const toComponent = (componentName, options) => ({
name: componentName,
version: options.version,
parameters: options.parameters || options.params
});

module.exports = function(conf) {
const config = sanitiser.sanitiseConfiguration(conf);
const validationResult = validator.validateConfiguration(config);
Expand All @@ -30,46 +53,92 @@ module.exports = function(conf) {
}

return {
supportsPromiseApi: true,
init: function(options, callback) {
const _renderComponents = options.renderComponents || renderComponents;
const warmup = new Warmup(config, _renderComponents);
return warmup(options, callback);
if (_.isFunction(options)) {
callback = options;
options = {};
}
options = options || {};

if (_.isFunction(callback)) {
warnAboutCallbacks();
const _renderComponents = options.renderComponents || renderComponents;
return new Warmup(config, _renderComponents)(options, callback);
}

return new Promise((resolve, reject) => {
const _renderComponents = options.renderComponents || renderComponents;
const warmup = new Warmup(config, _renderComponents);
warmup(options, (error, result) =>
error ? reject(error) : resolve(result)
);
});
},
renderComponent: function(componentName, options, callback) {
if (_.isFunction(options)) {
callback = options;
options = {};
}
options = options || {};
const components = [toComponent(componentName, options)];

renderComponents(
[
{
name: componentName,
version: options.version,
parameters: options.parameters || options.params
}
],
options,
(errors, results, details) => {
if (errors) {
return callback(errors[0], results[0], details[0]);
}

callback(null, results[0], details[0]);
}
);
if (_.isFunction(callback)) {
warnAboutCallbacks();
return renderComponents(
components,
options,
(errors, results, details) =>
callback(errors ? errors[0] : null, results[0], details[0])
);
}

return new Promise((resolve, reject) => {
renderComponents(components, options, (errors, results) =>
errors ? reject(errors[0]) : resolve(results[0])
);
});
},
renderComponents: function(components, options, callback) {
if (_.isFunction(options)) {
callback = options;
options = {};
}

renderComponents(components, options, callback);
if (_.isFunction(callback)) {
warnAboutCallbacks();
return renderComponents(components, options, callback);
}

return new Promise((resolve, reject) => {
renderComponents(components, options, (errors, results) =>
errors ? reject(errors) : resolve(results)
);
});
},
getComponentsInfo: function(components, callback) {
getComponentsInfo(components, callback);
if (_.isFunction(callback)) {
warnAboutCallbacks();
return getComponentsInfo(components, callback);
}

return new Promise((resolve, reject) => {
getComponentsInfo(components, (error, result) =>
error ? reject(error) : resolve(result)
);
});
},
renderTemplate: renderTemplate
renderTemplate: function(template, model, options, callback) {
if (_.isFunction(callback)) {
warnAboutCallbacks();
return renderTemplate(template, model, options, callback);
}

return new Promise((resolve, reject) => {
renderTemplate(template, model, options, (error, html) =>
error ? reject(error) : resolve(html)
);
});
}
};
};
144 changes: 144 additions & 0 deletions test/unit/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,148 @@ describe('client', () => {
expect(init).to.throw('argh!');
});
});

describe('promise and callback APIs', () => {
const warningStoreKey = Symbol.for('opencomponents.deprecation-warnings');
let client;
let renderComponents;
let getComponentsInfo;
let renderTemplate;
let warmup;
let emitWarning;
let previousWarningStore;

const rejectionOf = async promise => {
try {
await promise;
} catch (error) {
return error;
}
throw new Error('Expected promise to reject');
};

beforeEach(() => {
initialise();
validatorStub.returns({ isValid: true });
renderComponents = sinon.stub().yields(null, ['<p>hello</p>'], [{}]);
getComponentsInfo = sinon.stub().yields(null, [{ name: 'hello' }]);
renderTemplate = sinon.stub().yields(null, '<p>template</p>');
warmup = sinon.stub().yields(null, { hello: '<p>hello</p>' });
previousWarningStore = process[warningStoreKey];
delete process[warningStoreKey];
emitWarning = sinon.stub(process, 'emitWarning');
client = injectr(
'../../src/index.js',
{
'./validator': { validateConfiguration: validatorStub },
'./components-renderer': function() {
return renderComponents;
},
'./get-components-info': function() {
return getComponentsInfo;
},
'./template-renderer': function() {
return renderTemplate;
},
'./warmup': function() {
return warmup;
}
},
{ __dirname: '/something/', console: console, process }
)({});
});

afterEach(() => {
emitWarning.restore();
if (previousWarningStore) {
process[warningStoreKey] = previousWarningStore;
} else {
delete process[warningStoreKey];
}
});

it('returns the first success value from every promise API', async () => {
expect(await client.init()).to.eql({ hello: '<p>hello</p>' });
expect(await client.renderComponent('hello')).to.equal('<p>hello</p>');
expect(await client.renderComponents([{ name: 'hello' }])).to.eql([
'<p>hello</p>'
]);
expect(await client.getComponentsInfo([{ name: 'hello' }])).to.eql([
{ name: 'hello' }
]);
expect(await client.renderTemplate('template', {}, {})).to.equal(
'<p>template</p>'
);
expect(emitWarning.called).to.be.false;
});

it('rejects with the original callback errors', async () => {
const error = new Error('failed');
warmup.yields(error);
expect(await rejectionOf(client.init())).to.equal(error);

renderComponents.yields([error], ['fallback'], [{}]);
expect(await rejectionOf(client.renderComponent('hello'))).to.equal(
error
);
expect(
await rejectionOf(client.renderComponents([{ name: 'hello' }]))
).to.eql([error]);

getComponentsInfo.yields([error]);
expect(
await rejectionOf(client.getComponentsInfo([{ name: 'hello' }]))
).to.eql([error]);

renderTemplate.yields(error);
expect(
await rejectionOf(client.renderTemplate('template', {}, {}))
).to.equal(error);
});

it('preserves synchronous exceptions as promise rejection reasons', async () => {
const error = new Error('synchronous failure');
renderComponents.resetBehavior();
renderComponents.throws(error);

expect(await rejectionOf(client.renderComponent('hello'))).to.equal(
error
);
});

it('preserves direct callback behavior and warns once', () => {
const callback = sinon.spy();

expect(client.init(callback)).to.be.undefined;
expect(client.renderComponent('hello', callback)).to.be.undefined;
expect(client.renderComponents([{ name: 'hello' }], callback)).to.be
.undefined;
expect(client.getComponentsInfo([{ name: 'hello' }], callback)).to.be
.undefined;
expect(client.renderTemplate('template', {}, {}, callback)).to.be
.undefined;

expect(callback.callCount).to.equal(5);
expect(callback.secondCall.args).to.eql([null, '<p>hello</p>', {}]);
expect(emitWarning.calledOnce).to.be.true;
expect(emitWarning.firstCall.args[0]).to.contain('Node.js oc-client');
expect(emitWarning.firstCall.args[1]).to.equal('DeprecationWarning');
});

it('does not swallow exceptions thrown by legacy callbacks', () => {
expect(() =>
client.renderComponent('hello', () => {
throw new Error('callback failed');
})
).to.throw('callback failed');
});

it('shares warning identity with the core deprecation utility', () => {
process[warningStoreKey] = new Set(['node-oc-client-callback-api']);

client.renderComponent('hello', () => {});

expect(emitWarning.called).to.be.false;
});
});
});