├── test ├── fixtures │ ├── mediabody.txt │ ├── urlshort-insert-res.json │ ├── media-response.txt │ ├── kitchen │ │ ├── src │ │ │ └── index.ts │ │ ├── tsconfig.json │ │ └── package.json │ ├── public.pem │ ├── private.pem │ └── oauthcerts.json ├── samples │ ├── test.samples.customsearch.ts │ ├── test.samples.auth.ts │ ├── test.samples.youtube.ts │ ├── test.samples.gmail.ts │ └── test.samples.drive.ts ├── utils.ts ├── test.kitchen.ts ├── test.discover.ts ├── test.urlshortener.v1.ts ├── test.apikey.ts └── test.drive.v2.ts ├── samples ├── config.json ├── analytics │ ├── README.md │ └── analytics.js ├── compute │ ├── README.md │ └── compute.js ├── customsearch │ ├── README.md │ └── customsearch.js ├── urlshortener │ ├── README.md │ └── urlshortener.js ├── directory_v1 │ ├── authData.json │ ├── group-delete.js │ ├── group-insert.js │ ├── README.md │ ├── group-email-delete.js │ └── group-email-insert.js ├── blogger │ ├── README.md │ └── blogger.js ├── oauth2.keys.json ├── storage │ └── README.md ├── mirror │ ├── README.md │ └── mirror.js ├── youtube │ ├── README.md │ ├── search.js │ ├── playlist.js │ └── upload.js ├── jwt.keys.json ├── drive │ ├── README.md │ ├── list.js │ ├── download.js │ ├── export.js │ ├── upload.js │ └── quickstart.js ├── multiple.js ├── gmail │ ├── list.js │ └── labels.js ├── people │ └── me.js ├── jwt.js ├── mediaupload.js ├── oauth2.js ├── sampleclient.js ├── defaultauth.js ├── sheets │ └── quickstart.js └── README.md ├── .gitignore ├── tsconfig.tools.json ├── AUTHORS ├── tsconfig.json ├── .github ├── ISSUE_TEMPLATE.md ├── PULL_REQUEST_TEMPLATE.md ├── CLOSE_ISSUE_TEMPLATE.md └── CONTRIBUTING.md ├── .appveyor.yml ├── src ├── templates │ ├── resource-partial.njk │ ├── index.njk │ ├── method-partial.njk │ └── api-endpoint.njk ├── index.ts ├── scripts │ ├── generator_utils.ts │ └── generate.ts ├── lib │ ├── schema.ts │ ├── api.ts │ ├── googleapis.ts │ ├── endpoint.ts │ └── discovery.ts └── apis │ ├── groupsmigration │ └── v1.ts │ ├── playcustomapp │ └── v1.ts │ ├── webfonts │ └── v1.ts │ ├── kgsearch │ └── v1.ts │ ├── acceleratedmobilepageurl │ └── v1.ts │ ├── pagespeedonline │ ├── v1.ts │ ├── v2.ts │ └── v4.ts │ ├── searchconsole │ └── v1.ts │ ├── abusiveexperiencereport │ └── v1.ts │ ├── androidpublisher │ └── v1.ts │ └── adexperiencereport │ └── v1.ts ├── jsdoc-conf.json ├── Makefile ├── .circleci └── config.yml ├── CONTRIBUTORS └── package.json /test/fixtures/mediabody.txt: -------------------------------------------------------------------------------- 1 | hello world abc123 2 | -------------------------------------------------------------------------------- /samples/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "api_key": "YOUR_API_KEY", 3 | "customsearch_engine_id": "YOUR_CUSTOMSEARCH_ENGINE_ID" 4 | } -------------------------------------------------------------------------------- /test/fixtures/urlshort-insert-res.json: -------------------------------------------------------------------------------- 1 | { 2 | "kind": "urlshortener#url", 3 | "id": "http://goo.gl/mR2d", 4 | "longUrl": "http://google.com/" 5 | } 6 | -------------------------------------------------------------------------------- /test/fixtures/media-response.txt: -------------------------------------------------------------------------------- 1 | --$boundary 2 | Content-Type: application/json 3 | 4 | $resource 5 | --$boundary 6 | Content-Type: $mimeType 7 | 8 | $media 9 | --$boundary-- 10 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .idea 3 | doc/ 4 | npm-debug.log 5 | coverage 6 | .secrets.json 7 | # Empty API 8 | apis/iam/v1alpha1.js 9 | .nyc_output 10 | **/*.js 11 | **/*.js.map 12 | !samples/**/*.js 13 | .vscode 14 | **/*.d.ts 15 | **/credentials.json 16 | -------------------------------------------------------------------------------- /tsconfig.tools.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./node_modules/gts/tsconfig-google.json", 3 | "compilerOptions": { 4 | "rootDir": ".", 5 | "outDir": "build", 6 | "target": "es6" 7 | }, 8 | "include": [ 9 | "src/scripts/*.ts" 10 | ] 11 | } 12 | -------------------------------------------------------------------------------- /samples/analytics/README.md: -------------------------------------------------------------------------------- 1 | # Analytics Samples 2 | 3 | The Google Analytics API lets you collect, configure, and analyze your data to reach the right audience. 4 | 5 | [Getting Started](https://developers.google.com/analytics/) 6 | 7 | ## Running the sample 8 | 9 | `node analytics.js` -------------------------------------------------------------------------------- /samples/compute/README.md: -------------------------------------------------------------------------------- 1 | # Compute Engine Metadata API Samples 2 | 3 | The Google Compute Engine Metadata service lets you get and set key/value pairs on virtual machine instances. 4 | 5 | [Getting Started](https://cloud.google.com/compute/docs/metadata/) 6 | 7 | ## Running the sample 8 | 9 | `node compute.js` -------------------------------------------------------------------------------- /samples/customsearch/README.md: -------------------------------------------------------------------------------- 1 | # Custom Search API Samples 2 | 3 | Google Custom Search enables you to create a search engine for your website, your blog, or a collection of websites. 4 | 5 | [Getting Started](https://developers.google.com/custom-search/) 6 | 7 | ## Running the sample 8 | 9 | `node customsearch.js` -------------------------------------------------------------------------------- /test/fixtures/kitchen/src/index.ts: -------------------------------------------------------------------------------- 1 | import {google, GoogleApis} from 'googleapis'; 2 | // uncomment the line below during development 3 | // import {google, GoogleApis} from '../../../../src'; 4 | const drive = google.drive({}); 5 | const googleapis = new GoogleApis(); 6 | const oauth2 = new googleapis.auth.OAuth2(); 7 | -------------------------------------------------------------------------------- /test/fixtures/public.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN PUBLIC KEY----- 2 | MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDzU+jLTzW6154Joezxrd2+5pCN 3 | YP0HcaMoYqEyXfNRpkNE7wrQUEG830o4Qcaae2BhqZoujwSW7RkR6h0Fkd0WTR8h 4 | 5J8rSGNHv/1jJoUUjP9iZ/5SFAyIIyEYfDPqtnA4iF1QWO2lXWlEFSuZjwM/8jBm 5 | eGzoiw17akNThIw8NwIDAQAB 6 | -----END PUBLIC KEY----- 7 | -------------------------------------------------------------------------------- /test/fixtures/kitchen/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./node_modules/gts/tsconfig-google.json", 3 | "compilerOptions": { 4 | "rootDir": ".", 5 | "outDir": "build" 6 | }, 7 | "include": [ 8 | "src/*.ts", 9 | "src/**/*.ts" 10 | ], 11 | "exclude": [ 12 | "node_modules" 13 | ] 14 | } 15 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | # This is the official list of google-api-nodejs-client authors for copyright 2 | # purposes. This file is distinct from the CONTRIBUTORS files. See the latter 3 | # for an explanation. 4 | # 5 | # Names should be added to this file as: 6 | # Name or Organization 7 | # The email address is not required for organizations. 8 | Google Inc. 9 | -------------------------------------------------------------------------------- /samples/urlshortener/README.md: -------------------------------------------------------------------------------- 1 | # Url Shortener Samples 2 | 3 | The Google URL Shortener at goo.gl is a service that takes long URLs and squeezes them into fewer characters to make a link that is easier to share, tweet, or email to friends. 4 | 5 | [Getting Started](https://developers.google.com/url-shortener/) 6 | 7 | ## Running the sample 8 | 9 | `node urlshortener.js` -------------------------------------------------------------------------------- /samples/directory_v1/authData.json: -------------------------------------------------------------------------------- 1 | { 2 | "email": "21........misb7rvrmu@developer.gserviceaccount.com", 3 | "keyFile": "./keyFile.pem", 4 | "key": "f5938a...............68bf1a6d5ad02", 5 | "scopes": [ 6 | "https://www.googleapis.com/auth/admin.directory.group", 7 | "https://www.googleapis.com/auth/admin.directory.group.member" 8 | ], 9 | "subject": "admin@example.com" 10 | } 11 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./node_modules/gts/tsconfig-google.json", 3 | "compilerOptions": { 4 | "rootDir": ".", 5 | "outDir": "build", 6 | "noImplicitThis": false 7 | }, 8 | "include": [ 9 | "src/*.ts", 10 | "src/**/*.ts", 11 | "test/*.ts", 12 | "test/**/*.ts" 13 | ], 14 | "exclude": [ 15 | "node_modules", 16 | "test/fixtures" 17 | ] 18 | } 19 | -------------------------------------------------------------------------------- /samples/blogger/README.md: -------------------------------------------------------------------------------- 1 | # Blogger API Samples 2 | 3 | The Blogger API v3 allows client applications to view and update Blogger content. Your client application can use Blogger API v3 to create new blog posts, edit or delete existing posts, and query for posts that match particular criteria. 4 | 5 | [Getting Started](https://developers.google.com/blogger/) 6 | 7 | ## Running the sample 8 | 9 | `node blogger.js` -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | **** DELETE THIS BLOCK **** 2 | 3 | Thanks for filing an issue! Please keep keep issues limited to bug reports, feature requests, and other general issues. For support questions, please feel free to reach out on stack overflow: http://stackoverflow.com/questions/tagged/google-api-nodejs-client 4 | 5 | **** /DELETE THIS BLOCK **** 6 | 7 | 8 | 9 | Thanks! 10 | -------------------------------------------------------------------------------- /samples/oauth2.keys.json: -------------------------------------------------------------------------------- 1 | { 2 | "web": { 3 | "client_id": "YOUR_CLIENT_ID", 4 | "project_id": "YOUR_PROJECT_ID", 5 | "auth_uri": "https://accounts.google.com/o/oauth2/auth", 6 | "token_uri": "https://accounts.google.com/o/oauth2/token", 7 | "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", 8 | "client_secret": "YOUR_CLIENT_SECRET", 9 | "redirect_uris": [ 10 | "http://localhost:3000/oauth2callback" 11 | ] 12 | } 13 | } -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | Fixes # (it's a good idea to open an issue first for discussion) 2 | 3 | - [ ] `npm test` succeeds 4 | - [ ] Pull request has been squashed into 1 commit 5 | - [ ] I did NOT manually make changes to anything in `apis/` 6 | - [ ] Code coverage does not decrease (if any source code was changed) 7 | - [ ] Appropriate JSDoc comments were updated in source code (if applicable) 8 | - [ ] Appropriate changes to readme/docs are included in PR 9 | -------------------------------------------------------------------------------- /samples/storage/README.md: -------------------------------------------------------------------------------- 1 | # Google Cloud Storage 2 | 3 | [Google Cloud Storage](https://cloud.google.com/storage/docs/overview) offers developers and IT organizations durable and highly available object storage. 4 | 5 | ## Getting started 6 | The [gcloud NPM module](https://github.com/GoogleCloudPlatform/gcloud-node) includes a first class [API](https://github.com/GoogleCloudPlatform/gcloud-node#google-cloud-storage) for using Google Cloud Storage. Please `npm install gcloud` and follow the guide. 7 | -------------------------------------------------------------------------------- /.appveyor.yml: -------------------------------------------------------------------------------- 1 | environment: 2 | matrix: 3 | - nodejs_version: 8 4 | 5 | install: 6 | - ps: Install-Product node $env:nodejs_version 7 | - ps: (new-object net.webclient).DownloadFile('https://github.com/mbuilov/gnumake-windows/raw/master/gnumake-4.2.1-x64.exe', 'C:\projects\google-api-nodejs-client\make.exe') 8 | - set PATH=%APPDATA%\npm;%PATH% 9 | - npm install 10 | 11 | test_script: 12 | - node --version 13 | - npm --version 14 | - npm rebuild 15 | - npm test 16 | 17 | build: off 18 | 19 | matrix: 20 | fast_finish: true 21 | -------------------------------------------------------------------------------- /samples/mirror/README.md: -------------------------------------------------------------------------------- 1 | # Google Glass Mirror API Sample 2 | 3 | The Google Mirror API allows you to build web-based services that interact with Google Glass. It provides this functionality over a cloud-based API and does not require running code on Glass. 4 | 5 | [Learn more](https://developers.google.com/glass/develop/mirror/) 6 | 7 | ## Running the sample 8 | 9 | To run this sample, add your client id, client secret, and redirect url in oauth2.keys.json. You can also download this file directly from the Google Developers console. Then run: 10 | 11 | `node mirror.js` -------------------------------------------------------------------------------- /samples/youtube/README.md: -------------------------------------------------------------------------------- 1 | # YouTube API Samples 2 | 3 | With the YouTube Data API, you can add a variety of YouTube features to your application. Use the API to upload videos, manage playlists and subscriptions, update channel settings, and more. 4 | 5 | [Learn more](https://developers.google.com/youtube/v3/) 6 | 7 | ## Running the samples 8 | 9 | To run this sample, add your client id, client secret, and redirect url in oauth2.keys.json. You can also download this file directly from the Google Developers console. The samples include: 10 | 11 | - `node playlist` 12 | - `node search` 13 | - `node upload` 14 | -------------------------------------------------------------------------------- /src/templates/resource-partial.njk: -------------------------------------------------------------------------------- 1 | {% import "method-partial.njk" as method %} 2 | {% macro render(r, api, globalmethods) %} 3 | {% if r.methods %} 4 | {% for mname, m in r.methods|dictsort %} 5 | {{ method.render(m, mname, api, globalmethods) }} 6 | {% if globalmethods %};{% elif not loop.last %},{% endif %} 7 | {% endfor %} 8 | {% endif %}{% if r.methods and r.resources %},{% endif %} 9 | {% if r.resources %} 10 | {% for rname, sr in r.resources|dictsort %} 11 | {{ rname }}: { 12 | {{ render(sr, api, globalmethods) }} 13 | }{% if not loop.last %},{% endif %} 14 | {% endfor %} 15 | {% endif %} 16 | {% endmacro %} -------------------------------------------------------------------------------- /samples/jwt.keys.json: -------------------------------------------------------------------------------- 1 | { 2 | "type": "service_account", 3 | "project_id": "YOUR_PROJECT_ID", 4 | "private_key_id": "YOUR_PRIVATE_KEY_ID", 5 | "private_key": "-----BEGIN PRIVATE KEY-----\nYOUR_PRIVATE_KEY==\n-----END PRIVATE KEY-----\n", 6 | "client_email": "YOUR_ACCOUNT_EMAIL", 7 | "client_id": "YOUR_CLIENT_ID", 8 | "auth_uri": "https://accounts.google.com/o/oauth2/auth", 9 | "token_uri": "https://accounts.google.com/o/oauth2/token", 10 | "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", 11 | "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/DETAILS" 12 | } 13 | -------------------------------------------------------------------------------- /.github/CLOSE_ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | Closing as this does not appear to be an issue. If you are convinced that this is really a bug, please feel free to re-open the issue and add more information such as: 2 | 3 | * Expected behavior 4 | * Actual behavior 5 | * Code samples 6 | * Version numbers 7 | * References docs or other links 8 | 9 | Or, consider opening a Pull Request. 10 | 11 | __Otherwise, support questions are handled on [Stack Overflow][stackoverflow].__ [![Ask a question on Stackoverflow][overflowimg]][stackoverflow] 12 | 13 | [overflowimg]: https://googledrive.com/host/0ByfSjdPVs9MZbkhjeUhMYzRTeEE/stackoveflow-tag.png 14 | [stackoverflow]: http://stackoverflow.com/questions/tagged/google-api-nodejs-client 15 | -------------------------------------------------------------------------------- /test/fixtures/kitchen/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "google-api-nodejs-client-fixture", 3 | "version": "1.0.0", 4 | "description": "An app we're using to test the library. ", 5 | "scripts": { 6 | "check": "gts check", 7 | "clean": "gts clean", 8 | "compile": "tsc -p .", 9 | "fix": "gts fix", 10 | "prepare": "npm run compile", 11 | "pretest": "npm run compile", 12 | "posttest": "npm run check", 13 | "start": "node build/src/index.js" 14 | }, 15 | "license": "Apache-2.0", 16 | "dependencies": { 17 | "googleapis": "file:./googleapis.tgz" 18 | }, 19 | "devDependencies": { 20 | "@types/node": "^8.0.53", 21 | "typescript": "^2.6.2", 22 | "gts": "^0.5.1" 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import {GoogleApis} from './lib/googleapis'; 18 | const google = new GoogleApis(); 19 | export {google, GoogleApis}; 20 | -------------------------------------------------------------------------------- /samples/drive/README.md: -------------------------------------------------------------------------------- 1 | # Drive v3 API Samples 2 | 3 | This samples allows you to download a single file from Google Drive. 4 | 5 | ## Running the samples 6 | 7 | Set the following values in `secret.json` (up one directory): 8 | 9 | * `client_id` 10 | * `project_id` 11 | * `client_secret` 12 | 13 | __Run the `download.js` sample:__ 14 | 15 | ``` 16 | node download.js 17 | ``` 18 | 19 | where `` is the id of any file in Google Drive. 20 | 21 | Example: 22 | 23 | ``` 24 | node download.js 0B_Klegupc5gUcXhFZjZVUV9NeE0 25 | ``` 26 | 27 | __Run the `export.js` sample:__ 28 | 29 | ``` 30 | node export.js = 31 | ``` 32 | 33 | where `` is the id of a _Google Doc_ in Google Drive. 34 | 35 | Example: 36 | 37 | ``` 38 | node export.js 0B_Klegupc5gUcXhFZjZVUV9NeE0 ./file.pdf 39 | ``` 40 | -------------------------------------------------------------------------------- /test/fixtures/private.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN RSA PRIVATE KEY----- 2 | MIICXQIBAAKBgQDzU+jLTzW6154Joezxrd2+5pCNYP0HcaMoYqEyXfNRpkNE7wrQ 3 | UEG830o4Qcaae2BhqZoujwSW7RkR6h0Fkd0WTR8h5J8rSGNHv/1jJoUUjP9iZ/5S 4 | FAyIIyEYfDPqtnA4iF1QWO2lXWlEFSuZjwM/8jBmeGzoiw17akNThIw8NwIDAQAB 5 | AoGATpboVloEAY/IdFX/QGOmfhTb1T3hG3lheBa695iOkO2BRo9qT7PMN6NqxlbA 6 | PX7ht0lfCfCZS+HSOg4CR50/6WXHMSmwlvcjGuDIDKWjviQTTYE77MlVBQHw9WzY 7 | PfiRBbtouyPGQtO4rk42zkIILC6exBZ1vKpRPOmTAnxrjCECQQD+56r6hYcS6GNp 8 | NOWyv0eVFMBX4iNWAsRf9JVVvGDz2rVuhnkNiN73vfffDWvSXkCydL1jFmalgdQD 9 | gm77UZQHAkEA9F+CauU0aZsJ1SthQ6H0sDQ+eNRUgnz4itnkSC2C20fZ3DaSpCMC 10 | 0go81CcZOhftNO730ILqiS67C3d3rqLqUQJBAP10ROHMmz4Fq7MUUcClyPtHIuk/ 11 | hXskTTZL76DMKmrN8NDxDLSUf38+eJRkt+z4osPOp/E6eN3gdXr32nox50kCQCl8 12 | hXGMU+eR0IuF/88xkY7Qb8KnmWlFuhQohZ7TSyHbAttl0GNZJkNuRYFm2duI8FZK 13 | M3wMnbCIZGy/7WuScOECQQCV+0yrf5dL1M2GHjJfwuTb00wRKalKQEH1v/kvE5vS 14 | FmdN7BPK5Ra50MaecMNoYqu9rmtyWRBn93dcvKrL57nY 15 | -----END RSA PRIVATE KEY----- 16 | -------------------------------------------------------------------------------- /samples/blogger/blogger.js: -------------------------------------------------------------------------------- 1 | // Copyright 2013-2016, Google, Inc. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | 'use strict'; 15 | 16 | const {google} = require('googleapis'); 17 | const blogger = google.blogger('v3'); 18 | const nconf = require('nconf'); 19 | const path = require('path'); 20 | 21 | // Ex: node blogger.js --api_key "YOUR API KEY" 22 | nconf.argv().env().file(path.join(__dirname, 'config.json')); 23 | 24 | blogger.blogs.get({ 25 | key: nconf.get('api_key'), 26 | blogId: 3213900 27 | }, (err, res) => { 28 | if (err) { 29 | throw err; 30 | } 31 | console.log(res.data); 32 | }); 33 | -------------------------------------------------------------------------------- /jsdoc-conf.json: -------------------------------------------------------------------------------- 1 | { 2 | "tags": { 3 | "allowUnknownTags": true, 4 | "dictionaries": ["jsdoc"] 5 | }, 6 | "source": { 7 | "include": ["README.md", "package.json", "apis/", "lib/"], 8 | "exclude": [ 9 | "lib/auth/", 10 | "lib/apirequest.js", 11 | "lib/discovery.js", 12 | "lib/generator.js", 13 | "lib/generator_utils.js", 14 | "lib/pemverifier.js", 15 | "lib/transporters.js", 16 | "lib/utils.js" 17 | ], 18 | "includePattern": ".+\\.js(doc)?$", 19 | "excludePattern": "(^|\\/|\\\\)_" 20 | }, 21 | "plugins": [ 22 | "plugins/markdown" 23 | ], 24 | "opts": { 25 | "template": "./node_modules/ink-docstrap/template", 26 | "destination": "./doc/", 27 | "recurse": true, 28 | "verbose": true, 29 | "encoding": "utf8", 30 | "private": false, 31 | "readme": "./README.md", 32 | "package": "./package.json" 33 | }, 34 | "templates": { 35 | "copyright": "google-api-nodejs-client Copyright © 2012-2016 Google Inc.", 36 | "outputSourceFiles": false, 37 | "linenums": true, 38 | "systemName": "googleapis", 39 | "theme": "lumen", 40 | "search": false 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/scripts/generator_utils.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2014-2016, Google, Inc. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | /** 15 | * Build a string used to create a URL from the discovery doc provided URL. 16 | * 17 | * @private 18 | * @param input URL to build from 19 | * @return Resulting built URL 20 | */ 21 | export function buildurl(input?: string) { 22 | return input ? 23 | ('\'' + input + '\'') 24 | // No * symbols 25 | .replace(/\*/g, '') 26 | // No + symbols 27 | .replace(/\+/g, '') 28 | // replace double slashes with single slash (except in https://) 29 | .replace(/([^:]\/)\/+/g, '$1') 30 | // No {/ symbols 31 | .replace(/\{\//g, '/{') : 32 | ''; 33 | } 34 | -------------------------------------------------------------------------------- /samples/multiple.js: -------------------------------------------------------------------------------- 1 | // Copyright 2013-2016, Google, Inc. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | 'use strict'; 15 | 16 | const {google} = require('googleapis'); 17 | const urlshortener = google.urlshortener('v1'); 18 | const plus = google.plus('v1'); 19 | const nconf = require('nconf'); 20 | const path = require('path'); 21 | 22 | nconf.argv().env().file(path.join(__dirname, 'config.json')); 23 | 24 | // PUT your API key here or this example will return errors 25 | // To learn more about API keys, please see: 26 | // https://github.com/google/google-api-nodejs-client#using-api-keys 27 | 28 | urlshortener.url.get({ shortUrl: 'http://goo.gl/xKbRu3', auth: nconf.get('api_key') }); 29 | plus.people.get({ userId: '+google', auth: nconf.get('api_key') }); 30 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: build build-tools check check-samples check-licenses check-typescript clean coverage docs fix fix-samples fix-typescript generate install test test-samples watch 2 | 3 | PATH := $(shell npm bin):$(PATH) 4 | 5 | build: 6 | tsc -v && tsc -p . 7 | 8 | build-tools: 9 | tsc -p tsconfig.tools.json 10 | 11 | check: check-typescript check-samples check-licenses 12 | 13 | check-samples: 14 | semistandard 'samples/**/*.js' 15 | 16 | check-licenses: 17 | jsgl --local . 18 | 19 | check-typescript: 20 | gts check 21 | 22 | clean: 23 | gts clean 24 | 25 | coverage: build 26 | nyc --cache mocha build/test -t 10000 -S -R spec --require intelli-espower-loader 27 | nyc report --reporter=html 28 | 29 | docs: 30 | jsdoc -c jsdoc-conf.json 31 | 32 | fix: fix-typescript fix-samples 33 | 34 | fix-samples: 35 | semistandard --fix 'samples/**/*.js' 36 | 37 | fix-typescript: 38 | gts fix 39 | 40 | generate: build-tools 41 | node build/src/scripts/generate.js 42 | clang-format -i -style='{Language: JavaScript, BasedOnStyle: Google, ColumnLimit: 80}' src/apis/**/*.ts 43 | 44 | install: 45 | npm install 46 | 47 | node_modules/.link: 48 | npm link && npm link googleapis && touch $@ 49 | 50 | test: coverage check 51 | 52 | test-samples: node_modules/.link build 53 | mocha build/test/samples 54 | 55 | watch: 56 | tsc -p . --watch 57 | -------------------------------------------------------------------------------- /samples/urlshortener/urlshortener.js: -------------------------------------------------------------------------------- 1 | // Copyright 2012-2016, Google, Inc. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | 'use strict'; 15 | 16 | const {google} = require('googleapis'); 17 | const path = require('path'); 18 | const nconf = require('nconf'); 19 | 20 | nconf.argv().env().file(path.join(__dirname, '../config.json')); 21 | const urlshortener = google.urlshortener('v1', nconf.get('api_key')); 22 | 23 | urlshortener.url.get({ 24 | shortUrl: 'http://goo.gl/DdUKX' 25 | }, (err, res) => { 26 | if (err) { 27 | throw err; 28 | } 29 | console.log(res.data); 30 | }); 31 | 32 | urlshortener.url.insert({ 33 | resource: { 34 | longUrl: 'http://somelongurl.com' 35 | } 36 | }, (err, res) => { 37 | if (err) { 38 | throw err; 39 | } 40 | console.log(res.data); 41 | }); 42 | -------------------------------------------------------------------------------- /test/samples/test.samples.customsearch.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018, Google, LLC. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | import * as assert from 'assert'; 15 | import * as nock from 'nock'; 16 | import {Utils} from './../utils'; 17 | 18 | nock.disableNetConnect(); 19 | 20 | // tslint:disable: no-any 21 | const samples: any = { 22 | list: require('../../../samples/customsearch/customsearch') 23 | }; 24 | 25 | describe('customsearch samples', () => { 26 | afterEach(() => { 27 | nock.cleanAll(); 28 | }); 29 | 30 | it('should search', done => { 31 | const scope = 32 | nock(Utils.baseUrl).get(`/customsearch/v1?cx=cx&q=q`).reply(200, {}); 33 | const options = {cx: 'cx', q: 'q', auth: 'key'}; 34 | samples.list.runSample(options, (data: {}) => { 35 | assert(data); 36 | scope.done(); 37 | done(); 38 | }); 39 | }); 40 | }); 41 | -------------------------------------------------------------------------------- /samples/mirror/mirror.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016, Google, Inc. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | 'use strict'; 15 | 16 | const {google} = require('googleapis'); 17 | const sampleClient = require('../sampleclient'); 18 | 19 | // initialize the Google Mirror API library 20 | const mirror = google.mirror({ version: 'v1', auth: sampleClient.oAuth2Client }); 21 | 22 | // a very simple example of listing locations from the mirror API 23 | function runSample () { 24 | mirror.locations.list({}, (err, res) => { 25 | if (err) { 26 | throw err; 27 | } 28 | console.log(res.data); 29 | }); 30 | } 31 | 32 | const scopes = [ 33 | 'https://www.googleapis.com/auth/glass.timeline', 34 | 'https://www.googleapis.com/auth/glass.location' 35 | ]; 36 | 37 | sampleClient.authenticate(scopes, err => { 38 | if (err) { 39 | throw err; 40 | } 41 | runSample(); 42 | }); 43 | -------------------------------------------------------------------------------- /test/samples/test.samples.auth.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018, Google, LLC. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | import * as assert from 'assert'; 15 | import * as nock from 'nock'; 16 | import {Utils} from './../utils'; 17 | 18 | nock.disableNetConnect(); 19 | 20 | // tslint:disable: no-any 21 | const samples: any = { 22 | jwt: require('../../../samples/jwt') 23 | }; 24 | 25 | for (const p in samples) { 26 | if (samples[p]) { 27 | samples[p].client.credentials = {access_token: 'not-a-token'}; 28 | } 29 | } 30 | 31 | describe('Auth samples', () => { 32 | afterEach(() => { 33 | nock.cleanAll(); 34 | }); 35 | 36 | it('should support JWT', done => { 37 | const scope = nock(Utils.baseUrl).get(`/drive/v2/files`).reply(200, {}); 38 | samples.jwt.runSample((data: {}) => { 39 | assert(data); 40 | scope.done(); 41 | done(); 42 | }); 43 | }); 44 | }); 45 | -------------------------------------------------------------------------------- /samples/youtube/search.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016, Google, Inc. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | 'use strict'; 15 | 16 | const {google} = require('googleapis'); 17 | const sampleClient = require('../sampleclient'); 18 | 19 | // initialize the Youtube API library 20 | const youtube = google.youtube({ 21 | version: 'v3', 22 | auth: sampleClient.oAuth2Client 23 | }); 24 | 25 | // a very simple example of searching for youtube videos 26 | function runSamples () { 27 | youtube.search.list({ 28 | part: 'id,snippet', 29 | q: 'Node.js on Google Cloud' 30 | }, (err, res) => { 31 | if (err) { 32 | throw err; 33 | } 34 | console.log(res.data); 35 | }); 36 | } 37 | 38 | const scopes = [ 39 | 'https://www.googleapis.com/auth/youtube' 40 | ]; 41 | 42 | sampleClient.authenticate(scopes, err => { 43 | if (err) { 44 | throw err; 45 | } 46 | runSamples(); 47 | }); 48 | -------------------------------------------------------------------------------- /samples/gmail/list.js: -------------------------------------------------------------------------------- 1 | // Copyright 2018, Google, LLC. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | 'use strict'; 15 | 16 | const {google} = require('googleapis'); 17 | const sampleClient = require('../sampleclient'); 18 | 19 | const gmail = google.gmail({ 20 | version: 'v1', 21 | auth: sampleClient.oAuth2Client 22 | }); 23 | 24 | function runSample (callback) { 25 | gmail.users.messages.list({ 26 | userId: 'me' 27 | }, (err, res) => { 28 | if (err) { 29 | throw err; 30 | } 31 | console.log(res.data); 32 | callback(res.data); 33 | }); 34 | } 35 | 36 | const scopes = ['https://www.googleapis.com/auth/gmail.readonly']; 37 | 38 | if (module === require.main) { 39 | sampleClient.authenticate(scopes, err => { 40 | if (err) { 41 | throw err; 42 | } 43 | runSample(() => { /* sample complete */ }); 44 | }); 45 | } 46 | 47 | module.exports = { 48 | runSample, 49 | client: sampleClient.oAuth2Client 50 | }; 51 | -------------------------------------------------------------------------------- /samples/people/me.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016, Google, Inc. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | 'use strict'; 15 | 16 | const {google} = require('googleapis'); 17 | const sampleClient = require('../sampleclient'); 18 | 19 | const plus = google.plus({ 20 | version: 'v1', 21 | auth: sampleClient.oAuth2Client 22 | }); 23 | 24 | function runSample () { 25 | plus.people.get({ 26 | userId: 'me' 27 | }, (err, res) => { 28 | if (err) { 29 | throw err; 30 | } 31 | console.log(res.data); 32 | }); 33 | } 34 | 35 | const scopes = [ 36 | 'https://www.googleapis.com/auth/plus.login', 37 | 'https://www.googleapis.com/auth/plus.me', 38 | 'https://www.googleapis.com/auth/userinfo.email', 39 | 'https://www.googleapis.com/auth/userinfo.profile' 40 | ]; 41 | 42 | if (module === require.main) { 43 | sampleClient.authenticate(scopes, err => { 44 | if (err) { 45 | throw err; 46 | } 47 | runSample(); 48 | }); 49 | } 50 | -------------------------------------------------------------------------------- /test/utils.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2016, Google, Inc. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | import {AxiosResponse} from 'axios'; 15 | import * as url from 'url'; 16 | import {GoogleApis} from '../src/index'; 17 | import {Endpoint} from '../src/lib/endpoint'; 18 | 19 | export abstract class Utils { 20 | static getQs(res: AxiosResponse) { 21 | const query = url.parse(res.request.path).query; 22 | return query ? query.toString() : null; 23 | } 24 | 25 | static getPath(res: AxiosResponse) { 26 | return url.parse(res.config.url!).path!; 27 | } 28 | 29 | static getDiscoveryUrl(name: string, version: string) { 30 | return 'https://www.googleapis.com/discovery/v1/apis/' + name + '/' + 31 | version + '/rest'; 32 | } 33 | 34 | static loadApi( 35 | google: GoogleApis, name: string, version: string, options = {}) { 36 | return google.discoverAPI(Utils.getDiscoveryUrl(name, version), options); 37 | } 38 | 39 | static readonly noop = () => undefined; 40 | 41 | static readonly baseUrl = 'https://www.googleapis.com'; 42 | } 43 | -------------------------------------------------------------------------------- /samples/drive/list.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016, Google, Inc. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | 'use strict'; 15 | 16 | const {google} = require('googleapis'); 17 | const sampleClient = require('../sampleclient'); 18 | 19 | const drive = google.drive({ 20 | version: 'v3', 21 | auth: sampleClient.oAuth2Client 22 | }); 23 | 24 | function listDocs (query, callback) { 25 | // [START main_body] 26 | const params = { pageSize: 3 }; 27 | params.q = query; 28 | drive.files.list(params, (err, res) => { 29 | if (err) { 30 | console.error(err); 31 | throw err; 32 | } 33 | console.log(res.data); 34 | callback(res.data); 35 | }); 36 | // [END main_body] 37 | } 38 | 39 | const scopes = ['https://www.googleapis.com/auth/drive.metadata.readonly']; 40 | 41 | if (module === require.main) { 42 | sampleClient.authenticate(scopes, err => { 43 | if (err) { 44 | throw err; 45 | } 46 | listDocs(undefined, () => { /* list complete */ }); 47 | }); 48 | } 49 | 50 | module.exports = { 51 | listDocs, 52 | client: sampleClient.oAuth2Client 53 | }; 54 | -------------------------------------------------------------------------------- /samples/compute/compute.js: -------------------------------------------------------------------------------- 1 | // Copyright 2013-2016, Google, Inc. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | 'use strict'; 15 | 16 | const request = require('request'); 17 | const {google} = require('googleapis'); 18 | const compute = google.compute('v1'); 19 | const uri = 'http://metadata/computeMetadata/v1/project/project-id'; 20 | const headers = { 'Metadata-Flavor': 'Google' }; 21 | 22 | // This example can be run from a GCE VM in your project. The example fetches 23 | // your project ID from the VM's metadata server, and then uses the Compute API 24 | // to fetch the list of GCE zones in your project. 25 | // 26 | // See the defaultauth.js sample for an alternate way of fetching compute credentials. 27 | // 28 | google.options({ auth: new google.auth.Compute() }); 29 | request.get({ uri, headers }, (err, res, project) => { 30 | if (err) { 31 | throw err; 32 | } 33 | if (res.statusCode !== 200) { 34 | throw new Error(`Response failed with status ${res.statusCode}`); 35 | } 36 | compute.zones.list({ project }, (err, res) => { 37 | console.log(err, res.data); 38 | }); 39 | }); 40 | -------------------------------------------------------------------------------- /samples/directory_v1/group-delete.js: -------------------------------------------------------------------------------- 1 | // Copyright 2014-2016, Google, Inc. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | 'use strict'; 15 | 16 | const {google} = require('googleapis'); 17 | const nconf = require('nconf'); 18 | const path = require('path'); 19 | 20 | nconf.argv().env().file(path.join(__dirname, '../jwt.keys.json')); 21 | 22 | // Create JWT auth object 23 | const jwt = new google.auth.JWT( 24 | nconf.get('client_email'), 25 | null, 26 | nconf.get('private_key'), 27 | [ 28 | 'https://www.googleapis.com/auth/admin.directory.group', 29 | 'https://www.googleapis.com/auth/admin.directory.group.member' 30 | ] 31 | ); 32 | 33 | // Authorize 34 | jwt.authorize((err, data) => { 35 | if (err) { 36 | throw err; 37 | } 38 | console.log('You have been successfully authenticated: ', data); 39 | 40 | // Get Google Admin API 41 | const admin = google.admin('directory_v1'); 42 | 43 | // Delete group 44 | admin.groups.insert({ 45 | groupKey: 'some_group@example.com', 46 | auth: jwt 47 | }, (err, data) => { 48 | console.log(err || data); 49 | }); 50 | }); 51 | -------------------------------------------------------------------------------- /samples/directory_v1/group-insert.js: -------------------------------------------------------------------------------- 1 | // Copyright 2014-2016, Google, Inc. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | 'use strict'; 15 | 16 | const {google} = require('googleapis'); 17 | const path = require('path'); 18 | const nconf = require('nconf'); 19 | 20 | nconf.argv().env().file(path.join(__dirname, '../jwt.keys.json')); 21 | 22 | // Create JWT auth object 23 | const jwt = new google.auth.JWT( 24 | nconf.get('client_email'), 25 | null, 26 | nconf.get('private_key'), 27 | [ 28 | 'https://www.googleapis.com/auth/admin.directory.group', 29 | 'https://www.googleapis.com/auth/admin.directory.group.member' 30 | ] 31 | ); 32 | 33 | // Authorize 34 | jwt.authorize((err, data) => { 35 | if (err) { 36 | throw err; 37 | } 38 | console.log('You have been successfully authenticated: ', data); 39 | 40 | // Get Google Admin API 41 | const admin = google.admin('directory_v1'); 42 | 43 | // Insert group 44 | admin.groups.insert({ 45 | resource: { email: 'some_group@example.com' }, 46 | auth: jwt 47 | }, (err, data) => { 48 | console.log(err || data); 49 | }); 50 | }); 51 | -------------------------------------------------------------------------------- /src/scripts/generate.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2014 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import * as minimist from 'minimist'; 18 | import * as path from 'path'; 19 | import * as pify from 'pify'; 20 | import * as rimraf from 'rimraf'; 21 | import {install} from 'source-map-support'; 22 | import {Generator} from './generator'; 23 | 24 | // enable source map support 25 | install(); 26 | 27 | const debug = true; 28 | const argv = minimist(process.argv.slice(2)); 29 | const args = argv._; 30 | const gen = new Generator({debug, includePrivate: false}); 31 | 32 | async function main() { 33 | if (args.length) { 34 | args.forEach(async url => { 35 | await gen.generateAPI(url); 36 | console.log('Generated API for ' + url); 37 | }); 38 | } else { 39 | console.log('Removing old APIs...'); 40 | await pify(rimraf)(path.join(__dirname, '../../../src/apis')); 41 | console.log('Generating APIs...'); 42 | await gen.generateAllAPIs(); 43 | console.log('Finished generating APIs!'); 44 | } 45 | } 46 | main().catch(console.error); 47 | -------------------------------------------------------------------------------- /samples/directory_v1/README.md: -------------------------------------------------------------------------------- 1 | Directory v_1 Examples 2 | ====================== 3 | 4 | This directory contains some examples how to interact with `directory v_1` API. 5 | Authentication is done via JWT. 6 | 7 | ### Creating a Service Account using the Google Developers Console 8 | 9 | 1. From the [Google Developers Console](https://cloud.google.com/console), select your project or create a new one. 10 | 11 | 2. Under "APIs & auth", click "Credentials". 12 | 13 | 3. Under "OAuth", click the "Create new client ID" button. 14 | 15 | 4. Select "Service account" as the application type and click "Create Client ID". 16 | 17 | 5. The key for your new service account should prompt for download automatically. Note that your key is protected with a password. 18 | IMPORTANT: keep a secure copy of the key, as Google keeps only the public key. 19 | 20 | 6. Convert the downloaded key to PEM, so we can use it from the Node [crypto](http://nodejs.org/api/crypto.html) module. 21 | 22 | To do this, run the following in Terminal: 23 | ```bash 24 | openssl pkcs12 -in downloaded-key-file.p12 -out your-key-file.pem -nodes 25 | ``` 26 | 27 | You will be asked for the password you received during step 5. 28 | 29 | That's it! You now have a service account with an email address and a key that you can use from your Node application. 30 | 31 | [Source. Thanks!](https://github.com/extrabacon/google-oauth-jwt) 32 | 33 | ### Testing 34 | 35 | Replace the `keyFile.pem` file with the generated file generated in the previous step. Set your data in `authData.json`. 36 | 37 | Then you can run examples. 38 | 39 | ```sh 40 | $ node .js 41 | ``` 42 | -------------------------------------------------------------------------------- /samples/customsearch/customsearch.js: -------------------------------------------------------------------------------- 1 | // Copyright 2012-2016, Google, Inc. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | 'use strict'; 15 | 16 | // Example: node customsearch.js example_term 17 | 18 | const {google} = require('googleapis'); 19 | const customsearch = google.customsearch('v1'); 20 | 21 | // Ex: node customsearch.js 22 | // "Google Node.js" 23 | // "API KEY" 24 | // "CUSTOM ENGINE ID" 25 | 26 | function runSample (options, callback) { 27 | console.log(options); 28 | customsearch.cse.list({ 29 | cx: options.cx, 30 | q: options.q, 31 | auth: options.apiKey 32 | }, (err, res) => { 33 | if (err) { 34 | throw err; 35 | } 36 | console.log(res.data); 37 | callback(res.data); 38 | }); 39 | } 40 | 41 | if (module === require.main) { 42 | // You can get a custom search engine id at 43 | // https://www.google.com/cse/create/new 44 | const options = { 45 | q: process.argv[2], 46 | apiKey: process.argv[3], 47 | cx: process.argv[4] 48 | }; 49 | runSample(options, () => { /* complete */ }); 50 | } 51 | 52 | module.exports = { 53 | runSample 54 | }; 55 | -------------------------------------------------------------------------------- /samples/directory_v1/group-email-delete.js: -------------------------------------------------------------------------------- 1 | // Copyright 2014-2016, Google, Inc. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | 'use strict'; 15 | 16 | const {google} = require('googleapis'); 17 | const path = require('path'); 18 | const nconf = require('nconf'); 19 | 20 | nconf.argv().env().file(path.join(__dirname, '../jwt.keys.json')); 21 | 22 | // Create JWT auth object 23 | const jwt = new google.auth.JWT( 24 | nconf.get('client_email'), 25 | null, 26 | nconf.get('private_key'), 27 | [ 28 | 'https://www.googleapis.com/auth/admin.directory.group', 29 | 'https://www.googleapis.com/auth/admin.directory.group.member' 30 | ] 31 | ); 32 | 33 | // Authorize 34 | jwt.authorize((err, data) => { 35 | if (err) { 36 | throw err; 37 | } 38 | console.log('You have been successfully authenticated: ', data); 39 | 40 | // Get Google Admin API 41 | const admin = google.admin('directory_v1'); 42 | 43 | // Delete member from Google group 44 | admin.members.delete({ 45 | groupKey: 'my_group@example.com', 46 | memberKey: 'me@example.com', 47 | auth: jwt 48 | }, (err, data) => { 49 | console.log(err || data); 50 | }); 51 | }); 52 | -------------------------------------------------------------------------------- /test/fixtures/oauthcerts.json: -------------------------------------------------------------------------------- 1 | { 2 | "a15eea964ab9cce480e5ef4f47cb17b9fa7d0b21": "-----BEGIN CERTIFICATE-----\nMIICITCCAYqgAwIBAgIIY9n5UFWlXMAwDQYJKoZIhvcNAQEFBQAwNjE0MDIGA1UE\nAxMrZmVkZXJhdGVkLXNpZ25vbi5zeXN0ZW0uZ3NlcnZpY2VhY2NvdW50LmNvbTAe\nFw0xNDA3MTUyMTU4MzRaFw0xNDA3MTcxMDU4MzRaMDYxNDAyBgNVBAMTK2ZlZGVy\nYXRlZC1zaWdub24uc3lzdGVtLmdzZXJ2aWNlYWNjb3VudC5jb20wgZ8wDQYJKoZI\nhvcNAQEBBQADgY0AMIGJAoGBAMT3/AJ10HrJpVccblw6/U5tRla+XRLnqIwrL6d5\nafjp2foFzY6pMpF6Nf0kDVZrLEi00nLAJ4XLc3DMAU6Lfmasz8ssCsZtt4egYb9C\nRXc1XgiX0xNGILjVuniq1bWMuoXYO3ZOFTQC6ja3Yh6cEXNowAhWYhxSL0FErur9\nJ0mRAgMBAAGjODA2MAwGA1UdEwEB/wQCMAAwDgYDVR0PAQH/BAQDAgeAMBYGA1Ud\nJQEB/wQMMAoGCCsGAQUFBwMCMA0GCSqGSIb3DQEBBQUAA4GBAIh8vugPyw8JpCrj\nLrIy2w22hqUvs001o9PcFochdlXfsBJdPSm6iO3tYJHGBv8CXqiepr6yBToQMyIh\nay55A11QtLwKlEcpq1adMe8iqkqhWzqYNGU0zLn1+XsINy8g3YDLyFemX/0OA9r1\n7WuFo73Jp3O5G0fI6E56rRTZQzCf\n-----END CERTIFICATE-----\n", 3 | "39596dc3a3f12aa74b481579e4ec944f86d24b95": "-----BEGIN CERTIFICATE-----\nMIICITCCAYqgAwIBAgIIVGbuMRHq6YMwDQYJKoZIhvcNAQEFBQAwNjE0MDIGA1UE\nAxMrZmVkZXJhdGVkLXNpZ25vbi5zeXN0ZW0uZ3NlcnZpY2VhY2NvdW50LmNvbTAe\nFw0xNDA3MTYyMTQzMzRaFw0xNDA3MTgxMDQzMzRaMDYxNDAyBgNVBAMTK2ZlZGVy\nYXRlZC1zaWdub24uc3lzdGVtLmdzZXJ2aWNlYWNjb3VudC5jb20wgZ8wDQYJKoZI\nhvcNAQEBBQADgY0AMIGJAoGBAKE7fORxNmBsk0IRN5J+IGk4QkD6bYGN89yyav8d\nqvUJ7NThVJoVK9CbsO8DW9PVohabTAfoebVakBF4gMzcKvMvoJ0lyFiy9R6/t9Py\nvb4kUhyo6nXBcdEQQ/rPhM777LqXxfMaA75LXBU07v0XS4mIu4mq75K2AM2kjrOC\nlJ+TAgMBAAGjODA2MAwGA1UdEwEB/wQCMAAwDgYDVR0PAQH/BAQDAgeAMBYGA1Ud\nJQEB/wQMMAoGCCsGAQUFBwMCMA0GCSqGSIb3DQEBBQUAA4GBABqDpTNCkk26mDh5\n925qoneRWHC5mnTkdG/k5FFplTABwtDCfiDlsrnjq1cKkDfl9GrCc8T7UKeJwjR3\n+dGo6SlBzC9Zt8SYPS//nDFFj1PdgGSGoTnp4ku47CdqJgY4x19IsVq+d0Ezetr9\nyS8GRVi86P14/r4vsn3SJmolhZmI\n-----END CERTIFICATE-----\n" 4 | } 5 | -------------------------------------------------------------------------------- /samples/directory_v1/group-email-insert.js: -------------------------------------------------------------------------------- 1 | // Copyright 2014-2016, Google, Inc. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | 'use strict'; 15 | 16 | const {google} = require('googleapis'); 17 | const path = require('path'); 18 | const nconf = require('nconf'); 19 | 20 | nconf.argv().env().file(path.join(__dirname, '../jwt.keys.json')); 21 | 22 | // Create JWT auth object 23 | const jwt = new google.auth.JWT( 24 | nconf.get('client_email'), 25 | null, 26 | nconf.get('private_key'), 27 | [ 28 | 'https://www.googleapis.com/auth/admin.directory.group', 29 | 'https://www.googleapis.com/auth/admin.directory.group.member' 30 | ] 31 | ); 32 | 33 | // Authorize 34 | jwt.authorize((err, data) => { 35 | if (err) { 36 | throw err; 37 | } 38 | console.log('You have been successfully authenticated: ', data); 39 | 40 | // Get Google Admin API 41 | const admin = google.admin('directory_v1'); 42 | 43 | // Insert member in Google group 44 | admin.members.insert({ 45 | groupKey: 'my_group@example.com', 46 | resource: { email: 'me@example.com' }, 47 | auth: jwt 48 | }, (err, data) => { 49 | console.log(err || data); 50 | }); 51 | }); 52 | -------------------------------------------------------------------------------- /test/samples/test.samples.youtube.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018, Google, LLC. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | import * as assert from 'assert'; 15 | import * as fs from 'fs'; 16 | import * as nock from 'nock'; 17 | import * as os from 'os'; 18 | import * as path from 'path'; 19 | 20 | import {Utils} from './../utils'; 21 | 22 | nock.disableNetConnect(); 23 | 24 | // tslint:disable: no-any 25 | const samples: any = { 26 | upload: require('../../../samples/youtube/upload') 27 | }; 28 | 29 | for (const p in samples) { 30 | if (samples[p]) { 31 | samples[p].client.credentials = {access_token: 'not-a-token'}; 32 | } 33 | } 34 | 35 | const someFile = path.resolve('test/fixtures/public.pem'); 36 | 37 | describe('YouTube samples', () => { 38 | afterEach(() => { 39 | nock.cleanAll(); 40 | }); 41 | 42 | it('should upload a video', done => { 43 | const scope = 44 | nock(Utils.baseUrl) 45 | .post( 46 | `/upload/youtube/v3/videos?part=id%2Csnippet%2Cstatus¬ifySubscribers=false&uploadType=multipart`) 47 | .reply(200, {kind: 'youtube#video'}); 48 | samples.upload.runSample(someFile, (data: {kind: string}) => { 49 | assert(data); 50 | assert.equal(data.kind, 'youtube#video'); 51 | scope.done(); 52 | done(); 53 | }); 54 | }); 55 | }); 56 | -------------------------------------------------------------------------------- /test/samples/test.samples.gmail.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018, Google, LLC. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | import * as assert from 'assert'; 15 | import * as fs from 'fs'; 16 | import * as nock from 'nock'; 17 | import * as os from 'os'; 18 | import * as path from 'path'; 19 | 20 | import {Utils} from './../utils'; 21 | 22 | nock.disableNetConnect(); 23 | 24 | // tslint:disable: no-any 25 | const samples: any = { 26 | list: require('../../../samples/gmail/list'), 27 | labels: require('../../../samples/gmail/labels') 28 | }; 29 | 30 | for (const p in samples) { 31 | if (samples[p]) { 32 | samples[p].client.credentials = {access_token: 'not-a-token'}; 33 | } 34 | } 35 | 36 | describe('gmail samples', () => { 37 | afterEach(() => { 38 | nock.cleanAll(); 39 | }); 40 | 41 | it('should list emails', done => { 42 | const scope = 43 | nock(Utils.baseUrl).get(`/gmail/v1/users/me/messages`).reply(200, { 44 | yes: true 45 | }); 46 | samples.list.runSample((data: {}) => { 47 | assert(data); 48 | scope.done(); 49 | done(); 50 | }); 51 | }); 52 | 53 | it('should add a label', done => { 54 | const messageId = '12345'; 55 | const labelId = 'abcde'; 56 | const scope = nock(Utils.baseUrl) 57 | .post(`/gmail/v1/users/me/messages/${messageId}/modify`) 58 | .reply(200, {yes: true}); 59 | samples.labels.runSample('add', messageId, labelId, (data: {}) => { 60 | assert(data); 61 | scope.done(); 62 | done(); 63 | }); 64 | }); 65 | }); 66 | -------------------------------------------------------------------------------- /samples/drive/download.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016, Google, Inc. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | 'use strict'; 15 | 16 | const {google} = require('googleapis'); 17 | const sampleClient = require('../sampleclient'); 18 | const fs = require('fs'); 19 | const os = require('os'); 20 | 21 | const drive = google.drive({ 22 | version: 'v3', 23 | auth: sampleClient.oAuth2Client 24 | }); 25 | const scopes = ['https://www.googleapis.com/auth/drive.metadata.readonly']; 26 | 27 | function downloadDoc (callback) { 28 | // [START main_body] 29 | const fileId = '0B7l5uajXUzaFa0x6cjJfZEkzZVE'; 30 | const dest = fs.createWriteStream(`${os.tmpdir()}/photo.jpg`); 31 | 32 | drive.files.get( 33 | {fileId, alt: 'media'}, 34 | {responseType: 'stream'}, 35 | (err, res) => { 36 | if (err) { 37 | console.error(err); 38 | throw err; 39 | } 40 | res.data.on('end', () => { 41 | console.log('Done downloading file.'); 42 | callback(); 43 | }) 44 | .on('error', err => { 45 | console.error('Error downloading file.'); 46 | throw err; 47 | }) 48 | .pipe(dest); 49 | }); 50 | // [END main_body] 51 | } 52 | 53 | // if invoked directly (not tests), authenticate and run the samples 54 | if (module === require.main) { 55 | sampleClient.authenticate(scopes, err => { 56 | if (err) { 57 | throw err; 58 | } 59 | downloadDoc(() => { /* download complete */ }); 60 | }); 61 | } 62 | 63 | // export functions for testing purposes 64 | module.exports = { 65 | downloadDoc, 66 | client: sampleClient.oAuth2Client 67 | }; 68 | -------------------------------------------------------------------------------- /src/templates/index.njk: -------------------------------------------------------------------------------- 1 | // Copyright 2012-2016, Google, Inc. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | /*! THIS FILE IS AUTO-GENERATED */ 15 | 16 | import * as path from 'path'; 17 | import * as util from 'util'; 18 | import { APIList, ServiceOptions } from '../lib/api'; 19 | 20 | export interface APIList { 21 | // tslint:disable-next-line: no-any 22 | [index: string]: { [index: string]: any }; 23 | } 24 | 25 | const APIS: APIList = { 26 | {% for apiName, api in apis %}{{ apiName }}: { 27 | {% for versionName, version in api %}'{{ version }}': require('./{{ apiName }}/{{ version }}'), 28 | {% endfor %} 29 | }, 30 | {% endfor %} 31 | }; 32 | 33 | function getAPI(api: string, options: ServiceOptions|string) { 34 | let version: string; 35 | if (typeof options === 'string') { 36 | version = options; 37 | options = {}; 38 | } else if (typeof options === 'object') { 39 | version = options.version!; 40 | delete options.version; 41 | } else { 42 | throw new Error('Argument error: Accepts only string or object'); 43 | } 44 | try { 45 | const endpoint = APIS[api][path.basename(version)]; 46 | const ep = new endpoint(options); 47 | ep.google = this; // for drive.google.transporter 48 | return Object.freeze(ep); // create new & freeze 49 | } catch (e) { 50 | throw new Error( 51 | `Unable to load endpoint ${api}("${version}"): ${e.message}`); 52 | } 53 | } 54 | 55 | export class GeneratedAPIs { 56 | {% for apiName, api in apis %} 57 | {{ apiName }}(options: ServiceOptions|string) { 58 | return getAPI.call(this, '{{ apiName }}', options); 59 | } 60 | {% endfor %} 61 | } -------------------------------------------------------------------------------- /samples/drive/export.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016, Google, Inc. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | 'use strict'; 15 | 16 | const {google} = require('googleapis'); 17 | const sampleClient = require('../sampleclient'); 18 | const fs = require('fs'); 19 | const os = require('os'); 20 | 21 | const drive = google.drive({ 22 | version: 'v3', 23 | auth: sampleClient.oAuth2Client 24 | }); 25 | const scopes = ['https://www.googleapis.com/auth/drive.metadata.readonly']; 26 | 27 | function exportDoc (callback) { 28 | // [START main_body] 29 | const fileId = '1ZdR3L3qP4Bkq8noWLJHSr_iBau0DNT4Kli4SxNc2YEo'; 30 | const dest = fs.createWriteStream(`${os.tmpdir()}/resume.pdf`); 31 | 32 | drive.files.export( 33 | { fileId, mimeType: 'application/pdf' }, 34 | { responseType: 'stream' }, 35 | (err, res) => { 36 | if (err) { 37 | console.error(err); 38 | throw err; 39 | } 40 | res.data.on('end', () => { 41 | console.log('Done downloading document.'); 42 | callback(); 43 | }) 44 | .on('error', err => { 45 | console.error('Error downloading document.'); 46 | throw err; 47 | }) 48 | .pipe(dest); 49 | }); 50 | // [END main_body] 51 | } 52 | 53 | // if invoked directly (not tests), authenticate and run the samples 54 | if (module === require.main) { 55 | sampleClient.authenticate(scopes, err => { 56 | if (err) { 57 | throw err; 58 | } 59 | exportDoc(() => { /* export complete */ }); 60 | }); 61 | } 62 | 63 | // export functions for testing purposes 64 | module.exports = { 65 | exportDoc, 66 | client: sampleClient.oAuth2Client 67 | }; 68 | -------------------------------------------------------------------------------- /samples/drive/upload.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016, Google, Inc. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | 'use strict'; 15 | 16 | const {google} = require('googleapis'); 17 | const fs = require('fs'); 18 | const sampleClient = require('../sampleclient'); 19 | 20 | const drive = google.drive({ 21 | version: 'v3', 22 | auth: sampleClient.oAuth2Client 23 | }); 24 | 25 | function runSample (fileName, callback) { 26 | const fileSize = fs.statSync(fileName).size; 27 | drive.files.create({ 28 | resource: { 29 | // a resource element is required if you want to use multipart 30 | }, 31 | media: { 32 | body: fs.createReadStream(fileName) 33 | } 34 | }, { 35 | // Use the `onUploadProgress` event from Axios to track the 36 | // number of bytes uploaded to this point. 37 | onUploadProgress: evt => { 38 | const progress = (evt.bytesRead / fileSize) * 100; 39 | process.stdout.clearLine(); 40 | process.stdout.cursorTo(0); 41 | process.stdout.write(`${Math.round(progress)}% complete`); 42 | } 43 | }, (err, res) => { 44 | if (err) { 45 | throw err; 46 | } 47 | console.log(res.data); 48 | callback(res.data); 49 | }); 50 | } 51 | 52 | // if invoked directly (not tests), authenticate and run the samples 53 | if (module === require.main) { 54 | const scopes = ['https://www.googleapis.com/auth/drive.file']; 55 | sampleClient.authenticate(scopes, err => { 56 | if (err) { 57 | throw err; 58 | } 59 | const fileName = process.argv[2]; 60 | runSample(fileName, () => { /* complete */ }); 61 | }); 62 | } 63 | 64 | // export functions for testing purposes 65 | module.exports = { 66 | runSample, 67 | client: sampleClient.oAuth2Client 68 | }; 69 | -------------------------------------------------------------------------------- /samples/jwt.js: -------------------------------------------------------------------------------- 1 | // Copyright 2014-2016, Google, Inc. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | 'use strict'; 15 | 16 | const {google} = require('googleapis'); 17 | 18 | /** 19 | * The JWT authorization is ideal for performing server-to-server 20 | * communication without asking for user consent. 21 | * 22 | * Suggested reading for Admin SDK users using service accounts: 23 | * https://developers.google.com/admin-sdk/directory/v1/guides/delegation 24 | * 25 | * See the defaultauth.js sample for an alternate way of fetching compute credentials. 26 | */ 27 | 28 | const keys = require('./jwt.keys.json'); 29 | 30 | // Create a new JWT client using the key file downloaded from the Google Developer Console 31 | const jwtClient = new google.auth.JWT({ 32 | email: keys.client_email, 33 | key: keys.private_key, 34 | scopes: 'https://www.googleapis.com/auth/drive.readonly' 35 | }); 36 | 37 | // Obtain a new drive client, making sure you pass along the auth client 38 | const drive = google.drive({ 39 | version: 'v2', 40 | auth: jwtClient 41 | }); 42 | 43 | // Make an authorized request to list Drive files. 44 | function runSample (callback) { 45 | drive.files.list((err, res) => { 46 | if (err) { 47 | throw err; 48 | } 49 | console.log(res.data); 50 | callback(res.data); 51 | }); 52 | } 53 | 54 | if (module === require.main) { 55 | // Run `authorize` to obtain the right tokens for auth 56 | jwtClient.authorize(err => { 57 | if (err) { 58 | throw err; 59 | } 60 | // Now that we have credentials, run the sample 61 | runSample(() => { /* complete */ }); 62 | }); 63 | } 64 | 65 | // Exports for unit testing purposes 66 | module.exports = { 67 | runSample, 68 | client: jwtClient 69 | }; 70 | -------------------------------------------------------------------------------- /samples/youtube/playlist.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016, Google, Inc. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | 'use strict'; 15 | 16 | const {google} = require('googleapis'); 17 | const sampleClient = require('../sampleclient'); 18 | 19 | // initialize the Youtube API library 20 | const youtube = google.youtube({ 21 | version: 'v3', 22 | auth: sampleClient.oAuth2Client 23 | }); 24 | 25 | // a very simple example of getting data from a playlist 26 | function runSamples () { 27 | // the first query will return data with an etag 28 | getPlaylistData(null, (err, res) => { 29 | if (err) { 30 | throw err; 31 | } 32 | const etag = res.data.etag; 33 | console.log(`etag: ${etag}`); 34 | 35 | // the second query will (likely) return no data, and an HTTP 304 36 | // since the If-None-Match header was set with a matching eTag 37 | getPlaylistData(etag, (err, res) => { 38 | if (err) { 39 | throw err; 40 | } 41 | console.log(res.status); 42 | }); 43 | }); 44 | } 45 | 46 | function getPlaylistData (etag, callback) { 47 | // Create custom HTTP headers for the request to enable 48 | // use of eTags 49 | const headers = {}; 50 | if (etag) { 51 | headers['If-None-Match'] = etag; 52 | } 53 | youtube.playlists.list({ 54 | part: 'id,snippet', 55 | id: 'PLIivdWyY5sqIij_cgINUHZDMnGjVx3rxi', 56 | headers: headers 57 | }, (err, res) => { 58 | if (err) { 59 | throw err; 60 | } 61 | if (res) { 62 | console.log('Status code: ' + res.status); 63 | } 64 | console.log(res.data); 65 | callback(err, res); 66 | }); 67 | } 68 | 69 | const scopes = [ 70 | 'https://www.googleapis.com/auth/youtube' 71 | ]; 72 | 73 | sampleClient.authenticate(scopes, err => { 74 | if (err) { 75 | throw err; 76 | } 77 | runSamples(); 78 | }); 79 | -------------------------------------------------------------------------------- /samples/analytics/analytics.js: -------------------------------------------------------------------------------- 1 | // Copyright 2013-2016, Google, Inc. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | 'use strict'; 15 | 16 | const {google} = require('googleapis'); 17 | const sampleClient = require('../sampleclient'); 18 | 19 | const analytics = google.analytics({ 20 | version: 'v3', 21 | auth: sampleClient.oAuth2Client 22 | }); 23 | 24 | // Custom Goals must be exist prior to used as an objectiveMetric 25 | const objectiveMetric = 'ga:goal1Completions'; 26 | 27 | // Serving frameworks listed below: 28 | // https://developers.google.com/analytics/devguides/platform/experiments#serving-framework 29 | const servingFramework = 'API'; 30 | 31 | // Invalid URLs are used when user is not redirected when showing an experiment 32 | // Read more: http://goo.gl/oVwKH1 33 | const variations = [ 34 | {'name': 'Default', 'url': 'http://www.example.com', 'status': 'ACTIVE'}, 35 | {'name': 'variation 1', 'url': 'http://www.1.com', 'status': 'ACTIVE'}, 36 | {'name': 'variation 2', 'url': 'http://www.2.com', 'status': 'ACTIVE'} 37 | ]; 38 | 39 | // Specify Experiment configuration 40 | const resourceBody = { 41 | 'name': 'Example Experiment', 42 | 'status': 'READY_TO_RUN', 43 | 'objectiveMetric': objectiveMetric, 44 | 'servingFramework': servingFramework, 45 | 'variations': variations 46 | }; 47 | 48 | const scopes = [ 49 | 'https://www.googleapis.com/auth/analytics' 50 | ]; 51 | 52 | function runSample () { 53 | analytics.management.experiments.insert({ 54 | accountId: 'your-accountId', 55 | webPropertyId: 'your-webPropertyId', 56 | profileId: 'your-profileId', 57 | resource: resourceBody 58 | }, (err, res) => { 59 | if (err) { 60 | throw err; 61 | } 62 | console.log(res.data); 63 | }); 64 | } 65 | 66 | sampleClient.authenticate(scopes, err => { 67 | if (err) { 68 | throw err; 69 | } 70 | runSample(); 71 | }); 72 | -------------------------------------------------------------------------------- /samples/mediaupload.js: -------------------------------------------------------------------------------- 1 | // Copyright 2013-2016, Google, Inc. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | 'use strict'; 15 | 16 | const {google} = require('googleapis'); 17 | const drive = google.drive('v2'); 18 | const sampleClient = require('./sampleclient'); 19 | 20 | function runSamples () { 21 | // insertion example 22 | drive.files.insert({ 23 | resource: { 24 | title: 'Test', 25 | mimeType: 'text/plain' 26 | }, 27 | media: { 28 | mimeType: 'text/plain', 29 | body: 'Hello World updated with metadata' 30 | }, 31 | auth: sampleClient.oAuth2Client 32 | }, (err, res) => { 33 | if (err) { 34 | throw err; 35 | } 36 | console.log(res.data); 37 | }); 38 | 39 | // update with no metadata 40 | drive.files.update({ 41 | fileId: '0B-skmV2m1Arna1lZSGFHNWx6YXc', 42 | media: { 43 | mimeType: 'text/plain', 44 | body: 'Hello World updated with metadata' 45 | }, 46 | auth: sampleClient.oAuth2Client 47 | }, (err, res) => { 48 | if (err) { 49 | throw err; 50 | } 51 | console.log(res.data); 52 | }); 53 | 54 | // update example with metadata update 55 | drive.files.update({ 56 | fileId: '0B-skmV2...', 57 | resource: { 58 | title: 'Updated title' 59 | }, 60 | media: { 61 | mimeType: 'text/plain', 62 | body: 'Hello World updated with metadata' 63 | }, 64 | auth: sampleClient.oAuth2Client 65 | }, (err, res) => { 66 | if (err) { 67 | throw err; 68 | } 69 | console.log(res.data); 70 | }); 71 | } 72 | 73 | const scopes = [ 74 | 'https://www.googleapis.com/auth/drive.metadata', 75 | 'https://www.googleapis.com/auth/drive.photos', 76 | 'https://www.googleapis.com/auth/drive' 77 | ]; 78 | 79 | sampleClient.authenticate(scopes, err => { 80 | if (err) { 81 | throw err; 82 | } 83 | runSamples(); 84 | }); 85 | -------------------------------------------------------------------------------- /samples/gmail/labels.js: -------------------------------------------------------------------------------- 1 | // Copyright 2018, Google, LLC. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | 'use strict'; 15 | 16 | const { google } = require('googleapis'); 17 | const sampleClient = require('../sampleclient'); 18 | 19 | const gmail = google.gmail({ 20 | version: 'v1', 21 | auth: sampleClient.oAuth2Client 22 | }); 23 | 24 | function runSample (action, messageId, labelId, callback) { 25 | if (action === 'add') { 26 | gmail.users.messages.modify({ 27 | userId: 'me', 28 | id: messageId, 29 | resource: { 30 | 'addLabelIds': [labelId] 31 | } 32 | }, (err, res) => { 33 | if (err) { 34 | throw err; 35 | } 36 | console.log(res.data); 37 | callback(res.data); 38 | }); 39 | } else if (action === 'remove') { 40 | gmail.users.messages.modify({ 41 | userId: 'me', 42 | id: messageId, 43 | resource: { 44 | 'removeLabelIds': [labelId] 45 | } 46 | }, (err, res) => { 47 | if (err) { 48 | throw err; 49 | } 50 | console.log(res.data); 51 | callback(res.data); 52 | }); 53 | } 54 | } 55 | 56 | const scopes = ['https://www.googleapis.com/auth/gmail.modify']; 57 | 58 | if (module === require.main) { 59 | sampleClient.authenticate(scopes, err => { 60 | if (err) { 61 | throw err; 62 | } 63 | if (process.argv.length !== 5) { 64 | showUsage(); 65 | } 66 | const [action, messageId, labelId] = process.argv.slice(2); 67 | console.log(`action: ${action}`); 68 | console.log(`messageId: ${messageId}`); 69 | console.log(`labelId: ${labelId}`); 70 | runSample(action, messageId, labelId, () => { /* add complete */ }); 71 | }); 72 | } 73 | 74 | function showUsage () { 75 | console.info('USAGE: node labels.js '); 76 | process.exit(); 77 | } 78 | 79 | module.exports = { 80 | runSample, 81 | client: sampleClient.oAuth2Client 82 | }; 83 | -------------------------------------------------------------------------------- /samples/oauth2.js: -------------------------------------------------------------------------------- 1 | // Copyright 2012-2016, Google, Inc. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | 'use strict'; 15 | 16 | const {google} = require('googleapis'); 17 | const nconf = require('nconf'); 18 | const readline = require('readline'); 19 | const plus = google.plus('v1'); 20 | const path = require('path'); 21 | const OAuth2Client = google.auth.OAuth2; 22 | 23 | nconf.argv().env().file(path.join(__dirname, '/oauth2.keys.json')); 24 | const keys = nconf.get('web'); 25 | 26 | // Client ID and client secret are available at 27 | // https://code.google.com/apis/console 28 | const CLIENT_ID = keys.client_id; 29 | const CLIENT_SECRET = keys.client_secret; 30 | const REDIRECT_URL = keys.redirect_uris[0]; 31 | 32 | const oauth2Client = new OAuth2Client(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL); 33 | 34 | const rl = readline.createInterface({ 35 | input: process.stdin, 36 | output: process.stdout 37 | }); 38 | 39 | function getAccessToken (oauth2Client, callback) { 40 | // generate consent page url 41 | const url = oauth2Client.generateAuthUrl({ 42 | access_type: 'offline', // will return a refresh token 43 | scope: 'https://www.googleapis.com/auth/plus.me' // can be a space-delimited string or an array of scopes 44 | }); 45 | 46 | console.log('Visit the url: ', url); 47 | rl.question('Enter the code here:', code => { 48 | // request access token 49 | oauth2Client.getToken(code, (err, tokens) => { 50 | if (err) { 51 | return callback(err); 52 | } 53 | // set tokens to the client 54 | // TODO: tokens should be set by OAuth2 client. 55 | oauth2Client.setCredentials(tokens); 56 | callback(); 57 | }); 58 | }); 59 | } 60 | 61 | // retrieve an access token 62 | getAccessToken(oauth2Client, () => { 63 | // retrieve user profile 64 | plus.people.get({ userId: 'me', auth: oauth2Client }, (err, res) => { 65 | if (err) { 66 | throw err; 67 | } 68 | console.log(res.data.displayName, ':', res.data.tagline); 69 | }); 70 | }); 71 | -------------------------------------------------------------------------------- /samples/youtube/upload.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016, Google, Inc. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | 'use strict'; 15 | 16 | /** 17 | * Usage: node upload.js PATH_TO_VIDEO_FILE 18 | */ 19 | 20 | const {google} = require('googleapis'); 21 | const sampleClient = require('../sampleclient'); 22 | const fs = require('fs'); 23 | 24 | // initialize the Youtube API library 25 | const youtube = google.youtube({ 26 | version: 'v3', 27 | auth: sampleClient.oAuth2Client 28 | }); 29 | 30 | // very basic example of uploading a video to youtube 31 | function runSample (fileName, callback) { 32 | const fileSize = fs.statSync(fileName).size; 33 | youtube.videos.insert({ 34 | part: 'id,snippet,status', 35 | notifySubscribers: false, 36 | resource: { 37 | snippet: { 38 | title: 'Node.js YouTube Upload Test', 39 | description: 'Testing YouTube upload via Google APIs Node.js Client' 40 | }, 41 | status: { 42 | privacyStatus: 'private' 43 | } 44 | }, 45 | media: { 46 | body: fs.createReadStream(fileName) 47 | } 48 | }, { 49 | // Use the `onUploadProgress` event from Axios to track the 50 | // number of bytes uploaded to this point. 51 | onUploadProgress: evt => { 52 | const progress = (evt.bytesRead / fileSize) * 100; 53 | process.stdout.clearLine(); 54 | process.stdout.cursorTo(0); 55 | process.stdout.write(`${Math.round(progress)}% complete`); 56 | } 57 | }, (err, res) => { 58 | if (err) { 59 | throw err; 60 | } 61 | console.log('\n\n'); 62 | console.log(res.data); 63 | callback(res.data); 64 | }); 65 | } 66 | 67 | const scopes = [ 68 | 'https://www.googleapis.com/auth/youtube.upload', 69 | 'https://www.googleapis.com/auth/youtube' 70 | ]; 71 | 72 | if (module === require.main) { 73 | const fileName = process.argv[2]; 74 | sampleClient.authenticate(scopes, err => { 75 | if (err) { 76 | throw err; 77 | } 78 | runSample(fileName, () => { /* sample complete */ }); 79 | }); 80 | } 81 | 82 | module.exports = { 83 | runSample, 84 | client: sampleClient.oAuth2Client 85 | }; 86 | -------------------------------------------------------------------------------- /test/test.kitchen.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import * as cp from 'child_process'; 18 | import * as fs from 'fs'; 19 | import * as mv from 'mv'; 20 | import {ncp} from 'ncp'; 21 | import * as pify from 'pify'; 22 | import * as tmp from 'tmp'; 23 | 24 | const mvp = pify(mv); 25 | const ncpp = pify(ncp); 26 | const keep = !!process.env.GANC_KEEP_TEMPDIRS; 27 | const stagingDir = tmp.dirSync({keep, unsafeCleanup: true}); 28 | const stagingPath = stagingDir.name; 29 | const pkg = require('../../package.json'); 30 | 31 | const spawnp = (command: string, args: string[], options: cp.SpawnOptions = {}): 32 | Promise => { 33 | return new Promise((resolve, reject) => { 34 | cp.spawn( 35 | command, args, 36 | Object.assign(options, {stdio: 'inherit', shell: true})) 37 | .on('close', 38 | (code, signal) => { 39 | if (code === 0) { 40 | resolve(); 41 | } else { 42 | reject( 43 | new Error(`Spawn failed with an exit code of ${code}`)); 44 | } 45 | }) 46 | .on('error', err => { 47 | reject(err); 48 | }); 49 | }); 50 | }; 51 | 52 | /** 53 | * Create a staging directory with temp fixtures used 54 | * to test on a fresh application. 55 | */ 56 | 57 | describe('kitchen sink', async () => { 58 | it('should be able to use the d.ts', async () => { 59 | console.log(`${__filename} staging area: ${stagingPath}`); 60 | await spawnp('npm', ['pack']); 61 | const tarball = `${pkg.name}-${pkg.version}.tgz`; 62 | await mvp(tarball, `${stagingPath}/googleapis.tgz`); 63 | await ncpp('test/fixtures/kitchen', `${stagingPath}/`); 64 | await spawnp('npm', ['install'], {cwd: `${stagingPath}/`}); 65 | }).timeout(40000); 66 | }); 67 | 68 | /** 69 | * CLEAN UP - remove the staging directory when done. 70 | */ 71 | after('cleanup staging', async () => { 72 | if (!keep) { 73 | stagingDir.removeCallback(); 74 | } 75 | }); 76 | -------------------------------------------------------------------------------- /test/test.discover.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2016, Google, Inc. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | import * as assert from 'assert'; 15 | import * as fs from 'fs'; 16 | import * as path from 'path'; 17 | 18 | import {GoogleApis} from '../src'; 19 | import {APIEndpoint} from '../src/lib/api'; 20 | 21 | describe('GoogleApis#discover', () => { 22 | it('should generate all apis', (done) => { 23 | const localApis = fs.readdirSync(path.join(__dirname, '../src/apis')); 24 | const google = new GoogleApis(); 25 | // tslint:disable-next-line no-any 26 | const g2 = google as any; 27 | const localDrive = google.drive('v2'); 28 | 29 | assert.equal(typeof google.drive, 'function'); 30 | assert.equal(typeof localDrive, 'object'); 31 | 32 | localApis.splice(localApis.indexOf('index.ts'), 1); 33 | localApis.splice(localApis.indexOf('index.d.ts'), 1); 34 | localApis.splice(localApis.indexOf('index.js'), 1); 35 | localApis.splice(localApis.indexOf('index.js.map'), 1); 36 | 37 | localApis.forEach((name) => { 38 | assert(g2[name]); 39 | // Setting all APIs to null initially. 40 | g2[name] = null; 41 | }); 42 | 43 | assert.equal(google.drive, null); 44 | 45 | google.discover('https://www.googleapis.com/discovery/v1/apis', (err) => { 46 | if (err) { 47 | console.warn(err); 48 | return done(); 49 | } 50 | // APIs have all been re-added. 51 | localApis.forEach(name => { 52 | if (g2[name] === null) { 53 | // Warn if an API remains null (was not found during the discovery 54 | // process) to avoid failing the test. 55 | console.warn(name + ' was not found.'); 56 | } else { 57 | assert(g2[name]); 58 | } 59 | }); 60 | 61 | const remoteDrive = google.drive('v2'); 62 | assert.equal(typeof google.drive, 'function'); 63 | assert.equal(typeof remoteDrive, 'object'); 64 | 65 | for (const key in localDrive) { 66 | if (localDrive.hasOwnProperty(key)) { 67 | assert(remoteDrive[key], 'generated drive has same keys'); 68 | } 69 | } 70 | done(); 71 | }); 72 | }).timeout(120000); 73 | }); 74 | -------------------------------------------------------------------------------- /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | --- 2 | # "Include" for unit tests definition. 3 | unit_tests: &unit_tests 4 | steps: 5 | - checkout 6 | - run: 7 | name: Install modules and dependencies. 8 | command: npm install 9 | - run: 10 | name: Run unit tests. 11 | command: npm test 12 | - run: 13 | name: Submit coverage data to codecov. 14 | command: node_modules/.bin/codecov 15 | when: always 16 | 17 | # Testing the samples requires running `npm link` and 18 | # `npm link googleapis`, which attempts to make a global 19 | # change. This leads to a permissions error unless the 20 | # global npm module directory is changed. These samples 21 | # only tested against latest LTS. 22 | test_samples: &test_samples 23 | steps: 24 | - checkout 25 | - run: npm install 26 | - run: mkdir ~/.npm-packages 27 | - run: echo "prefix = $HOME/.npm-packages" >> ~/.npmrc 28 | - run: export PATH=~/.npm-packages/bin:$PATH 29 | - run: make && make test-samples 30 | 31 | version: 2.0 32 | workflows: 33 | version: 2 34 | tests: 35 | jobs: 36 | - node4: 37 | filters: 38 | tags: 39 | only: /.*/ 40 | - node6: 41 | filters: 42 | tags: 43 | only: /.*/ 44 | - node8: 45 | filters: 46 | tags: 47 | only: /.*/ 48 | - node9: 49 | filters: 50 | tags: 51 | only: /.*/ 52 | - publish_npm: 53 | requires: 54 | - node4 55 | - node6 56 | - node8 57 | - node9 58 | filters: 59 | branches: 60 | ignore: /.*/ 61 | tags: 62 | only: /^v[\d.]+$/ 63 | 64 | jobs: 65 | node4: 66 | docker: 67 | - image: node:4 68 | user: node 69 | <<: *unit_tests 70 | node6: 71 | docker: 72 | - image: node:6 73 | user: node 74 | <<: *unit_tests 75 | node8: 76 | docker: 77 | - image: node:8 78 | user: node 79 | <<: *unit_tests 80 | <<: *test_samples 81 | node9: 82 | docker: 83 | - image: node:9 84 | user: node 85 | <<: *unit_tests 86 | 87 | publish_npm: 88 | docker: 89 | - image: node:8 90 | user: node 91 | steps: 92 | - checkout 93 | - run: 94 | name: Install modules and dependencies. 95 | command: npm install --unsafe-perm 96 | - run: 97 | name: Set NPM authentication. 98 | command: echo "//registry.npmjs.org/:_authToken=${NPM_TOKEN}" > ~/.npmrc 99 | - run: 100 | name: Publish the module to npm. 101 | command: npm publish --access=public 102 | -------------------------------------------------------------------------------- /.github/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Before making any contributions, please sign one of the contributor 4 | license agreements below. 5 | 6 | Fork the repo, develop and test your code changes. 7 | 8 | Install all dependencies including development requirements by running: 9 | 10 | ``` sh 11 | $ npm install -d 12 | ``` 13 | 14 | Tests are run using mocha. To run all tests just run: 15 | 16 | ``` sh 17 | $ npm test 18 | ``` 19 | 20 | which looks for tests in the `test/` directory. 21 | 22 | Your code should honor the [Google JavaScript Style Guide][js-guide]. 23 | You can use [Closure Linter][c-linter] to detect style issues. 24 | 25 | Submit a pull request. The repo owner will review your request. If it is 26 | approved, the change will be merged. If it needs additional work, the repo 27 | owner will respond with useful comments. 28 | 29 | ## Generating APIs 30 | 31 | If you're a developer interested in contributing to this library, the following 32 | section will be useful for you. Each of the files in `apis/` is generated from 33 | the discovery docs available online. You can generate these files by running 34 | the following command: 35 | 36 | ``` sh 37 | npm run generate-apis 38 | ``` 39 | 40 | You can pass in custom Discovery URLs or paths to discovery docs: 41 | 42 | ``` sh 43 | node scripts/generate http://discoveryurl.example.com /path/to/discoverydoc.json 44 | ``` 45 | 46 | ## Generating Documentation 47 | 48 | You can generate the documentation for the APIs by running: 49 | 50 | ``` sh 51 | npm run generate-docs 52 | ``` 53 | 54 | Documentation will be generated in `docs/`. 55 | 56 | ## Preparing for release 57 | 58 | Before releasing a new version, you should generate all APIs, run tests, 59 | bump the version in `package.json` and create a git tag for the release. You 60 | can automate all this with a patch version bump (version += 0.0.1) by running: 61 | 62 | ``` sh 63 | npm run prepare 64 | ``` 65 | 66 | ## Contributor License Agreements 67 | 68 | Before creating a pull request, please fill out either the individual or 69 | corporate Contributor License Agreement. 70 | 71 | * If you are an individual writing original source code and you're sure you 72 | own the intellectual property, then you'll need to sign an 73 | [individual CLA][indv-cla]. 74 | * If you work for a company that wants to allow you to contribute your work 75 | to this client library, then you'll need to sign a 76 | [corporate CLA][corp-cla]. 77 | 78 | Follow either of the two links above to access the appropriate CLA and 79 | instructions for how to sign and return it. Once we receive it, we'll add you 80 | to the official list of contributors and be able to accept your patches. 81 | 82 | [js-guide]: https://google.github.io/styleguide/jsguide.html 83 | [c-linter]: https://code.google.com/p/closure-linter/ 84 | [indv-cla]: https://developers.google.com/open-source/cla/individual 85 | [corp-cla]: https://developers.google.com/open-source/cla/corporate 86 | -------------------------------------------------------------------------------- /src/templates/method-partial.njk: -------------------------------------------------------------------------------- 1 | {% macro render(m, mname, api, globalmethods) %} 2 | {% set lb = "{" %} 3 | {% set rb = "}" %} 4 | {% set pathParams = m.parameters|getPathParams|sort %} 5 | /** 6 | * {{ m.id }} 7 | {% if m.description %} 8 | * @desc {{ m.description|oneLine|cleanComments|safe }} 9 | {% endif %} 10 | {% if m.fragment %} 11 | * @example 12 | {{ m.fragment|safe }} 13 | {% endif %} 14 | * @alias {{ m.id }} 15 | * @memberOf! {{ api.name }}({{ api.version }}) 16 | * 17 | * @param {object{% if not m.parameterOrder and not m.request %}={% endif %}} params Parameters for request 18 | {% if m.parameters %} 19 | {% for pname, p in m.parameters|dictsort %} 20 | * @param {{ lb }}{{ p.type }}{% if not p.required %}={% endif %}{{ rb }} params.{{ pname|getSafeParamName }} {{ p.description|oneLine|cleanComments|safe }} 21 | {% endfor %} 22 | {% endif %} 23 | {% if m.supportsMediaUpload %} 24 | {% if m.request %} 25 | * @param {object} params.resource Media resource metadata 26 | {% endif %} 27 | * @param {object} params.media Media object 28 | * @param {string} params.media.mimeType Media mime-type 29 | * @param {string|object} params.media.body Media body contents 30 | {% elif m.request %} 31 | {% if m.request.$ref %} 32 | * @param {{ lb }}{{ api.name }}({{ api.version }}).{{ m.request.$ref }}{{ rb }} params.resource Request body data 33 | {% else %} 34 | * @param {object} params.resource Request body data 35 | {% endif %} 36 | {% endif %} 37 | * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. 38 | * @param {callback} callback The callback that handles the response. 39 | * @return {object} Request object 40 | */ 41 | {% if globalmethods %}this.{{ mname }} = (params: any, options: MethodOptions|BodyResponseCallback, callback?: BodyResponseCallback) => { {% endif %} 42 | {% if not globalmethods %}{{ mname }} (params: any, options: MethodOptions|BodyResponseCallback, callback?: BodyResponseCallback) { {% endif %} 43 | 44 | if (typeof options === 'function') { 45 | callback = options; 46 | options = {}; 47 | } 48 | options = options || {}; 49 | const rootUrl = options.rootUrl || {{ api.rootUrl|buildurl|safe }}; 50 | const parameters = { 51 | options: Object.assign({ 52 | url: (rootUrl + {{ ('/' + api.servicePath + m.path)|buildurl|safe }}).replace(/([^:]\/)\/+/g, '$1'), 53 | method: '{{ m.httpMethod }}' 54 | }, options), 55 | params, 56 | {% if m.mediaUpload.protocols.simple.path %}mediaUrl: (rootUrl + {{ ('/' + m.mediaUpload.protocols.simple.path)|buildurl|safe }}).replace(/([^:]\/)\/+/g, '$1'),{% endif %} 57 | requiredParams: [{% if m.parameterOrder.length %}'{{ m.parameterOrder|join("', '")|safe }}'{% endif %}], 58 | pathParams: [{% if pathParams.length %}'{{ pathParams|join("', '")|safe }}'{% endif %}], 59 | context: self 60 | }; 61 | return createAPIRequest(parameters, callback!); 62 | }{% if globalmethods %};{% endif %}{% endmacro %} -------------------------------------------------------------------------------- /samples/sampleclient.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016, Google, Inc. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | 'use strict'; 15 | 16 | /** 17 | * This is used by several samples to easily provide 18 | * an oauth2 workflow. 19 | */ 20 | 21 | const {google} = require('googleapis'); 22 | const OAuth2Client = google.auth.OAuth2; 23 | const http = require('http'); 24 | const url = require('url'); 25 | const querystring = require('querystring'); 26 | const opn = require('opn'); 27 | const nconf = require('nconf'); 28 | const path = require('path'); 29 | const destroyer = require('server-destroy'); 30 | 31 | nconf.argv().env() 32 | .file(path.join(__dirname, 'oauth2.keys.json')); 33 | let keys = nconf.get('web'); 34 | if (typeof keys === 'string') { 35 | keys = JSON.parse(keys); 36 | } 37 | 38 | class SampleClient { 39 | constructor (options) { 40 | this._options = options || { scopes: [] }; 41 | 42 | // create an oAuth client to authorize the API call 43 | this.oAuth2Client = new OAuth2Client( 44 | keys.client_id, 45 | keys.client_secret, 46 | keys.redirect_uris[0] 47 | ); 48 | } 49 | 50 | // Open an http server to accept the oauth callback. In this 51 | // simple example, the only request to our webserver is to 52 | // /callback?code= 53 | authenticate (scopes, callback) { 54 | // grab the url that will be used for authorization 55 | this.authorizeUrl = this.oAuth2Client.generateAuthUrl({ 56 | access_type: 'offline', 57 | scope: scopes.join(' ') 58 | }); 59 | const server = http.createServer((req, res) => { 60 | if (req.url.indexOf('/oauth2callback') > -1) { 61 | const qs = querystring.parse(url.parse(req.url).query); 62 | res.end('Authentication successful! Please return to the console.'); 63 | server.destroy(); 64 | this.oAuth2Client.getToken(qs.code, (err, tokens) => { 65 | if (err) { 66 | console.error('Error getting oAuth tokens: ' + err); 67 | callback(err); 68 | return; 69 | } 70 | this.oAuth2Client.credentials = tokens; 71 | callback(null, this.oAuth2Client); 72 | }); 73 | } 74 | }).listen(3000, () => { 75 | // open the browser to the authorize url to start the workflow 76 | opn(this.authorizeUrl, {wait: false}).then(cp => cp.unref()); 77 | }); 78 | destroyer(server); 79 | } 80 | } 81 | 82 | module.exports = new SampleClient(); 83 | -------------------------------------------------------------------------------- /samples/drive/quickstart.js: -------------------------------------------------------------------------------- 1 | // Copyright 2018, Google, LLC. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | 'use strict'; 15 | 16 | // [START main_body] 17 | const {google} = require('googleapis'); 18 | const express = require('express'); 19 | const opn = require('opn'); 20 | const path = require('path'); 21 | const fs = require('fs'); 22 | 23 | const keyfile = path.join(__dirname, 'credentials.json'); 24 | const keys = JSON.parse(fs.readFileSync(keyfile)); 25 | const scopes = ['https://www.googleapis.com/auth/drive.metadata.readonly']; 26 | 27 | // Create an oAuth2 client to authorize the API call 28 | const client = new google.auth.OAuth2( 29 | keys.web.client_id, 30 | keys.web.client_secret, 31 | keys.web.redirect_uris[0] 32 | ); 33 | 34 | // Generate the url that will be used for authorization 35 | this.authorizeUrl = client.generateAuthUrl({ 36 | access_type: 'offline', 37 | scope: scopes 38 | }); 39 | 40 | // Open an http server to accept the oauth callback. In this 41 | // simple example, the only request to our webserver is to 42 | // /oauth2callback?code= 43 | const app = express(); 44 | app.get('/oauth2callback', (req, res) => { 45 | const code = req.query.code; 46 | client.getToken(code, (err, tokens) => { 47 | if (err) { 48 | console.error('Error getting oAuth tokens:'); 49 | throw err; 50 | } 51 | client.credentials = tokens; 52 | res.send('Authentication successful! Please return to the console.'); 53 | server.close(); 54 | listFiles(client); 55 | }); 56 | }); 57 | const server = app.listen(3000, () => { 58 | // open the browser to the authorize url to start the workflow 59 | opn(this.authorizeUrl, { wait: false }); 60 | }); 61 | 62 | /** 63 | * Lists the names and IDs of up to 10 files. 64 | * @param {google.auth.OAuth2} auth An authorized OAuth2 client. 65 | */ 66 | function listFiles (auth) { 67 | const service = google.drive('v3'); 68 | service.files.list({ 69 | auth: auth, 70 | pageSize: 10, 71 | fields: 'nextPageToken, files(id, name)' 72 | }, (err, res) => { 73 | if (err) { 74 | console.error('The API returned an error.'); 75 | throw err; 76 | } 77 | const files = res.data.files; 78 | if (files.length === 0) { 79 | console.log('No files found.'); 80 | } else { 81 | console.log('Files:'); 82 | for (const file of files) { 83 | console.log(`${file.name} (${file.id})`); 84 | } 85 | } 86 | }); 87 | } 88 | // [END main_body] 89 | -------------------------------------------------------------------------------- /test/samples/test.samples.drive.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018, Google, LLC. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | import * as assert from 'assert'; 15 | import * as fs from 'fs'; 16 | import * as nock from 'nock'; 17 | import * as os from 'os'; 18 | import * as path from 'path'; 19 | 20 | import {Utils} from './../utils'; 21 | 22 | nock.disableNetConnect(); 23 | 24 | // tslint:disable: no-any 25 | const samples: any = { 26 | download: require('../../../samples/drive/download'), 27 | export: require('../../../samples/drive/export'), 28 | list: require('../../../samples/drive/list'), 29 | upload: require('../../../samples/drive/upload') 30 | }; 31 | 32 | for (const p in samples) { 33 | if (samples[p]) { 34 | samples[p].client.credentials = {access_token: 'not-a-token'}; 35 | } 36 | } 37 | 38 | const someFile = path.resolve('test/fixtures/public.pem'); 39 | 40 | describe('Drive samples', () => { 41 | afterEach(() => { 42 | nock.cleanAll(); 43 | }); 44 | 45 | it('should download the file', done => { 46 | const fileId = '0B7l5uajXUzaFa0x6cjJfZEkzZVE'; 47 | const scope = nock(Utils.baseUrl) 48 | .get(`/drive/v3/files/${fileId}?alt=media`) 49 | .replyWithFile(200, someFile); 50 | samples.download.downloadDoc(() => { 51 | assert(fs.existsSync(`${os.tmpdir()}/photo.jpg`)); 52 | scope.done(); 53 | done(); 54 | }); 55 | }); 56 | 57 | it('should download the doc', done => { 58 | const fileId = '1ZdR3L3qP4Bkq8noWLJHSr_iBau0DNT4Kli4SxNc2YEo'; 59 | const scope = 60 | nock(Utils.baseUrl) 61 | .get(`/drive/v3/files/${fileId}/export?mimeType=application%2Fpdf`) 62 | .replyWithFile(200, someFile); 63 | samples.export.exportDoc(() => { 64 | assert(fs.existsSync(`${os.tmpdir()}/resume.pdf`)); 65 | scope.done(); 66 | done(); 67 | }); 68 | }); 69 | 70 | it('should list all the docs', done => { 71 | const scope = 72 | nock(Utils.baseUrl).get(`/drive/v3/files?pageSize=3`).reply(200, {}); 73 | samples.list.listDocs(undefined, (data: {}) => { 74 | assert(data); 75 | scope.done(); 76 | done(); 77 | }); 78 | }); 79 | 80 | it('should upload a file', done => { 81 | const scope = nock(Utils.baseUrl) 82 | .post(`/upload/drive/v3/files?uploadType=multipart`) 83 | .reply(200, {}); 84 | samples.upload.runSample(someFile, (data: {}) => { 85 | assert(data); 86 | scope.done(); 87 | done(); 88 | }); 89 | }); 90 | }); 91 | -------------------------------------------------------------------------------- /samples/defaultauth.js: -------------------------------------------------------------------------------- 1 | // Copyright 2014-2016, Google, Inc. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | 'use strict'; 15 | 16 | const {google} = require('googleapis'); 17 | const compute = google.compute('v1'); 18 | 19 | /** 20 | * The getApplicationDefault method creates the appropriate type of credential client for you, 21 | * depending upon whether the client is running in Google App Engine, Google Compute Engine, a 22 | * Managed VM, or on a local developer machine. This allows you to write one set of auth code that 23 | * will work in all cases. It most situations, it is advisable to use the getApplicationDefault 24 | * method rather than creating your own JWT or Compute client directly. 25 | * 26 | * Note: In order to run on a local developer machine, it is necessary to download a private key 27 | * file to your machine, and to set a local environment variable pointing to the location of the 28 | * file. Create a service account using the Google Developers Console using the section APIs & Auth. 29 | * Select "Generate new JSON key" and download the resulting file. Once this is done, set the 30 | * GOOGLE_APPLICATION_CREDENTIALS environment variable to point to the location of the .json file. 31 | * 32 | * See also: 33 | * https://developers.google.com/accounts/docs/application-default-credentials 34 | */ 35 | 36 | // Get the appropriate type of credential client, depending upon the runtime environment. 37 | google.auth.getApplicationDefault((err, authClient) => { 38 | if (err) { 39 | console.error('Failed to get the default credentials.'); 40 | throw err; 41 | } 42 | // The createScopedRequired method returns true when running on GAE or a local developer 43 | // machine. In that case, the desired scopes must be passed in manually. When the code is 44 | // running in GCE or a Managed VM, the scopes are pulled from the GCE metadata server. 45 | // See https://cloud.google.com/compute/docs/authentication for more information. 46 | if (authClient.createScopedRequired && authClient.createScopedRequired()) { 47 | // Scopes can be specified either as an array or as a single, space-delimited string. 48 | authClient = authClient.createScoped(['https://www.googleapis.com/auth/compute']); 49 | } 50 | // Fetch the list of GCE zones within a project. 51 | // NOTE: You must fill in your valid project ID before running this sample! 52 | const projectId = 'fill in your project id here!'; 53 | compute.zones.list({ project: projectId, auth: authClient }, (err, res) => { 54 | if (err) { 55 | throw err; 56 | } 57 | console.log(res.data); 58 | }); 59 | }); 60 | -------------------------------------------------------------------------------- /samples/sheets/quickstart.js: -------------------------------------------------------------------------------- 1 | // Copyright 2018, Google, LLC. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | 'use strict'; 15 | 16 | // [START main_body] 17 | const {google} = require('googleapis'); 18 | const express = require('express'); 19 | const opn = require('opn'); 20 | const path = require('path'); 21 | const fs = require('fs'); 22 | 23 | const keyfile = path.join(__dirname, 'credentials.json'); 24 | const keys = JSON.parse(fs.readFileSync(keyfile)); 25 | const scopes = ['https://www.googleapis.com/auth/spreadsheets.readonly']; 26 | 27 | // Create an oAuth2 client to authorize the API call 28 | const client = new google.auth.OAuth2( 29 | keys.web.client_id, 30 | keys.web.client_secret, 31 | keys.web.redirect_uris[0] 32 | ); 33 | 34 | // Generate the url that will be used for authorization 35 | this.authorizeUrl = client.generateAuthUrl({ 36 | access_type: 'offline', 37 | scope: scopes 38 | }); 39 | 40 | // Open an http server to accept the oauth callback. In this 41 | // simple example, the only request to our webserver is to 42 | // /oauth2callback?code= 43 | const app = express(); 44 | app.get('/oauth2callback', (req, res) => { 45 | const code = req.query.code; 46 | client.getToken(code, (err, tokens) => { 47 | if (err) { 48 | console.error('Error getting oAuth tokens:'); 49 | throw err; 50 | } 51 | client.credentials = tokens; 52 | res.send('Authentication successful! Please return to the console.'); 53 | server.close(); 54 | listMajors(client); 55 | }); 56 | }); 57 | const server = app.listen(3000, () => { 58 | // open the browser to the authorize url to start the workflow 59 | opn(this.authorizeUrl, { wait: false }); 60 | }); 61 | 62 | /** 63 | * Print the names and majors of students in a sample spreadsheet: 64 | * https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit 65 | */ 66 | function listMajors (auth) { 67 | const sheets = google.sheets('v4'); 68 | sheets.spreadsheets.values.get({ 69 | auth: auth, 70 | spreadsheetId: '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms', 71 | range: 'Class Data!A2:E' 72 | }, (err, res) => { 73 | if (err) { 74 | console.error('The API returned an error.'); 75 | throw err; 76 | } 77 | const rows = res.data.values; 78 | if (rows.length === 0) { 79 | console.log('No data found.'); 80 | } else { 81 | console.log('Name, Major:'); 82 | for (const row of rows) { 83 | // Print columns A and E, which correspond to indices 0 and 4. 84 | console.log(`${row[0]}, ${row[4]}`); 85 | } 86 | } 87 | }); 88 | } 89 | // [END main_body] 90 | -------------------------------------------------------------------------------- /CONTRIBUTORS: -------------------------------------------------------------------------------- 1 | # People who have agreed to one of the CLAs and can contribute patches. The 2 | # AUTHORS file lists the copyright holders; this file lists people. For example, 3 | # Google employees are listed here but not in AUTHORS, because Google holds the 4 | # copyright. 5 | # 6 | # https://developers.google.com/open-source/cla/individual 7 | # https://developers.google.com/open-source/cla/corporate 8 | # 9 | # Names should be added to this file as: 10 | # Name 11 | Ace Nassri 12 | Adam Cohen 13 | Ali Ijaz Sheikh 14 | Anders D. Johnson 15 | Anson Chu 16 | Anthony Pigeot 17 | Ben Gourley 18 | Ben Reinhart 19 | Benton 20 | Brad Vogel 21 | Brandon Philips 22 | Bruneau 23 | Burcu Dogan 24 | Caleb Case 25 | Chris Bolin 26 | Christian Carnero 27 | Claudio Costa 28 | Daniel Wang 29 | Dave Bailey 30 | Dick Choi 31 | Eric Koleda 32 | Farid Neshat 33 | Geoffery Miller 34 | Greenkeeper 35 | Habib Rehman 36 | Hammy Havoc 37 | Ionică Bizău 38 | Ivan 39 | Jason Allor 40 | Jason Dobry 41 | Johan Euphrosine 42 | Jonathan Bergknoff 43 | Joseph Page 44 | Josh Senick 45 | Justin Beckwith 46 | Larry Maccherone 47 | Mark S. Everitt 48 | Matt Gaunt 49 | MidnightWonderer 50 | Monsur Hossain 51 | Morton Fox 52 | OnaBai 53 | Pieter Coucke 54 | Preston Holmes 55 | ReadmeCritic 56 | Rich Parrish 57 | Rob Hanlon 58 | Robert Rossmann 59 | Ryan Seys 60 | Sebastian Seilund 61 | Shay Erlichmen 62 | Stephen Wan 63 | Steven Bazyl 64 | Tamal Saha 65 | Theodore Wilson 66 | Thomas Coffee 67 | Tim Emiola 68 | Vikram Tiwari 69 | Vincent Scheib 70 | bentona 71 | ccarnero 72 | eiriksm 73 | glennschler 74 | jbergknoff 75 | proppy 76 | rakyll 77 | sebay00 78 | vladikoff 79 | -------------------------------------------------------------------------------- /src/templates/api-endpoint.njk: -------------------------------------------------------------------------------- 1 | {% import "resource-partial.njk" as resource %} 2 | {% import "method-partial.njk" as method %} 3 | {% set lb = "{" %} 4 | {% set rb = "}" %} 5 | /** 6 | * Copyright 2015 Google Inc. All Rights Reserved. 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | */ 20 | 21 | import {createAPIRequest} from '../../lib/apirequest'; 22 | import { MethodOptions, GlobalOptions, BodyResponseCallback } from '../../lib/api'; 23 | 24 | // TODO: We will eventually get the `any` in here cleared out, but in the interim we 25 | // want to turn on no-implicit-any. 26 | 27 | // tslint:disable: no-any 28 | 29 | {% set Name = api.name|capitalize %} 30 | {% if api.version %} 31 | {% set Version = api.version|replace('\.', '_')|capitalize %} 32 | {% endif %} 33 | {% set Namespace = [Name, Version]|join('') %} 34 | 35 | /** 36 | * {{ api.title }} 37 | * 38 | * {{ api.description | oneLine }} 39 | * 40 | * @example 41 | * const google = require('googleapis'); 42 | * const {{ api.name }} = google.{{ api.name }}('{{ api.version }}'); 43 | * 44 | * @namespace {{ api.name }} 45 | * @type {Function} 46 | * @version {{ api.version }} 47 | * @variation {{ api.version }} 48 | * @param {object=} options Options for {{ Name }} 49 | */ 50 | function {{ Name }} (options: GlobalOptions) { 51 | const self = this; 52 | self._options = options || {}; 53 | {% if api.methods %} 54 | {% for mname, m in api.methods|dictsort %} 55 | {{ method.render(m, mname, api, true) }} 56 | {% endfor %} 57 | {% endif %} 58 | {% if api.resources %} 59 | {% for rname, r in api.resources|dictsort %} 60 | self.{{ rname }} = { 61 | {{ resource.render(r, api, false) }} 62 | }; 63 | {% endfor %} 64 | {% endif %} 65 | } 66 | {% if api.schemas %} 67 | {% for schemaName, schema in api.schemas|dictsort %} 68 | /** 69 | * @typedef {{ schema.id | oneLine }} 70 | * @memberOf! {{ api.name }}({{ api.version }}) 71 | * @type {{ schema.type | oneLine }} 72 | {% if schema.properties %} 73 | {% for pname, p in schema.properties|dictsort %} 74 | {% if p.$ref %} 75 | * @property {{ lb }}{{ api.name }}({{ api.version }}).{{ p.$ref }}{{ rb }} {{ pname }} {{ p.description | cleanPaths | oneLine }} 76 | {% elif p.items and p.items.type %} 77 | * @property {{ lb }}{{ p.items.type }}[]{{ rb }} {{ pname }} {{ p.description | cleanPaths | oneLine }} 78 | {% elif p.items and p.items.$ref %} 79 | * @property {{ lb }}{{ api.name }}({{ api.version }}).{{ p.items.$ref }}[]{{ rb }} {{ pname }} {{ p.description | cleanPaths | oneLine }} 80 | {% else %} 81 | * @property {{ lb }}{{ p.type }}{{ rb }} {{ pname }} {{ p.description | cleanPaths | oneLine }} 82 | {% endif %} 83 | {% endfor %} 84 | {% endif %} 85 | */ 86 | {% endfor %} 87 | {% endif %} 88 | 89 | export = {{ Name }}; 90 | -------------------------------------------------------------------------------- /src/lib/schema.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018, Google, LLC. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | /** 15 | * These are a collection of interfaces that represent the GoogleApis 16 | * Discovery json formats. 17 | */ 18 | 19 | export interface Schemas { 20 | discoveryVersion: string; 21 | kind: string; 22 | items: Schema[]; 23 | } 24 | 25 | export interface Schema { 26 | auth: {oauth2: {scopes: {[index: string]: {description: string;}}}}; 27 | basePath: string; 28 | baseUrl: string; 29 | batchPath: string; 30 | description: string; 31 | discoveryVersion: string; 32 | discoveryRestUrl: string; 33 | documentationLink: string; 34 | etag: string; 35 | icons: {x16: string, x32: string}; 36 | id: string; 37 | kind: string; 38 | methods: SchemaMethods; 39 | name: string; 40 | ownerDomain: string; 41 | ownerName: string; 42 | parameters: SchemaParameters; 43 | protocol: string; 44 | resources: SchemaResources; 45 | revision: string; 46 | rootUrl: string; 47 | schemas: SchemaItems; 48 | servicePath: string; 49 | title: string; 50 | version: string; 51 | } 52 | 53 | export interface SchemaResources { [index: string]: SchemaResource; } 54 | 55 | export interface SchemaResource { 56 | methods?: SchemaMethods; 57 | resources?: SchemaResources; 58 | } 59 | 60 | export interface SchemaItems { [index: string]: SchemaItem; } 61 | 62 | export interface SchemaItem { 63 | description?: string; 64 | default?: string; 65 | id?: string; 66 | properties?: {[index: string]: SchemaItem}; 67 | items?: {[index: string]: SchemaItem}; 68 | type?: SchemaType; 69 | format?: ParameterFormat; 70 | $ref?: string; 71 | } 72 | 73 | export interface SchemaParameters { [index: string]: SchemaParameter; } 74 | 75 | export interface SchemaParameter { 76 | default: string; 77 | description: string; 78 | location: string; 79 | enum: string[]; 80 | enumDescription: string[]; 81 | type: SchemaType; 82 | format: ParameterFormat; 83 | required: boolean; 84 | } 85 | 86 | export interface SchemaMethods { [index: string]: SchemaMethod; } 87 | 88 | export interface SchemaMethod { 89 | description: string; 90 | httpMethod: HttpMethod; 91 | id: string; 92 | parameterOrder?: string[]; 93 | parameters?: {[index: string]: SchemaParameter}; 94 | path: string; 95 | request: {$ref: string;}; 96 | response: {$ref: string;}; 97 | sampleUrl: string; 98 | scopes: string[]; 99 | fragment: string; 100 | mediaUpload: {protocols: {simple: {path: string;};};}; 101 | } 102 | 103 | export interface FragmentResponse { 104 | codeFragment: {[index: string]: {fragment: string;}}; 105 | } 106 | 107 | export type ParameterFormat = 'int32'; 108 | export type HttpMethod = 'GET'|'PATCH'|'PUT'; 109 | export type SchemaType = 'object'|'integer'|'string'|'array'|'boolean'; 110 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "nyc": { 3 | "exclude": [ 4 | "build/src/apis", 5 | "build/test", 6 | "samples" 7 | ] 8 | }, 9 | "license": "Apache-2.0", 10 | "dependencies": { 11 | "google-auth-library": "^1.3.1", 12 | "pify": "^3.0.0", 13 | "qs": "^6.5.1", 14 | "string-template": "1.0.0", 15 | "uuid": "^3.2.1" 16 | }, 17 | "files": [ 18 | "LICENSE", 19 | "README.md", 20 | "build/src", 21 | "package.json" 22 | ], 23 | "semistandard": { 24 | "ignore": [ 25 | "apis", 26 | "templates/*" 27 | ], 28 | "globals": [ 29 | "after", 30 | "afterEach", 31 | "before", 32 | "beforeEach", 33 | "describe", 34 | "it" 35 | ] 36 | }, 37 | "repository": { 38 | "url": "https://github.com/google/google-api-nodejs-client.git", 39 | "type": "git" 40 | }, 41 | "name": "googleapis", 42 | "contributors": [ 43 | { 44 | "email": "jbd@google.com", 45 | "name": "Burcu Dogan" 46 | }, 47 | { 48 | "email": "jasonall@google.com", 49 | "name": "Jason Allor" 50 | }, 51 | { 52 | "email": "jason.dobry@gmail.com", 53 | "name": "Jason Dobry" 54 | }, 55 | { 56 | "email": "ryanseys@google.com", 57 | "name": "Ryan Seys" 58 | }, 59 | { 60 | "email": "tbetbetbe@google.com", 61 | "name": "Tim Emiola" 62 | }, 63 | { 64 | "email": "beckwith@google.com", 65 | "name": "Justin Beckwith" 66 | }, 67 | { 68 | "email": "fenster@google.com", 69 | "name": "Alexander Fenster" 70 | } 71 | ], 72 | "version": "27.0.0", 73 | "scripts": { 74 | "test": "make test -j 4" 75 | }, 76 | "author": "Google Inc.", 77 | "keywords": [ 78 | "google", 79 | "api", 80 | "google apis", 81 | "client", 82 | "client library" 83 | ], 84 | "description": "Google APIs Client Library for Node.js", 85 | "main": "./build/src/index.js", 86 | "types": "./build/src/index.d.ts", 87 | "engines": { 88 | "node": ">=4.0" 89 | }, 90 | "devDependencies": { 91 | "@types/express": "^4.11.1", 92 | "@types/minimist": "1.2.0", 93 | "@types/mkdirp": "0.5.2", 94 | "@types/mocha": "2.2.48", 95 | "@types/mv": "^2.1.0", 96 | "@types/ncp": "^2.0.1", 97 | "@types/nock": "^9.1.2", 98 | "@types/node": "9.4.7", 99 | "@types/nunjucks": "^3.0.0", 100 | "@types/p-queue": "^2.3.1", 101 | "@types/pify": "^3.0.0", 102 | "@types/qs": "^6.5.1", 103 | "@types/rimraf": "^2.0.2", 104 | "@types/source-map-support": "^0.4.0", 105 | "@types/string-template": "^1.0.2", 106 | "@types/tmp": "0.0.33", 107 | "@types/uuid": "^3.4.3", 108 | "axios": "^0.18.0", 109 | "clang-format": "^1.2.2", 110 | "codecov": "^3.0.0", 111 | "express": "^4.16.2", 112 | "gts": "0.5.4", 113 | "ink-docstrap": "1.3.2", 114 | "intelli-espower-loader": "1.0.1", 115 | "js-green-licenses": "^0.5.0", 116 | "jsdoc": "3.5.5", 117 | "minimist": "1.2.0", 118 | "mkdirp": "0.5.1", 119 | "mocha": "5.0.4", 120 | "mv": "^2.1.1", 121 | "nconf": "^0.10.0", 122 | "ncp": "^2.0.0", 123 | "nock": "9.2.2", 124 | "nunjucks": "^3.1.0", 125 | "nyc": "11.6.0", 126 | "opn": "5.2.0", 127 | "p-queue": "^2.3.0", 128 | "rimraf": "2.6.2", 129 | "semistandard": "12.0.1", 130 | "server-destroy": "^1.0.1", 131 | "source-map-support": "0.5.3", 132 | "tmp": "0.0.33", 133 | "typescript": "2.7.2" 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /src/apis/groupsmigration/v1.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2015 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import {BodyResponseCallback, GlobalOptions, MethodOptions} from '../../lib/api'; 18 | import {createAPIRequest} from '../../lib/apirequest'; 19 | 20 | // TODO: We will eventually get the `any` in here cleared out, but in the 21 | // interim we want to turn on no-implicit-any. 22 | 23 | // tslint:disable: no-any 24 | 25 | 26 | /** 27 | * Groups Migration API 28 | * 29 | * Groups Migration Api. 30 | * 31 | * @example 32 | * const google = require('googleapis'); 33 | * const groupsmigration = google.groupsmigration('v1'); 34 | * 35 | * @namespace groupsmigration 36 | * @type {Function} 37 | * @version v1 38 | * @variation v1 39 | * @param {object=} options Options for Groupsmigration 40 | */ 41 | function Groupsmigration(options: GlobalOptions) { 42 | const self = this; 43 | self._options = options || {}; 44 | self.archive = { 45 | /** 46 | * groupsmigration.archive.insert 47 | * @desc Inserts a new mail into the archive of the Google group. 48 | * @alias groupsmigration.archive.insert 49 | * @memberOf! groupsmigration(v1) 50 | * 51 | * @param {object} params Parameters for request 52 | * @param {string} params.groupId The group ID 53 | * @param {object} params.media Media object 54 | * @param {string} params.media.mimeType Media mime-type 55 | * @param {string|object} params.media.body Media body contents 56 | * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. 57 | * @param {callback} callback The callback that handles the response. 58 | * @return {object} Request object 59 | */ 60 | insert( 61 | params: any, options: MethodOptions|BodyResponseCallback, 62 | callback?: BodyResponseCallback) { 63 | if (typeof options === 'function') { 64 | callback = options; 65 | options = {}; 66 | } 67 | options = options || {}; 68 | const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; 69 | const parameters = { 70 | options: Object.assign( 71 | { 72 | url: (rootUrl + '/groups/v1/groups/{groupId}/archive') 73 | .replace(/([^:]\/)\/+/g, '$1'), 74 | method: 'POST' 75 | }, 76 | options), 77 | params, 78 | mediaUrl: (rootUrl + '/upload/groups/v1/groups/{groupId}/archive') 79 | .replace(/([^:]\/)\/+/g, '$1'), 80 | requiredParams: ['groupId'], 81 | pathParams: ['groupId'], 82 | context: self 83 | }; 84 | return createAPIRequest(parameters, callback!); 85 | } 86 | 87 | }; 88 | } 89 | /** 90 | * @typedef Groups 91 | * @memberOf! groupsmigration(v1) 92 | * @type object 93 | * @property {string} kind The kind of insert resource this is. 94 | * @property {string} responseCode The status of the insert request. 95 | */ 96 | 97 | export = Groupsmigration; 98 | -------------------------------------------------------------------------------- /test/test.urlshortener.v1.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2013-2016, Google, Inc. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | import * as assert from 'assert'; 15 | import * as nock from 'nock'; 16 | import * as path from 'path'; 17 | import * as pify from 'pify'; 18 | import * as url from 'url'; 19 | 20 | import {GoogleApis} from '../src'; 21 | import {APIEndpoint} from '../src/lib/api'; 22 | 23 | import {Utils} from './utils'; 24 | 25 | async function testSingleRequest(urlshortener: APIEndpoint) { 26 | const obj = {longUrl: 'http://someurl...'}; 27 | const reqPath = '/urlshortener/v1/url?longUrl=http%3A%2F%2Fsomeurl...'; 28 | nock(Utils.baseUrl).post(reqPath).reply(200); 29 | const res = await pify(urlshortener.url.insert)(obj); 30 | assert.equal(Utils.getQs(res), 'longUrl=http%3A%2F%2Fsomeurl...'); 31 | assert.equal(res.config.method.toLowerCase(), 'post'); 32 | } 33 | 34 | async function testParams(urlshortener: APIEndpoint) { 35 | const params = {shortUrl: 'a'}; 36 | nock(Utils.baseUrl).get('/urlshortener/v1/url?shortUrl=a').reply(200); 37 | const res = await pify(urlshortener.url.get)(params); 38 | assert.equal(Utils.getQs(res), 'shortUrl=a'); 39 | assert.equal(res.config.method.toLowerCase(), 'get'); 40 | } 41 | 42 | async function testInsert(urlshortener: APIEndpoint) { 43 | const obj = {longUrl: 'http://google.com/'}; 44 | nock(Utils.baseUrl).post('/resource').reply(200); 45 | const res = await pify(urlshortener.url.insert)({resource: obj}); 46 | assert.notEqual(res.data, null); 47 | assert.notEqual(res.data.kind, null); 48 | assert.notEqual(res.data.id, null); 49 | assert.equal(res.data.longUrl, 'http://google.com/'); 50 | return res; 51 | } 52 | 53 | describe('Urlshortener', () => { 54 | let localUrlshortener: APIEndpoint; 55 | let remoteUrlshortener: APIEndpoint; 56 | 57 | before(async () => { 58 | nock.cleanAll(); 59 | const google = new GoogleApis(); 60 | nock.enableNetConnect(); 61 | remoteUrlshortener = await Utils.loadApi(google, 'urlshortener', 'v1'); 62 | nock.disableNetConnect(); 63 | }); 64 | 65 | beforeEach(() => { 66 | nock.cleanAll(); 67 | nock.disableNetConnect(); 68 | const google = new GoogleApis(); 69 | localUrlshortener = google.urlshortener('v1'); 70 | }); 71 | 72 | it('should generate a valid payload for single requests', async () => { 73 | await testSingleRequest(localUrlshortener); 74 | await testSingleRequest(remoteUrlshortener); 75 | }); 76 | 77 | it('should generate valid payload if any params are given', async () => { 78 | await testParams(localUrlshortener); 79 | await testParams(remoteUrlshortener); 80 | }); 81 | 82 | it('should return a single response object for single requests', async () => { 83 | nock(Utils.baseUrl, {allowUnmocked: true}) 84 | .post('/urlshortener/v1/url') 85 | .times(2) 86 | .replyWithFile( 87 | 200, 88 | path.join( 89 | __dirname, '../../test/fixtures/urlshort-insert-res.json')); 90 | await testInsert(localUrlshortener); 91 | await testInsert(remoteUrlshortener); 92 | }); 93 | 94 | after(() => { 95 | nock.cleanAll(); 96 | nock.enableNetConnect(); 97 | }); 98 | }); 99 | -------------------------------------------------------------------------------- /src/lib/api.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018, Google, LLC. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | import {AxiosAdapter, AxiosProxyConfig, AxiosRequestConfig, AxiosResponse, AxiosTransformer, CancelToken} from 'axios'; 15 | import {OAuth2Client} from 'google-auth-library/build/src/auth/oauth2client'; 16 | import {OutgoingHttpHeaders} from 'http'; 17 | import * as stream from 'stream'; 18 | 19 | import {Endpoint} from './endpoint'; 20 | import {SchemaParameters} from './schema'; 21 | 22 | export interface APIRequestParams { 23 | options: AxiosRequestConfig; 24 | params: APIRequestMethodParams; 25 | requiredParams: string[]; 26 | pathParams: string[]; 27 | context: APIRequestContext; 28 | mediaUrl?: string|null; 29 | } 30 | 31 | export interface APIRequestContext { 32 | google: {_options: GlobalOptions;}; 33 | _options: GlobalOptions; 34 | } 35 | 36 | /** 37 | * This interface is a mix of the AxiosRequestConfig options 38 | * and our `auth: OAuth2Client|string` options. We need to redefine 39 | * the interface here because the `auth` property already exists 40 | * on AxiosRequestConfig, and uses an entirely different type. 41 | */ 42 | export interface GlobalOptions { 43 | url?: string; 44 | method?: string; 45 | baseURL?: string; 46 | transformRequest?: AxiosTransformer|AxiosTransformer[]; 47 | transformResponse?: AxiosTransformer|AxiosTransformer[]; 48 | // tslint:disable-next-line no-any 49 | headers?: any; 50 | // tslint:disable-next-line no-any 51 | params?: any; 52 | // tslint:disable-next-line no-any 53 | paramsSerializer?: (params: any) => string; 54 | // tslint:disable-next-line no-any 55 | data?: any; 56 | timeout?: number; 57 | withCredentials?: boolean; 58 | adapter?: AxiosAdapter; 59 | auth?: OAuth2Client|string; 60 | responseType?: string; 61 | xsrfCookieName?: string; 62 | xsrfHeaderName?: string; 63 | // tslint:disable-next-line no-any 64 | onUploadProgress?: (progressEvent: any) => void; 65 | // tslint:disable-next-line no-any 66 | onDownloadProgress?: (progressEvent: any) => void; 67 | maxContentLength?: number; 68 | validateStatus?: (status: number) => boolean; 69 | maxRedirects?: number; 70 | // tslint:disable-next-line no-any 71 | httpAgent?: any; 72 | // tslint:disable-next-line no-any 73 | httpsAgent?: any; 74 | proxy?: AxiosProxyConfig|false; 75 | cancelToken?: CancelToken; 76 | } 77 | 78 | export interface MethodOptions extends AxiosRequestConfig { rootUrl?: string; } 79 | export interface ServiceOptions extends GlobalOptions { version?: string; } 80 | 81 | export interface APIList { 82 | // tslint:disable-next-line no-any 83 | [index: string]: {[index: string]: any}; 84 | } 85 | 86 | export type BodyResponseCallback = 87 | (err: Error|null, res?: AxiosResponse|null) => void; 88 | 89 | export interface APIRequestMethodParams { 90 | // tslint:disable-next-line: no-any 91 | [index: string]: any; 92 | url?: string; 93 | media?: {body?: string|stream.Readable; mimeType?: string;}; 94 | resource?: {mimeType?: string;}; 95 | key?: string; 96 | uploadType?: string; 97 | auth?: OAuth2Client|string; 98 | headers?: OutgoingHttpHeaders; 99 | } 100 | 101 | // tslint:disable-next-line: no-any 102 | export type APIEndpoint = Readonly; 103 | -------------------------------------------------------------------------------- /src/apis/playcustomapp/v1.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2015 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import {BodyResponseCallback, GlobalOptions, MethodOptions} from '../../lib/api'; 18 | import {createAPIRequest} from '../../lib/apirequest'; 19 | 20 | // TODO: We will eventually get the `any` in here cleared out, but in the 21 | // interim we want to turn on no-implicit-any. 22 | 23 | // tslint:disable: no-any 24 | 25 | 26 | /** 27 | * Google Play Custom App Publishing API 28 | * 29 | * An API to publish custom Android apps. 30 | * 31 | * @example 32 | * const google = require('googleapis'); 33 | * const playcustomapp = google.playcustomapp('v1'); 34 | * 35 | * @namespace playcustomapp 36 | * @type {Function} 37 | * @version v1 38 | * @variation v1 39 | * @param {object=} options Options for Playcustomapp 40 | */ 41 | function Playcustomapp(options: GlobalOptions) { 42 | const self = this; 43 | self._options = options || {}; 44 | self.accounts = { 45 | customApps: { 46 | /** 47 | * playcustomapp.accounts.customApps.create 48 | * @desc Create and publish a new custom app. 49 | * @alias playcustomapp.accounts.customApps.create 50 | * @memberOf! playcustomapp(v1) 51 | * 52 | * @param {object} params Parameters for request 53 | * @param {string} params.account Developer account ID. 54 | * @param {object} params.resource Media resource metadata 55 | * @param {object} params.media Media object 56 | * @param {string} params.media.mimeType Media mime-type 57 | * @param {string|object} params.media.body Media body contents 58 | * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. 59 | * @param {callback} callback The callback that handles the response. 60 | * @return {object} Request object 61 | */ 62 | create( 63 | params: any, options: MethodOptions|BodyResponseCallback, 64 | callback?: BodyResponseCallback) { 65 | if (typeof options === 'function') { 66 | callback = options; 67 | options = {}; 68 | } 69 | options = options || {}; 70 | const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; 71 | const parameters = { 72 | options: Object.assign( 73 | { 74 | url: (rootUrl + 75 | '/playcustomapp/v1/accounts/{account}/customApps') 76 | .replace(/([^:]\/)\/+/g, '$1'), 77 | method: 'POST' 78 | }, 79 | options), 80 | params, 81 | mediaUrl: (rootUrl + 82 | '/upload/playcustomapp/v1/accounts/{account}/customApps') 83 | .replace(/([^:]\/)\/+/g, '$1'), 84 | requiredParams: ['account'], 85 | pathParams: ['account'], 86 | context: self 87 | }; 88 | return createAPIRequest(parameters, callback!); 89 | } 90 | 91 | } 92 | }; 93 | } 94 | /** 95 | * @typedef CustomApp 96 | * @memberOf! playcustomapp(v1) 97 | * @type object 98 | * @property {string} languageCode Default listing language in BCP 47 format. 99 | * @property {string} title Title for the Android app. 100 | */ 101 | 102 | export = Playcustomapp; 103 | -------------------------------------------------------------------------------- /test/test.apikey.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2014-2016, Google, Inc. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | import * as assert from 'assert'; 15 | import {OAuth2Client} from 'google-auth-library'; 16 | import * as nock from 'nock'; 17 | import * as pify from 'pify'; 18 | 19 | import {GoogleApis} from '../src'; 20 | import {google} from '../src'; 21 | import {APIEndpoint} from '../src/lib/api'; 22 | 23 | import {Utils} from './utils'; 24 | 25 | async function testGet(drive: APIEndpoint) { 26 | nock(Utils.baseUrl).get('/drive/v2/files/123?key=APIKEY').reply(200); 27 | const res = await pify(drive.files.get)({fileId: '123', auth: 'APIKEY'}); 28 | assert.equal(Utils.getQs(res), 'key=APIKEY'); 29 | } 30 | 31 | async function testParams2(drive: APIEndpoint) { 32 | nock(Utils.baseUrl).get('/drive/v2/files/123?key=API%20KEY').reply(200); 33 | const res = await pify(drive.files.get)({fileId: '123', auth: 'API KEY'}); 34 | assert.equal(Utils.getQs(res), 'key=API%20KEY'); 35 | } 36 | 37 | async function testKeyParam(drive: APIEndpoint) { 38 | nock(Utils.baseUrl).get('/drive/v2/files/123?key=abc123').reply(200); 39 | const res = await pify(drive.files.get)( 40 | {fileId: '123', auth: 'API KEY', key: 'abc123'}); 41 | assert.equal(Utils.getQs(res), 'key=abc123'); 42 | } 43 | 44 | async function testAuthKey(urlshortener: APIEndpoint) { 45 | nock(Utils.baseUrl) 46 | .get('/urlshortener/v1/url/history?key=YOUR%20API%20KEY') 47 | .reply(200); 48 | const res = await pify(urlshortener.url.list)({auth: 'YOUR API KEY'}); 49 | assert.equal(Utils.getQs(res)!.indexOf('key=YOUR%20API%20KEY') > -1, true); 50 | } 51 | 52 | describe('API key', () => { 53 | let localDrive: APIEndpoint; 54 | let remoteDrive: APIEndpoint; 55 | let localUrlshortener: APIEndpoint; 56 | let remoteUrlshortener: APIEndpoint; 57 | let authClient: OAuth2Client; 58 | 59 | before(async () => { 60 | nock.cleanAll(); 61 | const google = new GoogleApis(); 62 | nock.enableNetConnect(); 63 | [remoteDrive, remoteUrlshortener] = await Promise.all([ 64 | Utils.loadApi(google, 'drive', 'v2'), 65 | Utils.loadApi(google, 'urlshortener', 'v1') 66 | ]); 67 | nock.disableNetConnect(); 68 | }); 69 | 70 | beforeEach(() => { 71 | nock.cleanAll(); 72 | nock.disableNetConnect(); 73 | const google = new GoogleApis(); 74 | const OAuth2 = google.auth.OAuth2; 75 | authClient = new OAuth2('CLIENT_ID', 'CLIENT_SECRET', 'REDIRECT_URL'); 76 | authClient.credentials = {access_token: 'abc123'}; 77 | localDrive = google.drive('v2'); 78 | localUrlshortener = google.urlshortener('v1'); 79 | }); 80 | 81 | it('should include auth APIKEY as key=', async () => { 82 | await testGet(localDrive); 83 | await testGet(remoteDrive); 84 | }); 85 | 86 | it('should properly escape params E.g. API KEY to API%20KEY', async () => { 87 | await testParams2(localDrive); 88 | await testParams2(remoteDrive); 89 | }); 90 | 91 | it('should use key param over auth apikey param if both provided', 92 | async () => { 93 | await testKeyParam(localDrive); 94 | await testKeyParam(remoteDrive); 95 | }); 96 | 97 | it('should set API key parameter if it is present', async () => { 98 | await testAuthKey(localUrlshortener); 99 | await testAuthKey(remoteUrlshortener); 100 | }); 101 | 102 | after(() => { 103 | nock.cleanAll(); 104 | nock.enableNetConnect(); 105 | }); 106 | }); 107 | -------------------------------------------------------------------------------- /src/apis/webfonts/v1.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2015 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import {BodyResponseCallback, GlobalOptions, MethodOptions} from '../../lib/api'; 18 | import {createAPIRequest} from '../../lib/apirequest'; 19 | 20 | // TODO: We will eventually get the `any` in here cleared out, but in the 21 | // interim we want to turn on no-implicit-any. 22 | 23 | // tslint:disable: no-any 24 | 25 | 26 | /** 27 | * Google Fonts Developer API 28 | * 29 | * Accesses the metadata for all families served by Google Fonts, providing a 30 | * list of families currently available (including available styles and a list 31 | * of supported script subsets). 32 | * 33 | * @example 34 | * const google = require('googleapis'); 35 | * const webfonts = google.webfonts('v1'); 36 | * 37 | * @namespace webfonts 38 | * @type {Function} 39 | * @version v1 40 | * @variation v1 41 | * @param {object=} options Options for Webfonts 42 | */ 43 | function Webfonts(options: GlobalOptions) { 44 | const self = this; 45 | self._options = options || {}; 46 | self.webfonts = { 47 | /** 48 | * webfonts.webfonts.list 49 | * @desc Retrieves the list of fonts currently served by the Google Fonts 50 | * Developer API 51 | * @alias webfonts.webfonts.list 52 | * @memberOf! webfonts(v1) 53 | * 54 | * @param {object=} params Parameters for request 55 | * @param {string=} params.sort Enables sorting of the list 56 | * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. 57 | * @param {callback} callback The callback that handles the response. 58 | * @return {object} Request object 59 | */ 60 | list( 61 | params: any, options: MethodOptions|BodyResponseCallback, 62 | callback?: BodyResponseCallback) { 63 | if (typeof options === 'function') { 64 | callback = options; 65 | options = {}; 66 | } 67 | options = options || {}; 68 | const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; 69 | const parameters = { 70 | options: Object.assign( 71 | { 72 | url: (rootUrl + '/webfonts/v1/webfonts') 73 | .replace(/([^:]\/)\/+/g, '$1'), 74 | method: 'GET' 75 | }, 76 | options), 77 | params, 78 | requiredParams: [], 79 | pathParams: [], 80 | context: self 81 | }; 82 | return createAPIRequest(parameters, callback!); 83 | } 84 | 85 | }; 86 | } 87 | /** 88 | * @typedef Webfont 89 | * @memberOf! webfonts(v1) 90 | * @type object 91 | * @property {string} category The category of the font. 92 | * @property {string} family The name of the font. 93 | * @property {object} files The font files (with all supported scripts) for each one of the available variants, as a key : value map. 94 | * @property {string} kind This kind represents a webfont object in the webfonts service. 95 | * @property {string} lastModified The date (format "yyyy-MM-dd") the font was modified for the last time. 96 | * @property {string[]} subsets The scripts supported by the font. 97 | * @property {string[]} variants The available variants for the font. 98 | * @property {string} version The font version. 99 | */ 100 | /** 101 | * @typedef WebfontList 102 | * @memberOf! webfonts(v1) 103 | * @type object 104 | * @property {webfonts(v1).Webfont[]} items The list of fonts currently served by the Google Fonts API. 105 | * @property {string} kind This kind represents a list of webfont objects in the webfonts service. 106 | */ 107 | 108 | export = Webfonts; 109 | -------------------------------------------------------------------------------- /samples/README.md: -------------------------------------------------------------------------------- 1 | # Samples by API 2 | The following samples show basic usage of various APIs. Throughout these samples, you will find code that relies on various authentication methods. 3 | - **OAuth2** - To use the OAuth2 samples, create a credential in the cloud developer console, and save the file as `oauth2.keys.json` in the samples directory. 4 | - **Service account** - To use the service account based samples, create a new service account in the cloud developer console, and save the file as `jwt.keys.json` in the samples directory. 5 | - **API Key** - To use simple API keys, create a new API Key in the cloud developer console, then store the key in the `api_key` field of `config.json`. 6 | 7 | 8 | ## ![](http://www.google.com/images/icons/product/analytics-32.png) Google Analytics API 9 | 10 | View and manage your Google Analytics data. 11 | 12 | Documentation for the Google Analytics API in 13 | [JSDoc](http://google.github.io/google-api-nodejs-client/2.1.7/analytics.html). 14 | 15 | 16 | 17 | 18 | 19 | 20 |
samples/analyticsCommand-line samples for producing reports with the Analytics API
21 | 22 | ## ![](http://www.google.com/images/icons/product/blogger-32.png) Blogger API 23 | 24 | View and manage Blogger data. 25 | 26 | Documentation for the Blogger API in 27 | [JSDoc](http://google.github.io/google-api-nodejs-client/2.1.7/blogger.html). 28 | 29 | 30 | 31 | 32 | 33 | 34 |
samples/bloggerCommand-line samples for reading data with the Blogger API
35 | 36 | ## ![](https://www.google.com/images/icons/product/compute_engine-32.png) Google Compute Engine Metadata API 37 | 38 | Lets you set key/value pairs using the GCE metadata service. 39 | 40 | Documentation for the Google Compute Engine Metadata API in 41 | [JSDoc](http://google.github.io/google-api-nodejs-client/2.1.7/compute.html). 42 | 43 | 44 | 45 | 46 | 47 | 48 |
samples/computeDemonstrates how to use the Google Compute Engine Metadata API
49 | 50 | ## ![](http://www.google.com/images/icons/product/customsearch-32.png) CustomSearch API 51 | 52 | Lets you search over a website or collection of websites. 53 | 54 | Documentation for the CustomSearch API in 55 | [JSDoc](http://google.github.io/google-api-nodejs-client/2.1.7/customsearch.html). 56 | 57 | 58 | 59 | 60 | 61 | 62 |
samples/customsearchSearch from the command-line
63 | 64 | 65 | ## ![](http://www.google.com/images/icons/product/search-32.png) Glass Mirror API 66 | 67 | The Google Mirror API allows you to build web-based services that interact with Google Glass. It provides this functionality over a cloud-based API and does not require running code on Glass. 68 | 69 | Documentation for the Glass Mirror API in 70 | [JSDoc](http://google.github.io/google-api-nodejs-client/2.1.7/mirror.html). 71 | 72 | 73 | 74 | 75 | 76 | 77 |
samples/mirrorObtains a list of locations from glass data
78 | 79 | ## ![](http://www.google.com/images/icons/product/shortlinks-32.png) URL Shortener API 80 | 81 | Lets you create, inspect, and manage `goo.gl` short URLs. 82 | 83 | Documentation for the URL Shortener API in 84 | [JSDoc](http://google.github.io/google-api-nodejs-client/2.1.7/urlshortener.html). 85 | 86 | 87 | 88 | 89 | 90 | 91 |
samples/urlshortenerShortens a URL with the URL Shortener API
92 | 93 | 94 | ## ![](http://www.google.com/images/icons/product/youtube-32.png) YouTube API 95 | 96 | With the YouTube Data API, you can add a variety of YouTube features to your application. Use the API to upload videos, manage playlists and subscriptions, update channel settings, and more. 97 | 98 | Documentation for the YouTube Data API in 99 | [JSDoc](http://google.github.io/google-api-nodejs-client/2.1.7/youtube.html). 100 | 101 | 102 | 103 | 104 | 105 | 106 |
samples/youtubeSamples for working with playlists, search and videos.
107 | -------------------------------------------------------------------------------- /src/apis/kgsearch/v1.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2015 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import {BodyResponseCallback, GlobalOptions, MethodOptions} from '../../lib/api'; 18 | import {createAPIRequest} from '../../lib/apirequest'; 19 | 20 | // TODO: We will eventually get the `any` in here cleared out, but in the 21 | // interim we want to turn on no-implicit-any. 22 | 23 | // tslint:disable: no-any 24 | 25 | 26 | /** 27 | * Knowledge Graph Search API 28 | * 29 | * Searches the Google Knowledge Graph for entities. 30 | * 31 | * @example 32 | * const google = require('googleapis'); 33 | * const kgsearch = google.kgsearch('v1'); 34 | * 35 | * @namespace kgsearch 36 | * @type {Function} 37 | * @version v1 38 | * @variation v1 39 | * @param {object=} options Options for Kgsearch 40 | */ 41 | function Kgsearch(options: GlobalOptions) { 42 | const self = this; 43 | self._options = options || {}; 44 | self.entities = { 45 | /** 46 | * kgsearch.entities.search 47 | * @desc Searches Knowledge Graph for entities that match the constraints. A 48 | * list of matched entities will be returned in response, which will be in 49 | * JSON-LD format and compatible with http://schema.org 50 | * @alias kgsearch.entities.search 51 | * @memberOf! kgsearch(v1) 52 | * 53 | * @param {object} params Parameters for request 54 | * @param {string=} params.ids The list of entity id to be used for search instead of query string. To specify multiple ids in the HTTP request, repeat the parameter in the URL as in ...?ids=A&ids=B 55 | * @param {boolean=} params.indent Enables indenting of json results. 56 | * @param {string=} params.languages The list of language codes (defined in ISO 693) to run the query with, e.g. 'en'. 57 | * @param {integer=} params.limit Limits the number of entities to be returned. 58 | * @param {boolean=} params.prefix Enables prefix match against names and aliases of entities 59 | * @param {string=} params.query The literal query string for search. 60 | * @param {string=} params.types Restricts returned entities with these types, e.g. Person (as defined in http://schema.org/Person). If multiple types are specified, returned entities will contain one or more of these types. 61 | * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. 62 | * @param {callback} callback The callback that handles the response. 63 | * @return {object} Request object 64 | */ 65 | search( 66 | params: any, options: MethodOptions|BodyResponseCallback, 67 | callback?: BodyResponseCallback) { 68 | if (typeof options === 'function') { 69 | callback = options; 70 | options = {}; 71 | } 72 | options = options || {}; 73 | const rootUrl = options.rootUrl || 'https://kgsearch.googleapis.com/'; 74 | const parameters = { 75 | options: Object.assign( 76 | { 77 | url: (rootUrl + '/v1/entities:search') 78 | .replace(/([^:]\/)\/+/g, '$1'), 79 | method: 'GET' 80 | }, 81 | options), 82 | params, 83 | requiredParams: [], 84 | pathParams: [], 85 | context: self 86 | }; 87 | return createAPIRequest(parameters, callback!); 88 | } 89 | 90 | }; 91 | } 92 | /** 93 | * @typedef SearchResponse 94 | * @memberOf! kgsearch(v1) 95 | * @type object 96 | * @property {any} @context The local context applicable for the response. See more details at http://www.w3.org/TR/json-ld/#context-definitions. 97 | * @property {any} @type The schema type of top-level JSON-LD object, e.g. ItemList. 98 | * @property {any[]} itemListElement The item list of search results. 99 | */ 100 | 101 | export = Kgsearch; 102 | -------------------------------------------------------------------------------- /src/lib/googleapis.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2012-2016, Google, Inc. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | import {Compute, GoogleAuth, JWT, OAuth2Client} from 'google-auth-library'; 15 | 16 | import * as apis from './../apis'; 17 | import {APIEndpoint, GlobalOptions} from './api'; 18 | import {Discovery} from './discovery'; 19 | import {Endpoint} from './endpoint'; 20 | 21 | export class AuthPlus extends GoogleAuth { 22 | // tslint:disable-next-line: variable-name 23 | JWT = JWT; 24 | // tslint:disable-next-line: variable-name 25 | Compute = Compute; 26 | // tslint:disable-next-line: variable-name 27 | OAuth2 = OAuth2Client; 28 | } 29 | 30 | export class GoogleApis extends apis.GeneratedAPIs { 31 | private _discovery = new Discovery({debug: false, includePrivate: false}); 32 | auth = new AuthPlus(); 33 | _options: GlobalOptions = {}; 34 | [index: string]: APIEndpoint; 35 | 36 | /** 37 | * GoogleApis constructor. 38 | * 39 | * @example 40 | * const GoogleApis = require('googleapis').GoogleApis; 41 | * const google = new GoogleApis(); 42 | * 43 | * @class GoogleApis 44 | * @param {Object} [options] Configuration options. 45 | */ 46 | constructor(options?: GlobalOptions) { 47 | super(); 48 | this.options(options); 49 | // tslint:disable-next-line: no-any 50 | this.addAPIs(apis as any); 51 | } 52 | 53 | /** 54 | * Set options. 55 | * 56 | * @param {Object} [options] Configuration options. 57 | */ 58 | options(options?: GlobalOptions) { 59 | this._options = options || {}; 60 | } 61 | 62 | /** 63 | * Add APIs endpoints to googleapis object 64 | * E.g. googleapis.drive and googleapis.datastore 65 | * 66 | * @name GoogleApis#addAPIs 67 | * @method 68 | * @param {Object} apis Apis to be added to this GoogleApis instance. 69 | * @private 70 | */ 71 | private addAPIs(apisToAdd: apis.GeneratedAPIs) { 72 | for (const apiName in apisToAdd) { 73 | if (apisToAdd.hasOwnProperty(apiName)) { 74 | // tslint:disable-next-line: no-any 75 | this[apiName] = (apisToAdd as any)[apiName].bind(this); 76 | } 77 | } 78 | } 79 | 80 | /** 81 | * Dynamically generate an apis object that can provide Endpoint objects for 82 | * the discovered APIs. 83 | * 84 | * @example 85 | * const {google} = require('googleapis'); 86 | * const discoveryUrl = 87 | * 'https://myapp.appspot.com/_ah/api/discovery/v1/apis/'; 88 | * google.discover(discoveryUrl, function (err) { 89 | * const someapi = google.someapi('v1'); 90 | * }); 91 | * 92 | * @name GoogleApis#discover 93 | * @method 94 | * @param url Url to the discovery service for a set of APIs. e.g., 95 | * https://www.googleapis.com/discovery/v1/apis 96 | * @param {Function} callback Callback function. 97 | */ 98 | discover(url: string): Promise; 99 | discover(url: string, callback: (err?: Error) => void): void; 100 | discover(url: string, callback?: (err?: Error) => void): void|Promise { 101 | if (callback) { 102 | this.discoverAsync(url).then(() => callback()).catch(callback); 103 | } else { 104 | return this.discoverAsync(url); 105 | } 106 | } 107 | 108 | private async discoverAsync(url: string) { 109 | const allApis = await this._discovery.discoverAllAPIs(url); 110 | this.addAPIs(allApis); 111 | } 112 | 113 | /** 114 | * Dynamically generate an Endpoint object from a discovery doc. 115 | * 116 | * @param path Url or file path to discover doc for a single API. 117 | * @param Options to configure the Endpoint object generated from the 118 | * discovery doc. 119 | * @returns A promise that resolves with the configured endpoint. 120 | */ 121 | async discoverAPI(apiPath: string, options: {} = {}): 122 | Promise> { 123 | const endpointCreator = await this._discovery.discoverAPI(apiPath); 124 | const ep = endpointCreator(options); 125 | ep.google = this; // for drive.google.transporter 126 | return Object.freeze(ep); 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /src/apis/acceleratedmobilepageurl/v1.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2015 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import {BodyResponseCallback, GlobalOptions, MethodOptions} from '../../lib/api'; 18 | import {createAPIRequest} from '../../lib/apirequest'; 19 | 20 | // TODO: We will eventually get the `any` in here cleared out, but in the 21 | // interim we want to turn on no-implicit-any. 22 | 23 | // tslint:disable: no-any 24 | 25 | 26 | /** 27 | * Accelerated Mobile Pages (AMP) URL API 28 | * 29 | * Retrieves the list of AMP URLs (and equivalent AMP Cache URLs) for a given 30 | * list of public URL(s). 31 | * 32 | * @example 33 | * const google = require('googleapis'); 34 | * const acceleratedmobilepageurl = google.acceleratedmobilepageurl('v1'); 35 | * 36 | * @namespace acceleratedmobilepageurl 37 | * @type {Function} 38 | * @version v1 39 | * @variation v1 40 | * @param {object=} options Options for Acceleratedmobilepageurl 41 | */ 42 | function Acceleratedmobilepageurl(options: GlobalOptions) { 43 | const self = this; 44 | self._options = options || {}; 45 | self.ampUrls = { 46 | /** 47 | * acceleratedmobilepageurl.ampUrls.batchGet 48 | * @desc Returns AMP URL(s) and equivalent [AMP Cache 49 | * URL(s)](/amp/cache/overview#amp-cache-url-format). 50 | * @alias acceleratedmobilepageurl.ampUrls.batchGet 51 | * @memberOf! acceleratedmobilepageurl(v1) 52 | * 53 | * @param {object} params Parameters for request 54 | * @param {acceleratedmobilepageurl(v1).BatchGetAmpUrlsRequest} params.resource Request body data 55 | * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. 56 | * @param {callback} callback The callback that handles the response. 57 | * @return {object} Request object 58 | */ 59 | batchGet( 60 | params: any, options: MethodOptions|BodyResponseCallback, 61 | callback?: BodyResponseCallback) { 62 | if (typeof options === 'function') { 63 | callback = options; 64 | options = {}; 65 | } 66 | options = options || {}; 67 | const rootUrl = 68 | options.rootUrl || 'https://acceleratedmobilepageurl.googleapis.com/'; 69 | const parameters = { 70 | options: Object.assign( 71 | { 72 | url: (rootUrl + '/v1/ampUrls:batchGet') 73 | .replace(/([^:]\/)\/+/g, '$1'), 74 | method: 'POST' 75 | }, 76 | options), 77 | params, 78 | requiredParams: [], 79 | pathParams: [], 80 | context: self 81 | }; 82 | return createAPIRequest(parameters, callback!); 83 | } 84 | 85 | }; 86 | } 87 | /** 88 | * @typedef AmpUrl 89 | * @memberOf! acceleratedmobilepageurl(v1) 90 | * @type object 91 | * @property {string} ampUrl The AMP URL pointing to the publisher's web server. 92 | * @property {string} cdnAmpUrl The [AMP Cache URL](/amp/cache/overview#amp-cache-url-format) pointing to the cached document in the Google AMP Cache. 93 | * @property {string} originalUrl The original non-AMP URL. 94 | */ 95 | /** 96 | * @typedef AmpUrlError 97 | * @memberOf! acceleratedmobilepageurl(v1) 98 | * @type object 99 | * @property {string} errorCode The error code of an API call. 100 | * @property {string} errorMessage An optional descriptive error message. 101 | * @property {string} originalUrl The original non-AMP URL. 102 | */ 103 | /** 104 | * @typedef BatchGetAmpUrlsRequest 105 | * @memberOf! acceleratedmobilepageurl(v1) 106 | * @type object 107 | * @property {string} lookupStrategy The lookup_strategy being requested. 108 | * @property {string[]} urls List of URLs to look up for the paired AMP URLs. The URLs are case-sensitive. Up to 50 URLs per lookup (see [Usage Limits](/amp/cache/reference/limits)). 109 | */ 110 | /** 111 | * @typedef BatchGetAmpUrlsResponse 112 | * @memberOf! acceleratedmobilepageurl(v1) 113 | * @type object 114 | * @property {acceleratedmobilepageurl(v1).AmpUrl[]} ampUrls For each URL in BatchAmpUrlsRequest, the URL response. The response might not be in the same order as URLs in the batch request. If BatchAmpUrlsRequest contains duplicate URLs, AmpUrl is generated only once. 115 | * @property {acceleratedmobilepageurl(v1).AmpUrlError[]} urlErrors The errors for requested URLs that have no AMP URL. 116 | */ 117 | 118 | export = Acceleratedmobilepageurl; 119 | -------------------------------------------------------------------------------- /src/apis/pagespeedonline/v1.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2015 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import {BodyResponseCallback, GlobalOptions, MethodOptions} from '../../lib/api'; 18 | import {createAPIRequest} from '../../lib/apirequest'; 19 | 20 | // TODO: We will eventually get the `any` in here cleared out, but in the 21 | // interim we want to turn on no-implicit-any. 22 | 23 | // tslint:disable: no-any 24 | 25 | 26 | /** 27 | * PageSpeed Insights API 28 | * 29 | * Analyzes the performance of a web page and provides tailored suggestions to 30 | * make that page faster. 31 | * 32 | * @example 33 | * const google = require('googleapis'); 34 | * const pagespeedonline = google.pagespeedonline('v1'); 35 | * 36 | * @namespace pagespeedonline 37 | * @type {Function} 38 | * @version v1 39 | * @variation v1 40 | * @param {object=} options Options for Pagespeedonline 41 | */ 42 | function Pagespeedonline(options: GlobalOptions) { 43 | const self = this; 44 | self._options = options || {}; 45 | self.pagespeedapi = { 46 | /** 47 | * pagespeedonline.pagespeedapi.runpagespeed 48 | * @desc Runs PageSpeed analysis on the page at the specified URL, and 49 | * returns a PageSpeed score, a list of suggestions to make that page 50 | * faster, and other information. 51 | * @alias pagespeedonline.pagespeedapi.runpagespeed 52 | * @memberOf! pagespeedonline(v1) 53 | * 54 | * @param {object} params Parameters for request 55 | * @param {boolean=} params.filter_third_party_resources Indicates if third party resources should be filtered out before PageSpeed analysis. 56 | * @param {string=} params.locale The locale used to localize formatted results 57 | * @param {string=} params.rule A PageSpeed rule to run; if none are given, all rules are run 58 | * @param {boolean=} params.screenshot Indicates if binary data containing a screenshot should be included 59 | * @param {string=} params.strategy The analysis strategy to use 60 | * @param {string} params.url The URL to fetch and analyze 61 | * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. 62 | * @param {callback} callback The callback that handles the response. 63 | * @return {object} Request object 64 | */ 65 | runpagespeed( 66 | params: any, options: MethodOptions|BodyResponseCallback, 67 | callback?: BodyResponseCallback) { 68 | if (typeof options === 'function') { 69 | callback = options; 70 | options = {}; 71 | } 72 | options = options || {}; 73 | const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; 74 | const parameters = { 75 | options: Object.assign( 76 | { 77 | url: (rootUrl + '/pagespeedonline/v1/runPagespeed') 78 | .replace(/([^:]\/)\/+/g, '$1'), 79 | method: 'GET' 80 | }, 81 | options), 82 | params, 83 | requiredParams: ['url'], 84 | pathParams: [], 85 | context: self 86 | }; 87 | return createAPIRequest(parameters, callback!); 88 | } 89 | 90 | }; 91 | } 92 | /** 93 | * @typedef Result 94 | * @memberOf! pagespeedonline(v1) 95 | * @type object 96 | * @property {string} captchaResult The captcha verify result 97 | * @property {object} formattedResults Localized PageSpeed results. Contains a ruleResults entry for each PageSpeed rule instantiated and run by the server. 98 | * @property {string} id Canonicalized and final URL for the document, after following page redirects (if any). 99 | * @property {string[]} invalidRules List of rules that were specified in the request, but which the server did not know how to instantiate. 100 | * @property {string} kind Kind of result. 101 | * @property {object} pageStats Summary statistics for the page, such as number of JavaScript bytes, number of HTML bytes, etc. 102 | * @property {integer} responseCode Response code for the document. 200 indicates a normal page load. 4xx/5xx indicates an error. 103 | * @property {integer} score The PageSpeed Score (0-100), which indicates how much faster a page could be. A high score indicates little room for improvement, while a lower score indicates more room for improvement. 104 | * @property {object} screenshot Base64-encoded screenshot of the page that was analyzed. 105 | * @property {string} title Title of the page, as displayed in the browser's title bar. 106 | * @property {object} version The version of PageSpeed used to generate these results. 107 | */ 108 | 109 | export = Pagespeedonline; 110 | -------------------------------------------------------------------------------- /src/apis/searchconsole/v1.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2015 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import {BodyResponseCallback, GlobalOptions, MethodOptions} from '../../lib/api'; 18 | import {createAPIRequest} from '../../lib/apirequest'; 19 | 20 | // TODO: We will eventually get the `any` in here cleared out, but in the 21 | // interim we want to turn on no-implicit-any. 22 | 23 | // tslint:disable: no-any 24 | 25 | 26 | /** 27 | * Google Search Console URL Testing Tools API 28 | * 29 | * Provides tools for running validation tests against single URLs 30 | * 31 | * @example 32 | * const google = require('googleapis'); 33 | * const searchconsole = google.searchconsole('v1'); 34 | * 35 | * @namespace searchconsole 36 | * @type {Function} 37 | * @version v1 38 | * @variation v1 39 | * @param {object=} options Options for Searchconsole 40 | */ 41 | function Searchconsole(options: GlobalOptions) { 42 | const self = this; 43 | self._options = options || {}; 44 | self.urlTestingTools = { 45 | mobileFriendlyTest: { 46 | /** 47 | * searchconsole.urlTestingTools.mobileFriendlyTest.run 48 | * @desc Runs Mobile-Friendly Test for a given URL. 49 | * @alias searchconsole.urlTestingTools.mobileFriendlyTest.run 50 | * @memberOf! searchconsole(v1) 51 | * 52 | * @param {object} params Parameters for request 53 | * @param {searchconsole(v1).RunMobileFriendlyTestRequest} params.resource Request body data 54 | * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. 55 | * @param {callback} callback The callback that handles the response. 56 | * @return {object} Request object 57 | */ 58 | run(params: any, options: MethodOptions|BodyResponseCallback, 59 | callback?: BodyResponseCallback) { 60 | if (typeof options === 'function') { 61 | callback = options; 62 | options = {}; 63 | } 64 | options = options || {}; 65 | const rootUrl = 66 | options.rootUrl || 'https://searchconsole.googleapis.com/'; 67 | const parameters = { 68 | options: Object.assign( 69 | { 70 | url: (rootUrl + '/v1/urlTestingTools/mobileFriendlyTest:run') 71 | .replace(/([^:]\/)\/+/g, '$1'), 72 | method: 'POST' 73 | }, 74 | options), 75 | params, 76 | requiredParams: [], 77 | pathParams: [], 78 | context: self 79 | }; 80 | return createAPIRequest(parameters, callback!); 81 | } 82 | 83 | } 84 | }; 85 | } 86 | /** 87 | * @typedef BlockedResource 88 | * @memberOf! searchconsole(v1) 89 | * @type object 90 | * @property {string} url URL of the blocked resource. 91 | */ 92 | /** 93 | * @typedef Image 94 | * @memberOf! searchconsole(v1) 95 | * @type object 96 | * @property {string} data Image data in format determined by the mime type. Currently, the format will always be "image/png", but this might change in the future. 97 | * @property {string} mimeType The mime-type of the image data. 98 | */ 99 | /** 100 | * @typedef MobileFriendlyIssue 101 | * @memberOf! searchconsole(v1) 102 | * @type object 103 | * @property {string} rule Rule violated. 104 | */ 105 | /** 106 | * @typedef ResourceIssue 107 | * @memberOf! searchconsole(v1) 108 | * @type object 109 | * @property {searchconsole(v1).BlockedResource} blockedResource Describes a blocked resource issue. 110 | */ 111 | /** 112 | * @typedef RunMobileFriendlyTestRequest 113 | * @memberOf! searchconsole(v1) 114 | * @type object 115 | * @property {boolean} requestScreenshot Whether or not screenshot is requested. Default is false. 116 | * @property {string} url URL for inspection. 117 | */ 118 | /** 119 | * @typedef RunMobileFriendlyTestResponse 120 | * @memberOf! searchconsole(v1) 121 | * @type object 122 | * @property {string} mobileFriendliness Test verdict, whether the page is mobile friendly or not. 123 | * @property {searchconsole(v1).MobileFriendlyIssue[]} mobileFriendlyIssues List of mobile-usability issues. 124 | * @property {searchconsole(v1).ResourceIssue[]} resourceIssues Information about embedded resources issues. 125 | * @property {searchconsole(v1).Image} screenshot Screenshot of the requested URL. 126 | * @property {searchconsole(v1).TestStatus} testStatus Final state of the test, can be either complete or an error. 127 | */ 128 | /** 129 | * @typedef TestStatus 130 | * @memberOf! searchconsole(v1) 131 | * @type object 132 | * @property {string} details Error details if applicable. 133 | * @property {string} status Status of the test. 134 | */ 135 | 136 | export = Searchconsole; 137 | -------------------------------------------------------------------------------- /src/lib/endpoint.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018, Google, LLC. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | import {BodyResponseCallback} from 'google-auth-library/build/src/transporters'; 15 | 16 | import {GoogleApis} from '../index'; 17 | import {buildurl} from '../scripts/generator_utils'; 18 | 19 | import {APIRequestContext, APIRequestMethodParams, APIRequestParams, GlobalOptions} from './api'; 20 | import {createAPIRequest} from './apirequest'; 21 | import {Discovery} from './discovery'; 22 | import {Schema, SchemaMethod, SchemaParameters, SchemaResource} from './schema'; 23 | 24 | export interface Target { [index: string]: {}; } 25 | 26 | export class Endpoint implements Target, APIRequestContext { 27 | _options: GlobalOptions; 28 | // tslint:disable-next-line no-any 29 | google: any; 30 | [index: string]: {}; 31 | 32 | constructor(options: {}) { 33 | this._options = options || {}; 34 | } 35 | 36 | /** 37 | * Given a schema, add methods and resources to a target. 38 | * 39 | * @param {object} target The target to which to apply the schema. 40 | * @param {object} rootSchema The top-level schema, so we don't lose track of it 41 | * during recursion. 42 | * @param {object} schema The current schema from which to extract methods and 43 | * resources. 44 | * @param {object} context The context to add to each method. 45 | */ 46 | applySchema( 47 | target: Target, rootSchema: Schema, schema: SchemaResource, 48 | context: APIRequestContext) { 49 | this.applyMethodsFromSchema(target, rootSchema, schema, context); 50 | if (schema.resources) { 51 | for (const resourceName in schema.resources) { 52 | if (schema.resources.hasOwnProperty(resourceName)) { 53 | const resource = schema.resources[resourceName]; 54 | if (!target[resourceName]) { 55 | target[resourceName] = {}; 56 | } 57 | this.applySchema(target[resourceName], rootSchema, resource, context); 58 | } 59 | } 60 | } 61 | } 62 | 63 | /** 64 | * Given a schema, add methods to a target. 65 | * 66 | * @param {object} target The target to which to apply the methods. 67 | * @param {object} rootSchema The top-level schema, so we don't lose track of it 68 | * during recursion. 69 | * @param {object} schema The current schema from which to extract methods. 70 | * @param {object} context The context to add to each method. 71 | */ 72 | private applyMethodsFromSchema( 73 | target: Target, rootSchema: Schema, schema: SchemaResource, 74 | context: APIRequestContext) { 75 | if (schema.methods) { 76 | for (const name in schema.methods) { 77 | if (schema.methods.hasOwnProperty(name)) { 78 | const method = schema.methods[name]; 79 | target[name] = this.makeMethod(rootSchema, method, context); 80 | } 81 | } 82 | } 83 | } 84 | 85 | /** 86 | * Given a method schema, add a method to a target. 87 | * 88 | * @param target The target to which to add the method. 89 | * @param schema The top-level schema that contains the rootUrl, etc. 90 | * @param method The method schema from which to generate the method. 91 | * @param context The context to add to the method. 92 | */ 93 | private makeMethod( 94 | schema: Schema, method: SchemaMethod, context: APIRequestContext) { 95 | return (params: APIRequestMethodParams, 96 | callback: BodyResponseCallback<{}>) => { 97 | const schemaUrl = 98 | buildurl(schema.rootUrl + schema.servicePath + method.path); 99 | 100 | const parameters: APIRequestParams = { 101 | options: { 102 | url: schemaUrl.substring(1, schemaUrl.length - 1), 103 | method: method.httpMethod 104 | }, 105 | params, 106 | requiredParams: method.parameterOrder || [], 107 | pathParams: this.getPathParams(method.parameters), 108 | context 109 | }; 110 | 111 | if (method.mediaUpload && method.mediaUpload.protocols && 112 | method.mediaUpload.protocols.simple && 113 | method.mediaUpload.protocols.simple.path) { 114 | const mediaUrl = 115 | buildurl(schema.rootUrl + method.mediaUpload.protocols.simple.path); 116 | parameters.mediaUrl = mediaUrl.substring(1, mediaUrl.length - 1); 117 | } 118 | 119 | return createAPIRequest(parameters, callback); 120 | }; 121 | } 122 | 123 | private getPathParams(params?: SchemaParameters) { 124 | const pathParams = new Array(); 125 | if (typeof params !== 'object') { 126 | params = {}; 127 | } 128 | Object.keys(params).forEach(key => { 129 | if (params![key].location === 'path') { 130 | pathParams.push(key); 131 | } 132 | }); 133 | return pathParams; 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /test/test.drive.v2.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2014-2016, Google, Inc. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | import * as assert from 'assert'; 15 | import * as nock from 'nock'; 16 | import * as pify from 'pify'; 17 | 18 | import {GoogleApis} from '../src'; 19 | import {APIEndpoint} from '../src/lib/api'; 20 | 21 | import {Utils} from './utils'; 22 | 23 | const googleapis = new GoogleApis(); 24 | 25 | describe('drive:v2', () => { 26 | let localDrive: APIEndpoint, remoteDrive: APIEndpoint; 27 | 28 | before(async () => { 29 | nock.cleanAll(); 30 | const google = new GoogleApis(); 31 | nock.enableNetConnect(); 32 | remoteDrive = await Utils.loadApi(google, 'drive', 'v2'); 33 | nock.disableNetConnect(); 34 | }); 35 | 36 | beforeEach(() => { 37 | nock.cleanAll(); 38 | nock.disableNetConnect(); 39 | const google = new GoogleApis(); 40 | localDrive = google.drive('v2'); 41 | }); 42 | 43 | it('should exist', (done) => { 44 | assert.notEqual(typeof googleapis.drive, null); 45 | done(); 46 | }); 47 | 48 | it('should be a function', (done) => { 49 | assert.equal(typeof googleapis.drive, 'function'); 50 | done(); 51 | }); 52 | 53 | it('should create a drive object', (done) => { 54 | assert.notEqual(typeof localDrive, 'undefined'); 55 | assert.notEqual(typeof remoteDrive, 'undefined'); 56 | done(); 57 | }); 58 | 59 | it('should be frozen (immutable)', (done) => { 60 | assert.equal(Object.isFrozen(localDrive), true); 61 | assert.equal(Object.isFrozen(remoteDrive), true); 62 | done(); 63 | }); 64 | 65 | describe('.files', () => { 66 | it('should exist', (done) => { 67 | assert.notEqual(typeof localDrive.files, 'undefined'); 68 | assert.notEqual(typeof remoteDrive.files, 'undefined'); 69 | done(); 70 | }); 71 | 72 | it('should be an object', (done) => { 73 | assert.equal(typeof localDrive.files, 'object'); 74 | assert.equal(typeof remoteDrive.files, 'object'); 75 | done(); 76 | }); 77 | 78 | describe('.insert', () => { 79 | it('should exist', (done) => { 80 | assert.notEqual(typeof localDrive.files.insert, 'undefined'); 81 | assert.notEqual(typeof remoteDrive.files.insert, 'undefined'); 82 | done(); 83 | }); 84 | 85 | it('should be a function', (done) => { 86 | assert.equal(typeof localDrive.files.insert, 'function'); 87 | assert.equal(typeof remoteDrive.files.insert, 'function'); 88 | done(); 89 | }); 90 | 91 | it('should not return a Request object', (done) => { 92 | let req = localDrive.files.insert({}, Utils.noop); 93 | assert.equal(req, undefined); 94 | req = remoteDrive.files.insert({}, Utils.noop); 95 | assert.equal(req, undefined); 96 | done(); 97 | }); 98 | }); 99 | 100 | describe('.get', () => { 101 | it('should exist', () => { 102 | assert.notEqual(typeof localDrive.files.get, 'undefined'); 103 | assert.notEqual(typeof remoteDrive.files.get, 'undefined'); 104 | }); 105 | 106 | it('should be a function', () => { 107 | assert.equal(typeof localDrive.files.get, 'function'); 108 | assert.equal(typeof remoteDrive.files.get, 'function'); 109 | }); 110 | 111 | it('should not return a Request object', () => { 112 | let req = localDrive.files.get({fileId: '123'}, Utils.noop); 113 | assert.equal(req, undefined); 114 | req = remoteDrive.files.get({fileId: '123'}, Utils.noop); 115 | assert.equal(req, undefined); 116 | }); 117 | 118 | it('should use logError callback if no callback specified', (done) => { 119 | nock(Utils.baseUrl).get('/drive/v2/files?q=hello').times(2).reply(501, { 120 | error: 'not a real error' 121 | }); 122 | 123 | // logError internally uses console.error - let's monkey-patch the 124 | // function to intercept calls to it, then restore the original function 125 | // once we are done testing 126 | const origFn = console.error; 127 | let count = 0; 128 | console.error = (err) => { 129 | count++; 130 | assert.equal(err.response.status, 501); 131 | if (count === 2) { 132 | console.error = origFn; 133 | done(); 134 | } 135 | }; 136 | 137 | assert.doesNotThrow(() => { 138 | localDrive.files.list({q: 'hello'}); 139 | remoteDrive.files.list({q: 'hello'}); 140 | }); 141 | }); 142 | }); 143 | }); 144 | 145 | describe('._options', () => { 146 | it('should exist', () => { 147 | assert.notEqual(typeof localDrive._options, 'undefined'); 148 | assert.notEqual(typeof remoteDrive._options, 'undefined'); 149 | }); 150 | 151 | it('should be an object', () => { 152 | assert.equal(typeof localDrive._options, 'object'); 153 | assert.equal(typeof remoteDrive._options, 'object'); 154 | }); 155 | }); 156 | 157 | describe('.files.list()', () => { 158 | it('should not return missing param error', async () => { 159 | nock(Utils.baseUrl).get('/drive/v2/files?q=hello').times(2).reply(200); 160 | await pify(localDrive.files.list)({q: 'hello'}); 161 | await pify(remoteDrive.files.list)({q: 'hello'}); 162 | }); 163 | }); 164 | 165 | after(() => { 166 | nock.cleanAll(); 167 | nock.enableNetConnect(); 168 | }); 169 | }); 170 | -------------------------------------------------------------------------------- /src/lib/discovery.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2014-2016, Google, Inc. 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License. 13 | 14 | import * as fs from 'fs'; 15 | import {DefaultTransporter} from 'google-auth-library'; 16 | import * as pify from 'pify'; 17 | import * as url from 'url'; 18 | import * as util from 'util'; 19 | 20 | import {GeneratedAPIs} from '../apis/index'; 21 | 22 | import {APIRequestMethodParams, ServiceOptions} from './api'; 23 | import {createAPIRequest} from './apirequest'; 24 | import {Endpoint} from './endpoint'; 25 | import {Schema, Schemas} from './schema'; 26 | 27 | export type EndpointCreator = (options: {}) => Endpoint; 28 | 29 | const fsp = pify(fs); 30 | 31 | export interface DiscoveryOptions { 32 | includePrivate?: boolean; 33 | debug?: boolean; 34 | } 35 | 36 | export class Discovery { 37 | private transporter = new DefaultTransporter(); 38 | private options: DiscoveryOptions; 39 | 40 | /** 41 | * Discovery for discovering API endpoints 42 | * 43 | * @param options Options for discovery 44 | */ 45 | constructor(options: DiscoveryOptions) { 46 | this.options = options || {}; 47 | } 48 | 49 | /** 50 | * Generate and Endpoint from an endpoint schema object. 51 | * 52 | * @param schema The schema from which to generate the Endpoint. 53 | * @return A function that creates an endpoint. 54 | */ 55 | private makeEndpoint(schema: Schema) { 56 | return (options: {}) => { 57 | const ep = new Endpoint(options); 58 | ep.applySchema(ep, schema, schema, ep); 59 | return ep; 60 | }; 61 | } 62 | 63 | /** 64 | * Log output of generator. Works just like console.log 65 | */ 66 | private log(...args: string[]) { 67 | if (this.options && this.options.debug) { 68 | console.log.apply(this, arguments); 69 | } 70 | } 71 | 72 | /** 73 | * Generate all APIs and return as in-memory object. 74 | * @param discoveryUrl 75 | */ 76 | async discoverAllAPIs(discoveryUrl: string): Promise { 77 | const headers = this.options.includePrivate ? {} : {'X-User-Ip': '0.0.0.0'}; 78 | const res = 79 | await this.transporter.request({url: discoveryUrl, headers}); 80 | const items = res.data.items; 81 | const apis = await Promise.all(items.map(async api => { 82 | const endpointCreator = await this.discoverAPI(api.discoveryRestUrl); 83 | return {api, endpointCreator}; 84 | })); 85 | 86 | const versionIndex: 87 | {[index: string]: {[index: string]: EndpointCreator}} = {}; 88 | // tslint:disable-next-line no-any 89 | const apisIndex: {[index: string]: any} = {}; 90 | for (const set of apis) { 91 | if (!apisIndex[set.api.name]) { 92 | versionIndex[set.api.name] = {}; 93 | apisIndex[set.api.name] = (options: ServiceOptions|string) => { 94 | const type = typeof options; 95 | let version: string; 96 | if (type === 'string') { 97 | version = options as string; 98 | options = {}; 99 | } else if (type === 'object') { 100 | version = (options as ServiceOptions).version!; 101 | delete (options as ServiceOptions).version; 102 | } else { 103 | throw new Error('Argument error: Accepts only string or object'); 104 | } 105 | try { 106 | const endpointCreator = versionIndex[set.api.name][version]; 107 | const ep = set.endpointCreator(options); 108 | // tslint:disable-next-line: no-any 109 | (ep as any).google = this; // for drive.google.transporter 110 | return Object.freeze(ep); // create new & freeze 111 | } catch (e) { 112 | throw new Error(util.format( 113 | 'Unable to load endpoint %s("%s"): %s', set.api.name, version, 114 | e.message)); 115 | } 116 | }; 117 | } 118 | versionIndex[set.api.name][set.api.version] = set.endpointCreator; 119 | } 120 | return apisIndex as GeneratedAPIs; 121 | } 122 | 123 | /** 124 | * Generate API file given discovery URL 125 | * 126 | * @param apiDiscoveryUrl URL or filename of discovery doc for API 127 | * @returns A promise that resolves with a function that creates the endpoint 128 | */ 129 | async discoverAPI(apiDiscoveryUrl: string| 130 | APIRequestMethodParams): Promise { 131 | if (typeof apiDiscoveryUrl === 'string') { 132 | const parts = url.parse(apiDiscoveryUrl); 133 | if (apiDiscoveryUrl && !parts.protocol) { 134 | this.log('Reading from file ' + apiDiscoveryUrl); 135 | const file = await fsp.readFile(apiDiscoveryUrl, {encoding: 'utf8'}); 136 | return this.makeEndpoint(JSON.parse(file)); 137 | } else { 138 | this.log('Requesting ' + apiDiscoveryUrl); 139 | const res = 140 | await this.transporter.request({url: apiDiscoveryUrl}); 141 | return this.makeEndpoint(res.data); 142 | } 143 | } else { 144 | const options = apiDiscoveryUrl; 145 | this.log('Requesting ' + options.url); 146 | const url = options.url; 147 | delete options.url; 148 | const parameters = { 149 | options: {url, method: 'GET'}, 150 | requiredParams: [], 151 | pathParams: [], 152 | params: options, 153 | context: {google: {_options: {}}, _options: {}} 154 | }; 155 | const pcr = pify(createAPIRequest); 156 | const res = await pcr(parameters); 157 | return this.makeEndpoint(res.data); 158 | } 159 | } 160 | } 161 | -------------------------------------------------------------------------------- /src/apis/abusiveexperiencereport/v1.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2015 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import {BodyResponseCallback, GlobalOptions, MethodOptions} from '../../lib/api'; 18 | import {createAPIRequest} from '../../lib/apirequest'; 19 | 20 | // TODO: We will eventually get the `any` in here cleared out, but in the 21 | // interim we want to turn on no-implicit-any. 22 | 23 | // tslint:disable: no-any 24 | 25 | 26 | /** 27 | * Google Abusive Experience Report API 28 | * 29 | * View Abusive Experience Report data, and get a list of sites that have a 30 | * significant number of abusive experiences. 31 | * 32 | * @example 33 | * const google = require('googleapis'); 34 | * const abusiveexperiencereport = google.abusiveexperiencereport('v1'); 35 | * 36 | * @namespace abusiveexperiencereport 37 | * @type {Function} 38 | * @version v1 39 | * @variation v1 40 | * @param {object=} options Options for Abusiveexperiencereport 41 | */ 42 | function Abusiveexperiencereport(options: GlobalOptions) { 43 | const self = this; 44 | self._options = options || {}; 45 | self.sites = { 46 | /** 47 | * abusiveexperiencereport.sites.get 48 | * @desc Gets a summary of the abusive experience rating of a site. 49 | * @alias abusiveexperiencereport.sites.get 50 | * @memberOf! abusiveexperiencereport(v1) 51 | * 52 | * @param {object} params Parameters for request 53 | * @param {string} params.name The required site name. This is the site property whose abusive experiences have been reviewed, and it must be URL-encoded. For example, sites/https%3A%2F%2Fwww.google.com. The server will return an error of BAD_REQUEST if this field is not filled in. Note that if the site property is not yet verified in Search Console, the reportUrl field returned by the API will lead to the verification page, prompting the user to go through that process before they can gain access to the Abusive Experience Report. 54 | * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. 55 | * @param {callback} callback The callback that handles the response. 56 | * @return {object} Request object 57 | */ 58 | get(params: any, options: MethodOptions|BodyResponseCallback, 59 | callback?: BodyResponseCallback) { 60 | if (typeof options === 'function') { 61 | callback = options; 62 | options = {}; 63 | } 64 | options = options || {}; 65 | const rootUrl = 66 | options.rootUrl || 'https://abusiveexperiencereport.googleapis.com/'; 67 | const parameters = { 68 | options: Object.assign( 69 | { 70 | url: (rootUrl + '/v1/{name}').replace(/([^:]\/)\/+/g, '$1'), 71 | method: 'GET' 72 | }, 73 | options), 74 | params, 75 | requiredParams: ['name'], 76 | pathParams: ['name'], 77 | context: self 78 | }; 79 | return createAPIRequest(parameters, callback!); 80 | } 81 | 82 | }; 83 | self.violatingSites = { 84 | /** 85 | * abusiveexperiencereport.violatingSites.list 86 | * @desc Lists sites with Abusive Experience Report statuses of "Failing". 87 | * @alias abusiveexperiencereport.violatingSites.list 88 | * @memberOf! abusiveexperiencereport(v1) 89 | * 90 | * @param {object} params Parameters for request 91 | * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. 92 | * @param {callback} callback The callback that handles the response. 93 | * @return {object} Request object 94 | */ 95 | list( 96 | params: any, options: MethodOptions|BodyResponseCallback, 97 | callback?: BodyResponseCallback) { 98 | if (typeof options === 'function') { 99 | callback = options; 100 | options = {}; 101 | } 102 | options = options || {}; 103 | const rootUrl = 104 | options.rootUrl || 'https://abusiveexperiencereport.googleapis.com/'; 105 | const parameters = { 106 | options: Object.assign( 107 | { 108 | url: (rootUrl + '/v1/violatingSites') 109 | .replace(/([^:]\/)\/+/g, '$1'), 110 | method: 'GET' 111 | }, 112 | options), 113 | params, 114 | requiredParams: [], 115 | pathParams: [], 116 | context: self 117 | }; 118 | return createAPIRequest(parameters, callback!); 119 | } 120 | 121 | }; 122 | } 123 | /** 124 | * @typedef SiteSummaryResponse 125 | * @memberOf! abusiveexperiencereport(v1) 126 | * @type object 127 | * @property {string} abusiveStatus The status of the site reviewed for the abusive experiences. 128 | * @property {string} enforcementTime The date on which enforcement begins. 129 | * @property {string} filterStatus The abusive experience enforcement status of the site. 130 | * @property {string} lastChangeTime The last time that the site changed status. 131 | * @property {string} reportUrl A link that leads to a full abusive experience report. 132 | * @property {string} reviewedSite The name of the site reviewed. 133 | * @property {boolean} underReview Whether the site is currently under review. 134 | */ 135 | /** 136 | * @typedef ViolatingSitesResponse 137 | * @memberOf! abusiveexperiencereport(v1) 138 | * @type object 139 | * @property {abusiveexperiencereport(v1).SiteSummaryResponse[]} violatingSites A list of summaries of violating sites. 140 | */ 141 | 142 | export = Abusiveexperiencereport; 143 | -------------------------------------------------------------------------------- /src/apis/pagespeedonline/v2.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2015 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import {BodyResponseCallback, GlobalOptions, MethodOptions} from '../../lib/api'; 18 | import {createAPIRequest} from '../../lib/apirequest'; 19 | 20 | // TODO: We will eventually get the `any` in here cleared out, but in the 21 | // interim we want to turn on no-implicit-any. 22 | 23 | // tslint:disable: no-any 24 | 25 | 26 | /** 27 | * PageSpeed Insights API 28 | * 29 | * Analyzes the performance of a web page and provides tailored suggestions to 30 | * make that page faster. 31 | * 32 | * @example 33 | * const google = require('googleapis'); 34 | * const pagespeedonline = google.pagespeedonline('v2'); 35 | * 36 | * @namespace pagespeedonline 37 | * @type {Function} 38 | * @version v2 39 | * @variation v2 40 | * @param {object=} options Options for Pagespeedonline 41 | */ 42 | function Pagespeedonline(options: GlobalOptions) { 43 | const self = this; 44 | self._options = options || {}; 45 | self.pagespeedapi = { 46 | /** 47 | * pagespeedonline.pagespeedapi.runpagespeed 48 | * @desc Runs PageSpeed analysis on the page at the specified URL, and 49 | * returns PageSpeed scores, a list of suggestions to make that page faster, 50 | * and other information. 51 | * @alias pagespeedonline.pagespeedapi.runpagespeed 52 | * @memberOf! pagespeedonline(v2) 53 | * 54 | * @param {object} params Parameters for request 55 | * @param {boolean=} params.filter_third_party_resources Indicates if third party resources should be filtered out before PageSpeed analysis. 56 | * @param {string=} params.locale The locale used to localize formatted results 57 | * @param {string=} params.rule A PageSpeed rule to run; if none are given, all rules are run 58 | * @param {boolean=} params.screenshot Indicates if binary data containing a screenshot should be included 59 | * @param {string=} params.strategy The analysis strategy to use 60 | * @param {string} params.url The URL to fetch and analyze 61 | * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. 62 | * @param {callback} callback The callback that handles the response. 63 | * @return {object} Request object 64 | */ 65 | runpagespeed( 66 | params: any, options: MethodOptions|BodyResponseCallback, 67 | callback?: BodyResponseCallback) { 68 | if (typeof options === 'function') { 69 | callback = options; 70 | options = {}; 71 | } 72 | options = options || {}; 73 | const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; 74 | const parameters = { 75 | options: Object.assign( 76 | { 77 | url: (rootUrl + '/pagespeedonline/v2/runPagespeed') 78 | .replace(/([^:]\/)\/+/g, '$1'), 79 | method: 'GET' 80 | }, 81 | options), 82 | params, 83 | requiredParams: ['url'], 84 | pathParams: [], 85 | context: self 86 | }; 87 | return createAPIRequest(parameters, callback!); 88 | } 89 | 90 | }; 91 | } 92 | /** 93 | * @typedef PagespeedApiFormatStringV2 94 | * @memberOf! pagespeedonline(v2) 95 | * @type object 96 | * @property {object[]} args List of arguments for the format string. 97 | * @property {string} format A localized format string with {{FOO}} placeholders, where 'FOO' is the key of the argument whose value should be substituted. For HYPERLINK arguments, the format string will instead contain {{BEGIN_FOO}} and {{END_FOO}} for the argument with key 'FOO'. 98 | */ 99 | /** 100 | * @typedef PagespeedApiImageV2 101 | * @memberOf! pagespeedonline(v2) 102 | * @type object 103 | * @property {string} data Image data base64 encoded. 104 | * @property {integer} height Height of screenshot in pixels. 105 | * @property {string} key Unique string key, if any, identifying this image. 106 | * @property {string} mime_type Mime type of image data (e.g. "image/jpeg"). 107 | * @property {object} page_rect The region of the page that is captured by this image, with dimensions measured in CSS pixels. 108 | * @property {integer} width Width of screenshot in pixels. 109 | */ 110 | /** 111 | * @typedef Result 112 | * @memberOf! pagespeedonline(v2) 113 | * @type object 114 | * @property {string} captchaResult The captcha verify result 115 | * @property {object} formattedResults Localized PageSpeed results. Contains a ruleResults entry for each PageSpeed rule instantiated and run by the server. 116 | * @property {string} id Canonicalized and final URL for the document, after following page redirects (if any). 117 | * @property {string[]} invalidRules List of rules that were specified in the request, but which the server did not know how to instantiate. 118 | * @property {string} kind Kind of result. 119 | * @property {object} pageStats Summary statistics for the page, such as number of JavaScript bytes, number of HTML bytes, etc. 120 | * @property {integer} responseCode Response code for the document. 200 indicates a normal page load. 4xx/5xx indicates an error. 121 | * @property {object} ruleGroups A map with one entry for each rule group in these results. 122 | * @property {pagespeedonline(v2).PagespeedApiImageV2} screenshot Base64-encoded screenshot of the page that was analyzed. 123 | * @property {string} title Title of the page, as displayed in the browser's title bar. 124 | * @property {object} version The version of PageSpeed used to generate these results. 125 | */ 126 | 127 | export = Pagespeedonline; 128 | -------------------------------------------------------------------------------- /src/apis/androidpublisher/v1.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2015 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import {BodyResponseCallback, GlobalOptions, MethodOptions} from '../../lib/api'; 18 | import {createAPIRequest} from '../../lib/apirequest'; 19 | 20 | // TODO: We will eventually get the `any` in here cleared out, but in the 21 | // interim we want to turn on no-implicit-any. 22 | 23 | // tslint:disable: no-any 24 | 25 | 26 | /** 27 | * Google Play Developer API 28 | * 29 | * Lets Android application developers access their Google Play accounts. 30 | * 31 | * @example 32 | * const google = require('googleapis'); 33 | * const androidpublisher = google.androidpublisher('v1'); 34 | * 35 | * @namespace androidpublisher 36 | * @type {Function} 37 | * @version v1 38 | * @variation v1 39 | * @param {object=} options Options for Androidpublisher 40 | */ 41 | function Androidpublisher(options: GlobalOptions) { 42 | const self = this; 43 | self._options = options || {}; 44 | self.purchases = { 45 | /** 46 | * androidpublisher.purchases.cancel 47 | * @desc Cancels a user's subscription purchase. The subscription remains 48 | * valid until its expiration time. 49 | * @alias androidpublisher.purchases.cancel 50 | * @memberOf! androidpublisher(v1) 51 | * 52 | * @param {object} params Parameters for request 53 | * @param {string} params.packageName The package name of the application for which this subscription was purchased (for example, 'com.some.thing'). 54 | * @param {string} params.subscriptionId The purchased subscription ID (for example, 'monthly001'). 55 | * @param {string} params.token The token provided to the user's device when the subscription was purchased. 56 | * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. 57 | * @param {callback} callback The callback that handles the response. 58 | * @return {object} Request object 59 | */ 60 | cancel( 61 | params: any, options: MethodOptions|BodyResponseCallback, 62 | callback?: BodyResponseCallback) { 63 | if (typeof options === 'function') { 64 | callback = options; 65 | options = {}; 66 | } 67 | options = options || {}; 68 | const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; 69 | const parameters = { 70 | options: Object.assign( 71 | { 72 | url: 73 | (rootUrl + 74 | '/androidpublisher/v1/applications/{packageName}/subscriptions/{subscriptionId}/purchases/{token}/cancel') 75 | .replace(/([^:]\/)\/+/g, '$1'), 76 | method: 'POST' 77 | }, 78 | options), 79 | params, 80 | requiredParams: ['packageName', 'subscriptionId', 'token'], 81 | pathParams: ['packageName', 'subscriptionId', 'token'], 82 | context: self 83 | }; 84 | return createAPIRequest(parameters, callback!); 85 | }, /** 86 | * androidpublisher.purchases.get 87 | * @desc Checks whether a user's subscription purchase is valid and 88 | * returns its expiry time. 89 | * @alias androidpublisher.purchases.get 90 | * @memberOf! androidpublisher(v1) 91 | * 92 | * @param {object} params Parameters for request 93 | * @param {string} params.packageName The package name of the application for which this subscription was purchased (for example, 'com.some.thing'). 94 | * @param {string} params.subscriptionId The purchased subscription ID (for example, 'monthly001'). 95 | * @param {string} params.token The token provided to the user's device when the subscription was purchased. 96 | * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. 97 | * @param {callback} callback The callback that handles the response. 98 | * @return {object} Request object 99 | */ 100 | get(params: any, options: MethodOptions|BodyResponseCallback, 101 | callback?: BodyResponseCallback) { 102 | if (typeof options === 'function') { 103 | callback = options; 104 | options = {}; 105 | } 106 | options = options || {}; 107 | const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; 108 | const parameters = { 109 | options: Object.assign( 110 | { 111 | url: 112 | (rootUrl + 113 | '/androidpublisher/v1/applications/{packageName}/subscriptions/{subscriptionId}/purchases/{token}') 114 | .replace(/([^:]\/)\/+/g, '$1'), 115 | method: 'GET' 116 | }, 117 | options), 118 | params, 119 | requiredParams: ['packageName', 'subscriptionId', 'token'], 120 | pathParams: ['packageName', 'subscriptionId', 'token'], 121 | context: self 122 | }; 123 | return createAPIRequest(parameters, callback!); 124 | } 125 | 126 | }; 127 | } 128 | /** 129 | * @typedef SubscriptionPurchase 130 | * @memberOf! androidpublisher(v1) 131 | * @type object 132 | * @property {boolean} autoRenewing Whether the subscription will automatically be renewed when it reaches its current expiry time. 133 | * @property {string} initiationTimestampMsec Time at which the subscription was granted, in milliseconds since the Epoch. 134 | * @property {string} kind This kind represents a subscriptionPurchase object in the androidpublisher service. 135 | * @property {string} validUntilTimestampMsec Time at which the subscription will expire, in milliseconds since the Epoch. 136 | */ 137 | 138 | export = Androidpublisher; 139 | -------------------------------------------------------------------------------- /src/apis/adexperiencereport/v1.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2015 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import {BodyResponseCallback, GlobalOptions, MethodOptions} from '../../lib/api'; 18 | import {createAPIRequest} from '../../lib/apirequest'; 19 | 20 | // TODO: We will eventually get the `any` in here cleared out, but in the 21 | // interim we want to turn on no-implicit-any. 22 | 23 | // tslint:disable: no-any 24 | 25 | 26 | /** 27 | * Google Ad Experience Report API 28 | * 29 | * View Ad Experience Report data, and get a list of sites that have a 30 | * significant number of annoying ads. 31 | * 32 | * @example 33 | * const google = require('googleapis'); 34 | * const adexperiencereport = google.adexperiencereport('v1'); 35 | * 36 | * @namespace adexperiencereport 37 | * @type {Function} 38 | * @version v1 39 | * @variation v1 40 | * @param {object=} options Options for Adexperiencereport 41 | */ 42 | function Adexperiencereport(options: GlobalOptions) { 43 | const self = this; 44 | self._options = options || {}; 45 | self.sites = { 46 | /** 47 | * adexperiencereport.sites.get 48 | * @desc Gets a summary of the ad experience rating of a site. 49 | * @alias adexperiencereport.sites.get 50 | * @memberOf! adexperiencereport(v1) 51 | * 52 | * @param {object} params Parameters for request 53 | * @param {string} params.name The required site name. It should be the site property whose ad experiences may have been reviewed, and it should be URL-encoded. For example, sites/https%3A%2F%2Fwww.google.com. The server will return an error of BAD_REQUEST if this field is not filled in. Note that if the site property is not yet verified in Search Console, the reportUrl field returned by the API will lead to the verification page, prompting the user to go through that process before they can gain access to the Ad Experience Report. 54 | * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. 55 | * @param {callback} callback The callback that handles the response. 56 | * @return {object} Request object 57 | */ 58 | get(params: any, options: MethodOptions|BodyResponseCallback, 59 | callback?: BodyResponseCallback) { 60 | if (typeof options === 'function') { 61 | callback = options; 62 | options = {}; 63 | } 64 | options = options || {}; 65 | const rootUrl = 66 | options.rootUrl || 'https://adexperiencereport.googleapis.com/'; 67 | const parameters = { 68 | options: Object.assign( 69 | { 70 | url: (rootUrl + '/v1/{name}').replace(/([^:]\/)\/+/g, '$1'), 71 | method: 'GET' 72 | }, 73 | options), 74 | params, 75 | requiredParams: ['name'], 76 | pathParams: ['name'], 77 | context: self 78 | }; 79 | return createAPIRequest(parameters, callback!); 80 | } 81 | 82 | }; 83 | self.violatingSites = { 84 | /** 85 | * adexperiencereport.violatingSites.list 86 | * @desc Lists sites with Ad Experience Report statuses of "Failing" or 87 | * "Warning". 88 | * @alias adexperiencereport.violatingSites.list 89 | * @memberOf! adexperiencereport(v1) 90 | * 91 | * @param {object} params Parameters for request 92 | * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. 93 | * @param {callback} callback The callback that handles the response. 94 | * @return {object} Request object 95 | */ 96 | list( 97 | params: any, options: MethodOptions|BodyResponseCallback, 98 | callback?: BodyResponseCallback) { 99 | if (typeof options === 'function') { 100 | callback = options; 101 | options = {}; 102 | } 103 | options = options || {}; 104 | const rootUrl = 105 | options.rootUrl || 'https://adexperiencereport.googleapis.com/'; 106 | const parameters = { 107 | options: Object.assign( 108 | { 109 | url: (rootUrl + '/v1/violatingSites') 110 | .replace(/([^:]\/)\/+/g, '$1'), 111 | method: 'GET' 112 | }, 113 | options), 114 | params, 115 | requiredParams: [], 116 | pathParams: [], 117 | context: self 118 | }; 119 | return createAPIRequest(parameters, callback!); 120 | } 121 | 122 | }; 123 | } 124 | /** 125 | * @typedef PlatformSummary 126 | * @memberOf! adexperiencereport(v1) 127 | * @type object 128 | * @property {string} betterAdsStatus The status of the site reviewed for the Better Ads Standards. 129 | * @property {string} enforcementTime The date on which ad filtering begins. 130 | * @property {string} filterStatus The ad filtering status of the site. 131 | * @property {string} lastChangeTime The last time that the site changed status. 132 | * @property {string[]} region The assigned regions for the site and platform. 133 | * @property {string} reportUrl A link that leads to a full ad experience report. 134 | * @property {boolean} underReview Whether the site is currently under review. 135 | */ 136 | /** 137 | * @typedef SiteSummaryResponse 138 | * @memberOf! adexperiencereport(v1) 139 | * @type object 140 | * @property {adexperiencereport(v1).PlatformSummary} desktopSummary Summary for the desktop review of the site. 141 | * @property {adexperiencereport(v1).PlatformSummary} mobileSummary Summary for the mobile review of the site. 142 | * @property {string} reviewedSite The name of the site reviewed. 143 | */ 144 | /** 145 | * @typedef ViolatingSitesResponse 146 | * @memberOf! adexperiencereport(v1) 147 | * @type object 148 | * @property {adexperiencereport(v1).SiteSummaryResponse[]} violatingSites A list of summaries of violating sites. 149 | */ 150 | 151 | export = Adexperiencereport; 152 | -------------------------------------------------------------------------------- /src/apis/pagespeedonline/v4.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2015 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import {BodyResponseCallback, GlobalOptions, MethodOptions} from '../../lib/api'; 18 | import {createAPIRequest} from '../../lib/apirequest'; 19 | 20 | // TODO: We will eventually get the `any` in here cleared out, but in the 21 | // interim we want to turn on no-implicit-any. 22 | 23 | // tslint:disable: no-any 24 | 25 | 26 | /** 27 | * PageSpeed Insights API 28 | * 29 | * Analyzes the performance of a web page and provides tailored suggestions to 30 | * make that page faster. 31 | * 32 | * @example 33 | * const google = require('googleapis'); 34 | * const pagespeedonline = google.pagespeedonline('v4'); 35 | * 36 | * @namespace pagespeedonline 37 | * @type {Function} 38 | * @version v4 39 | * @variation v4 40 | * @param {object=} options Options for Pagespeedonline 41 | */ 42 | function Pagespeedonline(options: GlobalOptions) { 43 | const self = this; 44 | self._options = options || {}; 45 | self.pagespeedapi = { 46 | /** 47 | * pagespeedonline.pagespeedapi.runpagespeed 48 | * @desc Runs PageSpeed analysis on the page at the specified URL, and 49 | * returns PageSpeed scores, a list of suggestions to make that page faster, 50 | * and other information. 51 | * @alias pagespeedonline.pagespeedapi.runpagespeed 52 | * @memberOf! pagespeedonline(v4) 53 | * 54 | * @param {object} params Parameters for request 55 | * @param {boolean=} params.filter_third_party_resources Indicates if third party resources should be filtered out before PageSpeed analysis. 56 | * @param {string=} params.locale The locale used to localize formatted results 57 | * @param {string=} params.rule A PageSpeed rule to run; if none are given, all rules are run 58 | * @param {boolean=} params.screenshot Indicates if binary data containing a screenshot should be included 59 | * @param {boolean=} params.snapshots Indicates if binary data containing snapshot images should be included 60 | * @param {string=} params.strategy The analysis strategy (desktop or mobile) to use, and desktop is the default 61 | * @param {string} params.url The URL to fetch and analyze 62 | * @param {string=} params.utm_campaign Campaign name for analytics. 63 | * @param {string=} params.utm_source Campaign source for analytics. 64 | * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. 65 | * @param {callback} callback The callback that handles the response. 66 | * @return {object} Request object 67 | */ 68 | runpagespeed( 69 | params: any, options: MethodOptions|BodyResponseCallback, 70 | callback?: BodyResponseCallback) { 71 | if (typeof options === 'function') { 72 | callback = options; 73 | options = {}; 74 | } 75 | options = options || {}; 76 | const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; 77 | const parameters = { 78 | options: Object.assign( 79 | { 80 | url: (rootUrl + '/pagespeedonline/v4/runPagespeed') 81 | .replace(/([^:]\/)\/+/g, '$1'), 82 | method: 'GET' 83 | }, 84 | options), 85 | params, 86 | requiredParams: ['url'], 87 | pathParams: [], 88 | context: self 89 | }; 90 | return createAPIRequest(parameters, callback!); 91 | } 92 | 93 | }; 94 | } 95 | /** 96 | * @typedef PagespeedApiFormatStringV4 97 | * @memberOf! pagespeedonline(v4) 98 | * @type object 99 | * @property {object[]} args List of arguments for the format string. 100 | * @property {string} format A localized format string with {{FOO}} placeholders, where 'FOO' is the key of the argument whose value should be substituted. For HYPERLINK arguments, the format string will instead contain {{BEGIN_FOO}} and {{END_FOO}} for the argument with key 'FOO'. 101 | */ 102 | /** 103 | * @typedef PagespeedApiImageV4 104 | * @memberOf! pagespeedonline(v4) 105 | * @type object 106 | * @property {string} data Image data base64 encoded. 107 | * @property {integer} height Height of screenshot in pixels. 108 | * @property {string} key Unique string key, if any, identifying this image. 109 | * @property {string} mime_type Mime type of image data (e.g. "image/jpeg"). 110 | * @property {object} page_rect 111 | * @property {integer} width Width of screenshot in pixels. 112 | */ 113 | /** 114 | * @typedef PagespeedApiPagespeedResponseV4 115 | * @memberOf! pagespeedonline(v4) 116 | * @type object 117 | * @property {string} captchaResult The captcha verify result 118 | * @property {object} formattedResults Localized PageSpeed results. Contains a ruleResults entry for each PageSpeed rule instantiated and run by the server. 119 | * @property {string} id Canonicalized and final URL for the document, after following page redirects (if any). 120 | * @property {string[]} invalidRules List of rules that were specified in the request, but which the server did not know how to instantiate. 121 | * @property {string} kind Kind of result. 122 | * @property {object} loadingExperience Metrics of end users' page loading experience. 123 | * @property {object} pageStats Summary statistics for the page, such as number of JavaScript bytes, number of HTML bytes, etc. 124 | * @property {integer} responseCode Response code for the document. 200 indicates a normal page load. 4xx/5xx indicates an error. 125 | * @property {object} ruleGroups A map with one entry for each rule group in these results. 126 | * @property {pagespeedonline(v4).PagespeedApiImageV4} screenshot Base64-encoded screenshot of the page that was analyzed. 127 | * @property {pagespeedonline(v4).PagespeedApiImageV4[]} snapshots Additional base64-encoded screenshots of the page, in various partial render states. 128 | * @property {string} title Title of the page, as displayed in the browser's title bar. 129 | * @property {object} version The version of PageSpeed used to generate these results. 130 | */ 131 | 132 | export = Pagespeedonline; 133 | --------------------------------------------------------------------------------