Added node-modules

This commit is contained in:
Dobie Wollert
2014-09-14 07:04:16 -04:00
parent 663941bf57
commit 6a92348cf5
4870 changed files with 670395 additions and 0 deletions

41
node_modules/googleapis/lib/auth/authclient.js generated vendored Normal file
View File

@ -0,0 +1,41 @@
/**
* Copyright 2012 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var DefaultTransporter = require('../transporters.js');
function AuthClient() {
this.transporter = new DefaultTransporter();
}
/**
* Provides an alternative request
* implementations with auth credentials.
*/
AuthClient.prototype.request = function() {
throw new Error('Not implemented yet.');
};
/**
* Sets auth credentials.
* @param {object} credentials Credentials.
*/
AuthClient.prototype.setCredentials = function(credentials) {
this.credentials = credentials;
};
/**
* Export AuthClient.
*/
module.exports = AuthClient;

79
node_modules/googleapis/lib/auth/computeclient.js generated vendored Normal file
View File

@ -0,0 +1,79 @@
/**
* Copyright 2013 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var querystring = require('querystring');
var Auth2Client = require('./oauth2client.js');
var util = require('util');
/**
* @private
* Google Compute Engine metadata server token endpoint.
*/
Compute.GOOGLE_OAUTH2_TOKEN_URL_ =
'http://metadata/computeMetadata/v1beta1/instance/service-accounts/default/token';
/**
* @constructor
* Google Compute Engine service account credentials.
*
* Retrieve access token from the metadata server.
* See: https://developers.google.com/compute/docs/authentication
*
*/
function Compute() {
Compute.super_.call(this);
}
/**
* Inherit from Auth2Client.
*/
util.inherits(Compute, Auth2Client);
/**
* Get the initial access token from compute metadata server.
* @param {function=} opt_callback Optional callback.
*/
Compute.prototype.authorize = function(opt_callback) {
var that = this;
that.refreshToken_(null, function(err, result) {
if (!err) {
that.credentials = result;
that.credentials.refresh_token = 'compute-placeholder';
}
opt_callback && opt_callback(err, result);
});
};
/**
* @private
* Refreshes the access token.
* @param {object=} ignored_
* @param {function=} opt_callback Optional callback.
*/
Compute.prototype.refreshToken_ = function(ignored_, opt_callback) {
var uri = this.opts.tokenUrl || Compute.GOOGLE_OAUTH2_TOKEN_URL_;
// request for new token
this.transporter.request({
method: 'GET',
uri: uri,
json: true
}, opt_callback);
};
/**
* Export Compute.
*/
module.exports = Compute;

199
node_modules/googleapis/lib/auth/oauth2client.js generated vendored Normal file
View File

