Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

translate: api updates #1781

Merged
merged 5 commits into from
Nov 14, 2016
Merged
Show file tree
Hide file tree
Changes from 4 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
70 changes: 67 additions & 3 deletions packages/translate/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,14 @@
- [API Documentation][gcloud-translate-docs]
- [Official Documentation][cloud-translate-docs]

**An API key is required for Translate.** See [Identifying your application to Google][api-key-howto].


```sh
$ npm install --save @google-cloud/translate
```
```js
var translate = require('@google-cloud/translate')({
key: 'API Key'
projectId: 'grape-spaceship-123',
keyFilename: '/path/to/keyfile.json'
});

// Translate a string of text.
Expand Down Expand Up @@ -59,6 +58,71 @@ var translate = require('@google-cloud/translate')({
```


## Authentication

It's incredibly easy to get authenticated and start using Google's APIs. You can set your credentials on a global basis as well as on a per-API basis. See each individual API section below to see how you can auth on a per-API-basis. This is useful if you want to use different accounts for different Google Cloud services.

### On Google Compute Engine

If you are running this client on Google Compute Engine, we handle authentication for you with no configuration. You just need to make sure that when you [set up the GCE instance][gce-how-to], you add the correct scopes for the APIs you want to access.

``` js
// Authenticating on a global basis.
var projectId = process.env.GCLOUD_PROJECT; // E.g. 'grape-spaceship-123'

var translate = require('@google-cloud/translate')({
projectId: projectId
});

// ...you're good to go!
```

### With a Google Developers Service Account

If you are not running this client on Google Compute Engine, you need a Google Developers service account. To create a service account:

1. Visit the [Google Developers Console][dev-console].
2. Create a new project or click on an existing project.
3. Navigate to **APIs & auth** > **APIs section** and turn on the following APIs (you may need to enable billing in order to use these services):
* Google Translate API
4. Navigate to **APIs & auth** > **Credentials** and then:
* If you want to use a new service account, click on **Create new Client ID** and select **Service account**. After the account is created, you will be prompted to download the JSON key file that the library uses to authenticate your requests.
* If you want to generate a new key for an existing service account, click on **Generate new JSON key** and download the JSON key file.

``` js
var projectId = process.env.GCLOUD_PROJECT; // E.g. 'grape-spaceship-123'

var translate = require('@google-cloud/translate')({
projectId: projectId,

// The path to your key file:
keyFilename: '/path/to/keyfile.json'

// Or the contents of the key file:
credentials: require('./path/to/keyfile.json')
});

// ...you're good to go!
```

### With an API key

It's also possible to authenticate with an API key. To create an API key:

1. Visit the [Google Developers Console][dev-console].
2. Create a new project or click on an existing project.
3. Navigate to **APIs & auth** > **APIs section** and turn on the following APIs (you may need to enable billing in order to use these services):
* Google Translate API
4. Navigate to **APIs & auth** > **Credentials** and then click on **Create new Client ID** and select **API key**. You should then be presented with a pop-up containing your newly created key.

```js
var translate = require('@google-cloud/translate')({
key: 'API Key'
});

// ...you're good to go!
```

[google-cloud]: https://github.com/GoogleCloudPlatform/google-cloud-node/
[api-key-howto]: https://cloud.google.com/translate/v2/using_rest#auth
[gcloud-translate-docs]: https://googlecloudplatform.github.io/google-cloud-node/#/docs/translate
Expand Down
59 changes: 39 additions & 20 deletions packages/translate/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ var extend = require('extend');
var is = require('is');
var isHtml = require('is-html');
var prop = require('propprop');
var util = require('util');

var PKG = require('../package.json');

