Skip to content

Commit 636b36a

Browse files
feat: add maybeOptionsOrCallback util method (#315)
1 parent 60ccc62 commit 636b36a

3 files changed

Lines changed: 34 additions & 2 deletions

File tree

core/common/src/util.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -740,6 +740,20 @@ export class Util {
740740

741741
return hyphenatedPackageName + '/' + packageJson.version;
742742
}
743+
744+
/**
745+
* Given two parameters, figure out if this is either:
746+
* - Just a callback function
747+
* - An options object, and then a callback function
748+
* @param optionsOrCallback An options object or callback.
749+
* @param cb A potentially undefined callback.
750+
*/
751+
maybeOptionsOrCallback<T = {}, C = (err?: Error) => void>(
752+
optionsOrCallback?: T|C, cb?: C): [T, C] {
753+
return typeof optionsOrCallback === 'function' ?
754+
[{} as T, optionsOrCallback as C] :
755+
[optionsOrCallback as T, cb as C];
756+
}
743757
}
744758

745759
const util = new Util();

core/common/test/service.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ import * as proxyquire from 'proxyquire';
2020
import {Request, RequestResponse} from 'request';
2121

2222
import {Interceptor} from '../src';
23-
import {Service, ServiceConfig, ServiceOptions} from '../src/service';
23+
import {ServiceConfig, ServiceOptions} from '../src/service';
2424
import {BodyResponseCallback, DecorateRequestOptions, MakeAuthenticatedRequest, MakeAuthenticatedRequestFactoryConfig, util, Util} from '../src/util';
2525

2626
proxyquire.noPreserveCache();

core/common/test/util.ts

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ function fakeRequest() {
5454
return (requestOverride || request).apply(null, arguments);
5555
}
5656

57-
fakeRequest.defaults = (defaultConfiguration: {}) => {
57+
fakeRequest.defaults = () => {
5858
// Ignore the default values, so we don't have to test for them in every API
5959
// call.
6060
return fakeRequest;
@@ -1505,4 +1505,22 @@ describe('common/util', () => {
15051505
assert.strictEqual(userAgent, 'gcloud-node-storage/0.1.0');
15061506
});
15071507
});
1508+
1509+
describe('maybeOptionsOrCallback', () => {
1510+
it('should allow passing just a callback', () => {
1511+
const optionsOrCallback = () => {};
1512+
const [opts, cb] = util.maybeOptionsOrCallback(optionsOrCallback);
1513+
assert.strictEqual(optionsOrCallback, cb);
1514+
assert.deepStrictEqual(opts, {});
1515+
});
1516+
1517+
it('should allow passing both opts and callback', () => {
1518+
const optionsOrCallback = {};
1519+
const callback = () => {};
1520+
const [opts, cb] =
1521+
util.maybeOptionsOrCallback(optionsOrCallback, callback);
1522+
assert.strictEqual(opts, optionsOrCallback);
1523+
assert.strictEqual(cb, callback);
1524+
});
1525+
});
15081526
});

0 commit comments

Comments
 (0)