@ -0,0 +1,199 @@
/**
* Copyright 2012 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var querystring = require('querystring');
var AuthClient = require('./authclient.js');
var util = require('util');
function OAuth2Client(clientId, clientSecret, redirectUri, opt_opts) {
OAuth2Client.super_.call(this);
this.clientId_ = clientId;
this.clientSecret_ = clientSecret;
this.redirectUri_ = redirectUri;
this.opts = opt_opts || {};
this.credentials = null;
}
/**
* Inherit from AuthClient.
*/
util.inherits(OAuth2Client, AuthClient);
/**
* The base URL for auth endpoints.
* @const
* @private
*
*/
OAuth2Client.GOOGLE_OAUTH2_AUTH_BASE_URL_ =
'https://accounts.google.com/o/oauth2/auth';
/**
* The base endpoint for token retrieval.
* @const
* @private
* The ..
*/
OAuth2Client.GOOGLE_OAUTH2_TOKEN_URL_ =
'https://accounts.google.com/o/oauth2/token';
/**
* The base endpoint to revoke tokens.
* @const
* @private
*/
OAuth2Client.GOOGLE_OAUTH2_REVOKE_URL_ =
'https://accounts.google.com/o/oauth2/revoke';
/**
* Generates URL for consent page landing.
* @param {object=} opt_opts Options.
* @return {string} URL to consent page.
*/
OAuth2Client.prototype.generateAuthUrl = function(opt_opts) {
var opts = opt_opts || {};
opts.response_type = opts.response_type || 'code';
opts.client_id = this.clientId_;
opts.redirect_uri = this.redirectUri_;
var rootUrl = this.opts.authBaseUrl ||
OAuth2Client.GOOGLE_OAUTH2_AUTH_BASE_URL_;
return rootUrl + '?' + querystring.stringify(opts);
};
/**
* Gets the access token for given code.
* @param {string} code The authorization code.
* @param {function=} opt_callback Optional callback fn.
*/
OAuth2Client.prototype.getToken = function(code, opt_callback) {
var uri = this.opts.tokenUrl || OAuth2Client.GOOGLE_OAUTH2_TOKEN_URL_;
var values = {
code: code,
client_id: this.clientId_,
client_secret: this.clientSecret_,
redirect_uri: this.redirectUri_,
grant_type: 'authorization_code'
};
this.transporter.request({
method: 'POST',
uri: uri,
form: values,
json: true
}, opt_callback);
};
/**
* @private
* Refreshes the access token.
* @param {string} refresh_token Existing refresh token.
* @param {function=} opt_callback Optional callback.
*/
OAuth2Client.prototype.refreshToken_ =
function(refresh_token, opt_callback) {
var uri = this.opts.tokenUrl || OAuth2Client.GOOGLE_OAUTH2_TOKEN_URL_;
var values = {
refresh_token: refresh_token,
client_id: this.clientId_,
client_secret: this.clientSecret_,
grant_type: 'refresh_token'
};
// request for new token
this.transporter.request({
method: 'POST',
uri: uri,
form: values,
json: true
}, opt_callback);
};
/**
* Revokes the access given to token.
* @param {string} token The existing token to be revoked.
* @param {function=} opt_callback Optional callback fn.
*/
OAuth2Client.prototype.revokeToken = function(token, opt_callback) {
this.transporter.request({
uri: OAuth2Client.GOOGLE_OAUTH2_REVOKE_URL_ +
'?' + querystring.stringify({ token: token }),
json: true
}, opt_callback);
};
/**
* Provides a request implementation with OAuth 2.0 flow.
* If credentials have a refresh_token, in cases of HTTP
* 401 and 403 responses, it automatically asks for a new
* access token and replays the unsuccessful request.
* @param {object} opts Request options.
* @param {function=} opt_callback Optional callback.
* @param {boolean=} opt_dontForceRefresh If set, don't ask for a new token
* with refresh_token.
*/
OAuth2Client.prototype.request =
function(opts, opt_callback, opt_dontForceRefresh) {
var that = this;
var credentials = this.credentials;
if (!credentials.access_token && !credentials.refresh_token) {
throw new Error('No access or refresh token is set.');
}
credentials.token_type = credentials.token_type || 'Bearer';
opts.headers = opts.headers || {};
opts.headers['Authorization']
= credentials.token_type + ' ' + credentials.access_token;
this.transporter.request(opts, function(err, body, res) {
var hasAuthError = false;
// TODO(burcud): Should we redo requests without
// an auth error? This question will be invalid when we switch
// to multi part batch requests.
err && err.forEach(function(e) {
hasAuthError = (e.code == 401 || e.code == 403);
});
// if there is an auth error, refresh the token
// and make the request again
if (!opt_dontForceRefresh && hasAuthError && credentials.refresh_token) {
// refresh access token and re-request
that.refreshToken_(credentials.refresh_token, function(err, result) {
if (err) {
opt_callback && opt_callback(err, null, null);
} else {
var tokens = result;
tokens.refresh_token = credentials.refresh_token;
that.credentials = tokens;
that.request(opts, opt_callback, true);
}
});
} else {
opt_callback && opt_callback(err, body, res);
}
});
};
/**
* Export OAuth2Client.
*/
module.exports = OAuth2Client;