Expand All @@ -40,9 +41,6 @@ var PKG = require('../package.json');
* [Pricing](https://cloud.google.com/translate/v2/pricing.html) and
* [FAQ](https://cloud.google.com/translate/v2/faq.html) pages for details.
*
* **An API key is required for Translate.** See
* [Identifying your application to Google](https://cloud.google.com/translate/v2/using_rest#auth).
*
* @constructor
* @alias module:translate
*
Expand All @@ -52,7 +50,7 @@ var PKG = require('../package.json');
* @throws {Error} If an API key is not provided.
*
* @param {object} options - [Configuration object](#/docs).
* @param {string} options.key - An API key.
* @param {string=} options.key - An API key.
*
* @example
* //-
Expand All @@ -70,21 +68,30 @@ function Translate(options) {
return new Translate(options);
}

if (!options.key) {
throw new Error('An API key is required to use the Translate API.');
}

this.baseUrl = 'https://www.googleapis.com/language/translate/v2';
var baseUrl = 'https://translation.googleapis.com/language/translate/v2';

if (process.env.GOOGLE_CLOUD_TRANSLATE_ENDPOINT) {
this.baseUrl = process.env.GOOGLE_CLOUD_TRANSLATE_ENDPOINT
baseUrl = process.env.GOOGLE_CLOUD_TRANSLATE_ENDPOINT
.replace(/\/+$/, '');
}

this.options = options;
this.key = options.key;
if (options.key) {
this.options = options;
this.key = options.key;
}

var config = {
baseUrl: baseUrl,
scopes: ['https://www.googleapis.com/auth/cloud-platform'],
packageJson: require('../package.json'),
projectIdRequired: false

This comment was marked as spam.

This comment was marked as spam.

};

common.Service.call(this, config, options);
}

util.inherits(Translate, common.Service);

/**
* Detect the language used in a string or multiple strings.
*
Expand Down Expand Up @@ -153,9 +160,9 @@ Translate.prototype.detect = function(input, callback) {
input = arrify(input);

this.request({
method: 'POST',
uri: '/detect',
useQuerystring: true,
qs: {
json: {
q: input
}
}, function(err, resp) {
Expand Down Expand Up @@ -303,6 +310,9 @@ Translate.prototype.getLanguages = function(target, callback) {
* not, we set the format as `text`.
* @param {string} options.from - The ISO 639-1 language code the source input
* is written in.
* @param {string} options.model - **Note:** Users must be whitelisted to use
* this parameter. Set the model type requested for this translation. Please
* refer to the upstread documentation for possible values.

This comment was marked as spam.

This comment was marked as spam.

* @param {string} options.to - The ISO 639-1 language code to translate the
* input to.
* @param {function} callback - The callback function.
Expand Down Expand Up @@ -381,16 +391,20 @@ Translate.prototype.translate = function(input, options, callback) {
if (options.to) {
query.target = options.to;
}

if (options.model) {
query.model = options.model;

This comment was marked as spam.

This comment was marked as spam.

}
}

if (!query.target) {
throw new Error('A target language is required to perform a translation.');
}

this.request({
method: 'POST',
uri: '',
useQuerystring: true,
qs: query
json: query
}, function(err, resp) {
if (err) {
callback(err, null, resp);
Expand All @@ -408,17 +422,22 @@ Translate.prototype.translate = function(input, options, callback) {
};

/**
* A custom request implementation. Requests to this API use an API key for an
* application, not a bearer token from a service account. This means we skip
* the `makeAuthenticatedRequest` portion of the typical request lifecycle, and
* manually authenticate the request here.
* A custom request implementation. Requests to this API may optionally use an
* API key for an application, not a bearer token from a service account. This
* means it is possible to skip the `makeAuthenticatedRequest` portion of the
* typical request lifecycle, and manually authenticate the request here.
*
* @private
*
* @param {object} reqOpts - Request options that are passed to `request`.
* @param {function} callback - The callback function passed to `request`.
*/
Translate.prototype.request = function(reqOpts, callback) {
if (!this.key) {
common.Service.prototype.request.call(this, reqOpts, callback);
return;
}

reqOpts.uri = this.baseUrl + reqOpts.uri;

reqOpts = extend(true, {}, reqOpts, {
Expand Down
20 changes: 12 additions & 8 deletions packages/translate/system-test/translate.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,8 @@ var Translate = require('../');

var API_KEY = process.env.GCLOUD_TESTS_API_KEY;

// Only run the tests if there is an API key to test with.
(API_KEY ? describe : describe.skip)('translate', function() {
if (!API_KEY) {
// The test runner still executes this function, even if it is skipped.
return;
}

var translate = new Translate(extend({}, env, { key: API_KEY }));
describe('translate', function() {

This comment was marked as spam.

This comment was marked as spam.

var translate = new Translate(extend({}, env));

describe('detecting language from input', function() {
var INPUT = [
Expand Down Expand Up @@ -153,4 +147,14 @@ var API_KEY = process.env.GCLOUD_TESTS_API_KEY;
});
});
});

(API_KEY ? describe : describe.skip)('authentication', function() {
beforeEach(function() {
translate = new Translate({ key: API_KEY });
});

it('should use an API key to authenticate', function(done) {
translate.getLanguages(done);
});
});
});
Loading