Skip to content
Merged
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
26 changes: 25 additions & 1 deletion packages/common/src/service.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ var extend = require('extend');
*/
var util = require('./util.js');

var PROJECT_ID_TOKEN = '{{projectId}}';

/**
* Service is a base class, meant to be inherited from by a "service," like
* BigQuery or Storage.
Expand Down Expand Up @@ -57,11 +59,33 @@ function Service(config, options) {
this.globalInterceptors = arrify(options.interceptors_);
this.interceptors = [];
this.packageJson = config.packageJson;
this.projectId = options.projectId || '{{projectId}}';
this.projectId = options.projectId || PROJECT_ID_TOKEN;
this.projectIdRequired = config.projectIdRequired !== false;
this.Promise = options.promise || Promise;
}

/**
* Get and update the Service's project ID.
*
* @param {function} callback - The callback function.
*/
Service.prototype.getProjectId = function(callback) {
var self = this;

this.authClient.getProjectId(function(err, projectId) {
if (err) {
callback(err);
return;
}

if (self.projectId === PROJECT_ID_TOKEN && projectId) {
self.projectId = projectId;
}

callback(null, self.projectId);
});
};

/**
* Make an authenticated API request.
*
Expand Down
45 changes: 45 additions & 0 deletions packages/common/test/service.js
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,51 @@ describe('Service', function() {
});
});

describe('getProjectId', function() {
it('should get the project ID from the auth client', function(done) {
service.authClient = {
getProjectId: function() {
done();
}
};

service.getProjectId(assert.ifError);
});

it('should return error from auth client', function(done) {
var error = new Error('Error.');

service.authClient = {
getProjectId: function(callback) {
callback(error);
}
};

service.getProjectId(function(err) {
assert.strictEqual(err, error);
done();
});
});

it('should update and return the project ID if found', function(done) {
var service = new Service({}, {});
var projectId = 'detected-project-id';

service.authClient = {
getProjectId: function(callback) {
callback(null, projectId);
}
};

service.getProjectId(function(err, projectId_) {
assert.ifError(err);
assert.strictEqual(service.projectId, projectId);
assert.strictEqual(projectId_, projectId);
done();
});
});
});

describe('request_', function() {
var reqOpts;

Expand Down