Skip to content

Commit

Permalink
Integrate resource manager support
Browse files Browse the repository at this point in the history
  • Loading branch information
stephenplusplus committed Sep 11, 2015
1 parent 8a186ed commit ad66ebe
Show file tree
Hide file tree
Showing 8 changed files with 633 additions and 3 deletions.
Empty file.
16 changes: 15 additions & 1 deletion docs/site/components/docs/docs-values.js
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,17 @@ angular.module('gcloud.docs')
]
},

resource: {
title: 'Resource',
_url: '{baseUrl}/resource',
pages: [
{
title: 'Project',
url: '/project'
}
]
},

search: {
title: 'Search',
_url: '{baseUrl}/search',
Expand Down Expand Up @@ -226,6 +237,9 @@ angular.module('gcloud.docs')
'>=0.18.0': ['dns'],

// introduce compute api.
'>=0.20.0': ['compute']
'>=0.20.0': ['compute'],

// introduce resource api.
'>=0.22.0': ['resource']
}
});
6 changes: 4 additions & 2 deletions lib/common/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -473,11 +473,13 @@ util.decorateRequest = decorateRequest;
* @param {?object} localConfig - api level configurations
* @return {object} config - merged and validated configurations
*/
function normalizeArguments(globalContext, localConfig) {
function normalizeArguments(globalContext, localConfig, options) {
var globalConfig = globalContext && globalContext.config_ || {};
var config = util.extendGlobalConfig(globalConfig, localConfig);

if (!config.projectId) {
options = options || {};

if (!config.projectId && options.projectIdRequired !== false) {
throw util.missingProjectIdError;
}

Expand Down
23 changes: 23 additions & 0 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,29 @@ var apis = {
*/
pubsub: require('./pubsub'),

/**
* [The Cloud Resource Manager](https://cloud.google.com/resource-manager/)
* provides methods that you can use to programmatically manage your projects
* in the Google Cloud Platform. With this API, you can do the following:
*
* - Get a list of all projects associated with an account.
* - Create new projects.
* - Update existing projects.
* - Delete projects.
* - Recover projects.
*
* <p class="notice">
* **This is a *Beta* release of Cloud Resource Manager.** This API is not
* covered by any SLA or deprecation policy and may be subject to backward-
* incompatible changes.
* </p>
*
* @type {module:resource}
*
* @return {module:resource}
*/
resource: require('./resource'),

/**
* [Google Cloud Search](https://cloud.google.com/search/) allows you to
* quickly perform full-text and geospatial searches against your data without
Expand Down
299 changes: 299 additions & 0 deletions lib/resource/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,299 @@
/*!
* Copyright 2015 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.
*/

/*!
* @module resource
*/

'use strict';

var extend = require('extend');
var is = require('is');

/**
* @type {module:resource/project}
* @private
*/
var Project = require('./project.js');

/**
* @type {module:common/streamrouter}
* @private
*/
var streamRouter = require('../common/stream-router.js');

/**
* @type {module:common/util}
* @private
*/
var util = require('../common/util.js');

/**
* @const {string}
* @private
*/
var BASE_URL = 'https://cloudresourcemanager.googleapis.com/v1beta1/projects';

/**
* Required scopes for Google Cloud Resource Manager API.
* @const {array}
* @private
*/
var SCOPES = [
'https://www.googleapis.com/auth/cloud-platform'
];

/**
* [The Cloud Resource Manager](https://cloud.google.com/resource-manager/)
* provides methods that you can use to programmatically manage your projects
* in the Google Cloud Platform. With this API, you can do the following:
*
* - Get a list of all projects associated with an account.
* - Create new projects.
* - Update existing projects.
* - Delete projects.
* - Recover projects.
*
* @alias module:resource
* @constructor
*
* @param {object} options - [Configuration object](#/docs/?method=gcloud).
*
* @example
* var gcloud = require('gcloud')({
* keyFilename: '/path/to/keyfile.json',
* projectId: 'grape-spaceship-123'
* });
*
* var resource = gcloud.resource();
*/
function Resource(options) {
if (!(this instanceof Resource)) {
options = util.normalizeArguments(this, options, {
projectIdRequired: false
});
return new Resource(options);
}

this.defaultProjectId_ = options.projectId;

this.makeAuthorizedRequest_ = util.makeAuthorizedRequestFactory({
credentials: options.credentials,
keyFile: options.keyFilename,
scopes: SCOPES,
email: options.email
});
}

/**
* Create a project.
*
* @resource [Projects Overview]{@link https://cloud.google.com/compute/docs/networking#networks}
* @resource [projects: create API Documentation]{@link https://cloud.google.com/resource-manager/reference/rest/v1beta1/projects/create}
*
* @param {string} name - Name of the project.
* @param {object=} options - See a
* [Project resource](https://cloud.google.com/resource-manager/reference/rest/v1beta1/projects#Project).
* @param {function=} callback - The callback function.
* @param {?error} callback.err - An error returned while making this request.
* @param {module:resource/project} callback.project - The created Project
* object.
* @param {object} callback.apiResponse - The full API response.
*
* @example
* resource.createProject('new project name', function(err, project) {
* if (!err) {
* // `project` is a new Project instance.
* }
* });
*/
Resource.prototype.createProject = function(id, options, callback) {
var self = this;

if (is.fn(options)) {
callback = options;
options = {};
}

var body = extend({}, options, {
projectId: id
});

this.makeReq_('POST', '/', null, body, function(err, resp) {
if (err) {
callback(err, null, resp);
return;
}

var project = self.project(resp.projectId);
project.metadata = resp;

callback(null, project, resp);
});
};

/**
* Get a list of projects.
*
* @resource [Projects Overview]{@link https://cloud.google.com/resource-manager/reference/rest/v1beta1/projects}
* @resource [projects: list API Documentation]{@link https://cloud.google.com/resource-manager/reference/rest/v1beta1/projects/list}
*
* @param {object=} options - Operation search options.
* @param {boolean} options.autoPaginate - Have pagination handled
* automatically. Default: true.
* @param {string} options.filter - An expression for filtering the results.
* @param {number} options.pageSize - Maximum number of projects to return.
* @param {string} options.pageToken - A previously-returned page token
* representing part of the larger set of results to view.
* @param {function} callback - The callback function.
* @param {?error} callback.err - An error returned while making this request.
* @param {module:resource/project} callback.operations - Project objects from
* your account.
* @param {?object} callback.nextQuery - If present, query with this object to
* check for more results.
* @param {object} callback.apiResponse - The full API response.
*
* @example
* resource.getProjects(function(err, projects) {
* // `projects` is an array of `Project` objects.
* });
*
* //-
* // To control how many API requests are made and page through the results
* // manually, set `autoPaginate` to `false`.
* //-
* function callback(err, projects, nextQuery, apiResponse) {
* if (nextQuery) {
* // More results exist.
* resource.getProjects(nextQuery, callback);
* }
* }
*
* resource.getProjects({
* autoPaginate: false
* }, callback);
*
* //-
* // Get the projects from your account as a readable object stream.
* //-
* resource.getProjects()
* .on('error', console.error)
* .on('data', function(project) {
* // `project` is a `Project` object.
* })
* .on('end', function() {
* // All projects retrieved.
* });
*
* //-
* // If you anticipate many results, you can end a stream early to prevent
* // unnecessary processing and API requests.
* //-
* resource.getProjects()
* .on('data', function(project) {
* this.end();
* });
*/
Resource.prototype.getProjects = function(options, callback) {
var self = this;

if (is.fn(options)) {
callback = options;
options = {};
}

options = options || {};

this.makeReq_('GET', '/', options, null, function(err, resp) {
if (err) {
callback(err, null, null, resp);
return;
}

var nextQuery = null;

if (resp.nextPageToken) {
nextQuery = extend({}, options, {
pageToken: resp.nextPageToken
});
}

var projects = (resp.projects || []).map(function(project) {
var projectInstance = self.project(project.name);
projectInstance.metadata = project;
return projectInstance;
});

callback(null, projects, nextQuery, resp);
});
};

/**
* Create a Project object to reference an existing project. See
* {module:resoucemanager/createProject} to create a project.
*
* @throws {Error} If an ID is not provided.
*
* @param {string} id - The ID of the project (eg: `grape-spaceship-123`).
* @return {module:resource/project}
*
* @example
* var project = resource.project('grape-spaceship-123');
*/
Resource.prototype.project = function(id) {
id = id || this.defaultProjectId_;

if (!id) {
throw new Error('A project ID is required.');
}

return new Project(this, id);
};

/**
* Make a new request object from the provided arguments and wrap the callback
* to intercept non-successful responses.
*
* @private
*
* @param {string} method - Action.
* @param {string} path - Request path.
* @param {*} query - Request query object.
* @param {*} body - Request body contents.
* @param {function} callback - The callback function.
*/
Resource.prototype.makeReq_ = function(method, path, query, body, callback) {
var reqOpts = {
method: method,
qs: query,
uri: BASE_URL + path
};

if (body) {
reqOpts.json = body;
}

this.makeAuthorizedRequest_(reqOpts, callback);
};

/*! Developer Documentation
*
* These methods can be used with either a callback or as a readable object
* stream. `streamRouter` is used to add this dual behavior.
*/
streamRouter.extend(Resource, ['getProjects']);

module.exports = Resource;
Loading

0 comments on commit ad66ebe

Please sign in to comment.