112
node_modules/googleapis/lib/cache.js generated vendored Normal file
View File

@ -0,0 +1,112 @@
/**
* Copyright 2013 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var fs = require('fs');
/**
* @const
* @private
* Path to the temporary directory.
* @type {String}
*/
Cache.TMP_DIR_ = __dirname + '/../.cache';
/**
* @const
* @private
* Default encoding for cached files.
* @type {String}
*/
Cache.ENCODING_ = 'utf-8';
/**
* @const
* @private
* Default expires time in micro seconds.
* @type {Number}
*/
Cache.EXPIRES_IN_ = 5 * 60 * 1000;
/**
* @constructor
* Cache constructor.
* @param {String} opt_opts Optional options.
*/
function Cache(opt_opts) {
this.opts = opt_opts || {};
this.opts.path = this.opts.path || Cache.TMP_DIR_;
if (!fs.existsSync(this.opts.path)) {
fs.mkdirSync(this.opts.path, '700');
}
}
/**
* Loads discovery data from cache
* @param {object} api
* @return {object?} Returns the cached discovery data if exists
* or not expired.
*/
Cache.prototype.load = function(api) {
var path = this.getPath(api);
// check if file exists and not expired
if (!fs.existsSync(path)) {
return null;
}
if (this.isExpired(path)) {
// delete the expired cache file
fs.unlinkSync(path);
return null;
}
var data = fs.readFileSync(this.getPath(api), Cache.ENCODING_);
return data && JSON.parse(data);
};
/**
* Writes api discovery data to the cache.
* @param {object} api
* @param {object} data
*/
Cache.prototype.write = function(api, data) {
data && fs.writeFileSync(
this.getPath(api), JSON.stringify(data), Cache.ENCODING_);
};
/**
* Checks whether the file at path is expired or not
* @param {[type]} path The path of the file to check.
* @return {Boolean} Returns true or false depending on the expiration.
*/
Cache.prototype.isExpired = function(path) {
var expiresIn = this.opts.expiresIn || Cache.EXPIRES_IN_;
return new Date(fs.statSync(path).mtime).getTime() - expiresIn < 0;
};
/**
* Gets the path where the api data is stored at.
* @param {[type]} api
* @return {string} Path to the data file.
*/
Cache.prototype.getPath = function(api) {
return this.opts.path + '/' + api.name + api.version;
};
/**
* Exports Cache.
* @type {Cache}
*/
module.exports = Cache;

140
node_modules/googleapis/lib/client.js generated vendored Normal file
View File

@ -0,0 +1,140 @@
/**
* Copyright 2012 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var Request = require('./requests.js').Request;
var BatchRequest = require('./requests.js').BatchRequest;
/**
* Constructs a new client with given API name and version.
* @constructor
*
* @param {object} apiMeta Schema returned by Discovery API.
*/
function Client(apiMeta) {
this.apiMeta = apiMeta;
this.authClient = null;
// generate helper methods
this.registerHelpers_();
}
/**
* Gets the API's name.
* @return {String}
*/
Client.prototype.getName = function() {
return this.apiMeta.name;
};
/**
* Gets the API's version.
* @return {String}
*/
Client.prototype.getVersion = function() {
return this.apiMeta.version;
};
/**
* @private
* Registers request builders for existing API methods.
*/
Client.prototype.registerHelpers_ = function() {
for (var i in this.apiMeta.methods) {
var methodMeta = this.apiMeta.methods[i];
this.extend_(this, methodMeta.id, this.generateHelper_(methodMeta));
}
};
/**
* @private
* TODO(burcud): move to utils
*
* @param {?object} root Object to be extended.
* @param {string} key Full key.
* @param {?object} obj Object to extend root object with.
* @return {object} Extended object.
*/
Client.prototype.extend_ = function(root, key, obj) {
if (!root) root = {};
var namespaceKeys = key.split('.');
var chain = root;
// avoid the client name
for (var i = 1; i < namespaceKeys.length; i++) {
var chainKey = namespaceKeys[i];
// if this is the last key, put obj in it.
if (i == namespaceKeys.length - 1) {
chain[chainKey] = obj;
} else if (!chain[chainKey]) {
chain[chainKey] = {};
}
// move to the next key
chain = chain[chainKey];
}
return root;
};
/**
* @private
* Generate a request builder helper.
*
* @param {object} methodMeta Method's schema returned by Discovery API.
* @return {Function} Function generated by methodMeta.
*/
Client.prototype.generateHelper_ = function(methodMeta) {
var that = this;
// generates a function to make a request
// to the resource on given method
return function(params, resource) {
return that.newRequest(methodMeta.id, params, resource);
};
};
/**
* Constructs a request to method with given parameters.
*
* @param {string} methodName Full name of the method.
* @param {?object} params Parameters.
* @param {object=} opt_resource Optional resource.
*
* @return {Request} New Request object constructed with given args.
*/
Client.prototype.newRequest = function(methodName, params, opt_resource) {
return new Request(this.apiMeta, methodName, params, opt_resource)
.withAuthClient(this.authClient);
};
/**
* Adds global auth client.
*
* @param {auth.AuthClient} client An auth client instance.
*
* @return {Client} Returns itself.
*/
Client.prototype.withAuthClient = function(client) {
this.authClient = client;
return this;
};
/**
* Exporting Client.
*/
module.exports = Client;

268
node_modules/googleapis/lib/googleapis.js generated vendored Normal file
View File

@ -0,0 +1,268 @@
/**
* Copyright 2012 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var async = require('async'),
Cache = require('./cache.js'),
Client = require('./client.js'),
DefaultTransporter = require('./transporters.js'),
qs = require('querystring'),
requests = require('./requests.js'),
fs = require('fs');
/**
* @constructor
* GoogleApisClient constructor.
*/
function GoogleApisClient() {
this.clients = [];
this.ops = {};
this.authClient = null;
}
/**
* Add a new individual client to the instance.
* @param {String} name
* @param {Client} client
*/
GoogleApisClient.prototype.add = function(name, client) {
this[name] = client.withAuthClient(this.authClient);
};
/**
* Creates a new batch request.
* @return {BatchRequest} New batch request.
*/
GoogleApisClient.prototype.newBatchRequest = function() {
return new requests.BatchRequest()
.withAuthClient(this.authClient);
};
/**
* Adds global auth client.
*
* @param {auth.AuthClient} client An auth client instance.
*
* @return {Client} Returns itself.
*/
GoogleApisClient.prototype.withAuthClient = function(client) {
this.authClient = client;
return this;
};
/**
* @constructor
* GoogleApis constructor.
*/
function GoogleApis() {
this.opts = {};
this.toBeDiscovered = [];
this.transporter = exports.Transporter || new DefaultTransporter();
this.authClient = null;
}
/**
* @const
* @private
* Base path for discovery API.
* @type {string}
*/
GoogleApis.BASE_DISCOVERY_URL_ =
'https://www.googleapis.com/discovery/v1/apis/';
/**
* @const
* @private
* Discovery type.
* @type {string}
*/
// TODO(burcud): Switch to REST.
GoogleApis.DISCOVERY_TYPE_ = 'rpc';
/**
* @const
* @private
* Additional discovery parameters.
* @type {object}
*/
GoogleApis.DISCOVERY_PARAMS_ = null;
/**
* Discover the API with the given name, version and opt options.
* @param {String} name The name of the API.
* @param {String} version The version of the API.
* @param {Object} opt_opts Additional options.
* @return {GoogleApis} Returns itself.
*/
GoogleApis.prototype.discover = function(name, version, opt_opts) {
this.toBeDiscovered.push({
name: name, version: version, opts: opt_opts });
return this;
};
/**
* Executes requests to discover APIs.
* @param {Function=} opt_callback
*/
GoogleApis.prototype.execute = function(opt_callback) {
var that = this,
operations = [],
client = new GoogleApisClient()
.withAuthClient(this.authClient);
this.toBeDiscovered.forEach(function(obj) {
operations.push(function(callback) {
that.load.call(that, obj, callback);
});
});
async.parallel(operations, function(err, results) {
if (err) {
opt_callback && opt_callback(err, null);
} else {
results = results || [];
results.forEach(function(result) {
// extend client object with indivual clients.
client.add(result.getName(), result);
});
opt_callback && opt_callback(null, client);
}
});
};
/**
* Generates a client through discovery API.
* @param {String} api An object to represent the api name, version and opts.
* @param {Function=} opt_callback Optional callback function.
*/
GoogleApis.prototype.load = function(api, opt_callback) {
var that = this;
var cache = new Cache(this.opts.cache);
if (api.opts && api.opts.localDiscoveryFilePath) {
that.loadFromFile(api.opts.localDiscoveryFilePath, opt_callback);
return;
}
var generateClient = function(err, data) {
var client = null;
if (!err && data) {
cache.write(api, data);
client = new Client(data);
}
opt_callback && opt_callback(err, client);
};
var data = cache.load(api);
if (data) {
generateClient(null, data);
} else {
that.transporter.request({
uri: that.generateDiscoveryUrl(api), json: true
}, generateClient);
}
};
/**
* Generates a client from a local discovery file.
* @param {String} filename Path of the local discovery file.
* @param {Function=} opt_callback Optional callback function.
*/
GoogleApis.prototype.loadFromFile = function(filename, opt_callback) {
fs.readFile(filename, function(err, data) {
var client = null;
if (!err && data) {
client = new Client(JSON.parse(data));
}
opt_callback && opt_callback(err, client);
});
};
/**
* Generates the discovery url.
* @param {String} api An object to represent the api name, version and opts.
* @return {string} discoveryUrl.
*/
GoogleApis.prototype.generateDiscoveryUrl = function(api) {
api.opts = api.opts || {};
var baseDiscoveryUrl = api.opts.baseDiscoveryUrl ||
GoogleApis.BASE_DISCOVERY_URL_;
var discoveryParams = api.opts.discoveryParams ||
GoogleApis.DISCOVERY_PARAMS_;
var discoveryUrl = baseDiscoveryUrl;
discoveryUrl += encodeURIComponent(api.name) +
'/' + encodeURIComponent(api.version) +
'/' + GoogleApis.DISCOVERY_TYPE_;
if (discoveryParams) {
discoveryUrl += '?' + qs.stringify(discoveryParams);
}
return discoveryUrl;
};
/**
* Adds options.
*
* @param {object} opts Options.
* @return {GoogleApis} Returns itself.
*/
GoogleApis.prototype.withOpts = function(opts) {
this.opts = opts;
return this;
};
/**
* Adds global auth client.
*
* @param {auth.AuthClient} client An auth client instance.
* @return {GoogleApis} Returns itself.
*/
GoogleApis.prototype.withAuthClient = function(client) {
this.authClient = client;
return this;
};
var googleapis = new GoogleApis();
/**
* Shortcut to GoogleApis.
*/
googleapis.GoogleApis = GoogleApis;
/**
* Shortcut to OAuth2Client.
*/
googleapis.OAuth2Client = require('./auth/oauth2client.js');
/**
* Shortcut to Auth.
*/
googleapis.auth = {
Compute: require('./auth/computeclient.js'),
OAuth2Client: googleapis.OAuth2Client
};
/**
* Exports googleapis.
*/
module.exports = googleapis;
/**
* Exports Transporter.
*/
exports.Transporter = null;

286
node_modules/googleapis/lib/requests.js generated vendored Normal file
View File

@ -0,0 +1,286 @@
/**
* Copyright 2012 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var util = require('util');
var querystring = require('querystring');
var DefaultTransporter = require('./transporters.js');
function BaseRequest(apiMeta) {
this.transporter = new DefaultTransporter();
this.authClient = null;
this.apiKey = null;
}
/**
* @const
* @type {String}
*/
BaseRequest.JSONRPC_VERSION = '2.0';
/**
* @const
* @type {String}
*/
BaseRequest.JSONRPC_URL = 'https://www.googleapis.com/rpc';
/**
* Sets the auth client.
* @param {AuthClient} client An auth client instance.
* @return {BaseRequest} Returns itself.
*/
BaseRequest.prototype.withAuthClient = function(client) {
this.authClient = client;
return this;
};
/**
* Sets an API key.
* @param {String} apiKey
* @return {BaseRequest} Returns itself.
*/
BaseRequest.prototype.withApiKey = function(apiKey) {
this.apiKey = apiKey;
return this;
};
/**
* Returns true if request requires a parameter.
* If no metadata is known about the request's method, true is returned.
* @return {boolean} Returns whether a parameter is required or not.
*/
BaseRequest.prototype.doesRequireParams = function() {
if (!this.apiMeta || !this.apiMeta.methods ||
!this.apiMeta.methods[this.methodName]) {
// nothing to do here, dont have enough
// info about the parameters
return true;
}
var methodMeta = this.apiMeta.methods[this.methodName];
for (var i in methodMeta.parameters) {
if (methodMeta.parameters[i].required) {
return true;
}
}
return false;
};
/**
* @protected
* Generates uri end-point with given params.
*
* @param {object=} opt_params Query parameters or null.
* @return {string} Generated uri.
*/
BaseRequest.prototype.generateUri = function(opt_params) {
var url = BaseRequest.JSONRPC_URL;
opt_params = opt_params || {};
if (this.apiKey) {
opt_params.key = this.apiKey;
}
var params = querystring.stringify(opt_params);
if (params) {
url += '?' + params;
}
return url;
};
/**
* @protected
* Generates payload body of the request.
* @return {object?} Request payload.
*/
BaseRequest.prototype.generatePayload = function() {
return null;
};
/**
* Executes the batch request.
*
* @param {Function=} opt_callback Optional callback function.
*/
BaseRequest.prototype.execute = function(opt_callback) {
// TODO(burcud): Switch to REST.
opt_callback = opt_callback || function() {};
var callback = this.handleResponse(opt_callback);
var requestOpts = {
method: 'POST',
uri: this.generateUri(),
json: this.generatePayload()
};
if (this.authClient) {
this.authClient.request(requestOpts, callback);
} else {
// make the request with default client
this.transporter.request(requestOpts, callback);
}
};
/**
* @protected
* Wraps request callbacks.
*
* @param {Function=} opt_fn Optional callback function to be wrapped.
* @return {Function} Wrapped callback function.
*/
BaseRequest.prototype.handleResponse = function(opt_fn) {
throw new Error('Not implemented...');
};
/**
* Constructs a new Request.
* @constructor
*
* @param {object} apiMeta Schema returned by Discovery API.
* @param {string} methodName Method name.
* @param {?object} opt_params Required Parameters. If none are required,
* expected to be not passed.
* @param {object=} opt_resource Optional resource.
*/
function Request(
apiMeta, methodName, opt_params, opt_resource) {
Request.super_.call(this);
this.apiMeta = apiMeta;
this.methodName = methodName;
if (!this.doesRequireParams() && !opt_resource) {
this.params = {};
this.resource = opt_params;
} else {
this.params = opt_params || {};
this.resource = opt_resource;
}
}
/**
* Inherits from BaseRequest.
*/
util.inherits(Request, BaseRequest);
/**
* Generates JSON-RPC payload with a single request.
* @return {Array.<object>} Returns request payload.
*/
Request.prototype.generatePayload = function() {
this.params.resource = this.resource;
console.dir(this.params);
var request = {
jsonrpc: BaseRequest.JSONRPC_VERSION,
id: 0,
method: this.methodName,
params: this.params,
apiVersion: this.apiMeta.version
};
return [request];
};
/**
* Handles response.
* @param {Function=} opt_fn Optional callback function.
* @return {Function} Wraps response callback and returns.
*/
Request.prototype.handleResponse = function(opt_fn) {
return function(err, results, res) {
var result = results && results[0] && results[0].result;
err = err && util.isArray(err) ? err[0] : err;
opt_fn && opt_fn(err, result, res);
};
};
/**
* Constructs a new batch request.
* @constructor
*/
function BatchRequest() {
BatchRequest.super_.call(this);
this.requests_ = [];
}
/**
* Inherits from BaseRequest.
*/
util.inherits(BatchRequest, BaseRequest);
/**
* Adds a request to the batch request.
* @param {Request} request A Request object to add to the batch.
*
* @return {BatchRequest} Returns itself.
*/
BatchRequest.prototype.add = function(request) {
this.requests_.push({
apiMeta: request.apiMeta,
method: request.methodName,
params: request.params,
resource: request.resource
});
return this;
};
/**
* @protected
* Generates JSON-RPC payload.
*
* @return {Array.<object>} Generated payload.
*/
BatchRequest.prototype.generatePayload = function() {
var payload = [];
for (var i = 0; i < this.requests_.length; i++) {
var request = this.requests_[i];
request.params.resource = request.resource;
payload.push({
jsonrpc: BaseRequest.JSONRPC_VERSION,
id: i,
method: request.method,
params: request.params,
apiVersion: request.apiMeta.version
});
}
return payload;
};
/**
* @protected
* Wraps request callbacks.
*
* @param {Function=} opt_fn Optional callback function to be wrapped.
* @return {Function} Wrapped callback function.
*/
BatchRequest.prototype.handleResponse = function(opt_fn) {
return function(err, body, res) {
var results = null;
if (body) {
results = [];
for (var i in body) {
results.push(body[i].result || null);
}
}
opt_fn && opt_fn(err, results, res);
};
};
/**
* Exports Request.
*/
exports.Request = Request;
/**
* Exports BatchRequest.
*/
exports.BatchRequest = BatchRequest;

90
node_modules/googleapis/lib/transporters.js generated vendored Normal file
View File

@ -0,0 +1,90 @@
/**
* Copyright 2012 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var request = require('request'),
pkg = require('../package.json');
/**
* Default transporter constructor.
* Wraps request and callback functions.
*/
function DefaultTransporter() {}
/**
* Default user agent.
*/
DefaultTransporter.prototype.USER_AGENT =
'google-api-nodejs-client/' + pkg.version;
/**
* Configures request options before making a request.
* @param {object} opts Options to configure.
* @return {object} Configured options.
*/
DefaultTransporter.prototype.configure = function(opts) {
// set transporter user agent
opts.headers = opts.headers || {};
opts.headers['User-Agent'] = opts.headers['User-Agent'] ?
opts.headers['User-Agent'] + ' ' + this.USER_AGENT : this.USER_AGENT;
return opts;
};
/**
* Makes a request with given options and invokes callback.
* @param {object} opts Options.
* @param {Function=} opt_callback Optional callback.
*/
DefaultTransporter.prototype.request = function(opts, opt_callback) {
opts = this.configure(opts);
request(opts, this.wrapCallback_(opt_callback));
};
/**
* @private
* Wraps the response callback.
* @param {Function=} opt_callback Optional callback.
* @return {Function} Wrapped callback function.
*/
DefaultTransporter.prototype.wrapCallback_ = function(opt_callback) {
return function(err, res, body) {
if (err || !body) {
opt_callback && opt_callback(err, null, res);
} else if (body && body.error) {
// handle single request errors
err = body.error;
delete body.error;
opt_callback(err, body, res);
} else {
// TODO(burcud): Logic not related to the means of transportation
// should be handled elsewhere.
var errors = null;
// iterate over objects to check if there are errors or not.
for (var i = 0; i < body.length; i++) {
if (body[i].error) {
errors = errors || [];
errors[i] = body[i].error;
delete body[i].error;
}
}
opt_callback && opt_callback(errors, body, res);
}
};
};
/**
* Exports DefaultTransporter.
*/
module.exports = DefaultTransporter;