Skip to content

Commit

Permalink
chore: switch to axios (#182)
Browse files Browse the repository at this point in the history
  • Loading branch information
JustinBeckwith committed Nov 24, 2017
1 parent 7a0c748 commit 98b2b1a
Show file tree
Hide file tree
Showing 21 changed files with 2,126 additions and 2,549 deletions.
587 changes: 169 additions & 418 deletions package-lock.json

Large diffs are not rendered by default.

7 changes: 2 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,19 +21,16 @@
],
"dependencies": {
"gtoken": "^2.0.1",
"axios": "^0.17.1",
"jws": "^3.1.4",
"lodash.isstring": "^4.0.1",
"lodash.merge": "^4.6.0",
"request": "^2.81.0"
"lodash.isstring": "^4.0.1"
},
"devDependencies": {
"@types/jws": "^3.1.0",
"@types/lodash.isstring": "^4.0.2",
"@types/lodash.merge": "^4.6.2",
"@types/mocha": "^2.2.41",
"@types/nock": "^8.2.1",
"@types/node": "^8.0.47",
"@types/request": "2.0.7",
"coveralls": "^2.13.0",
"gts": "^0.5.1",
"istanbul": "^0.4.5",
Expand Down
9 changes: 3 additions & 6 deletions src/auth/authclient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,16 @@
* limitations under the License.
*/

import * as request from 'request';

import {AxiosPromise, AxiosRequestConfig} from 'axios';
import {DefaultTransporter} from '../transporters';

import {Credentials} from './credentials';

export abstract class AuthClient {
transporter = new DefaultTransporter();
credentials: Credentials;

/**
* Provides an alternative request
* implementations with auth credentials.
* Provides an alternative Axios request implementation with auth credentials
*/
abstract request(opts: request.Options): request.Request|void;
abstract request<T>(opts: AxiosRequestConfig): AxiosPromise<T>;
}
118 changes: 53 additions & 65 deletions src/auth/computeclient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,11 @@
* limitations under the License.
*/

import * as request from 'request';
import {AxiosError, AxiosPromise, AxiosRequestConfig, AxiosResponse} from 'axios';

import {BodyResponseCallback, RequestError} from './../transporters';
import {OAuth2Client} from './oauth2client';

export interface Token {
expires_in: number;
expiry_date: number;
}

export declare type RefreshTokenCallback =
(err?: Error|null, token?: Token,
response?: request.RequestResponse|null) => void;
import {RequestError} from './../transporters';
import {CredentialRequest, Credentials} from './credentials';
import {GetTokenResponse, OAuth2Client} from './oauth2client';

export class Compute extends OAuth2Client {
/**
Expand All @@ -51,7 +43,7 @@ export class Compute extends OAuth2Client {
/**
* Indicates whether the credential requires scopes to be created by calling
* createdScoped before use.
* @return {object} The cloned instance.
* @return Boolean indicating if scope is required.
*/
createScopedRequired() {
// On compute engine, scopes are specified at the compute instance's
Expand All @@ -62,64 +54,60 @@ export class Compute extends OAuth2Client {

/**
* Refreshes the access token.
* @param {object=} ignored_
* @param {function=} callback Optional callback.
* @param refreshToken Unused parameter
*/
protected refreshToken(ignored: null, callback?: BodyResponseCallback):
request.Request {
const uri = this.opts.tokenUrl || Compute._GOOGLE_OAUTH2_TOKEN_URL;
protected async refreshToken(refreshToken?: string|
null): Promise<GetTokenResponse> {
const url = this.opts.tokenUrl || Compute._GOOGLE_OAUTH2_TOKEN_URL;
let res: AxiosResponse<CredentialRequest>|null = null;
// request for new token
return this.transporter.request(
{method: 'GET', uri, json: true}, (err, body, response) => {
const token = body as Token;
if (!err && token && token.expires_in) {
token.expiry_date =
((new Date()).getTime() + (token.expires_in * 1000));
delete token.expires_in;
}
if (callback) {
callback(err, token, response);
}
});
try {
res = await this.transporter.request<CredentialRequest>({url});
} catch (e) {
e.message = 'Could not refresh access token.';
throw e;
}
console.log(res.data);
const tokens = res.data as Credentials;
if (res.data && res.data.expires_in) {
tokens.expiry_date =
((new Date()).getTime() + (res.data.expires_in * 1000));
delete (tokens as CredentialRequest).expires_in;
}
return {tokens, res};
}

/**
* Inserts a helpful error message guiding the user toward fixing common auth
* issues.
* @param {object} err Error result.
* @param {object} result The result.
* @param {object} response The HTTP response.
* @param {Function} callback The callback.
*/
protected postRequest(
err: Error, result: {}, response: request.RequestResponse,
callback: BodyResponseCallback) {
if (response && response.statusCode) {
let helpfulMessage = null;
if (response.statusCode === 403) {
helpfulMessage =
'A Forbidden error was returned while attempting to retrieve an access ' +
'token for the Compute Engine built-in service account. This may be because the Compute ' +
'Engine instance does not have the correct permission scopes specified.';
} else if (response.statusCode === 404) {
helpfulMessage =
'A Not Found error was returned while attempting to retrieve an access' +
'token for the Compute Engine built-in service account. This may be because the Compute ' +
'Engine instance does not have any permission scopes specified.';
}
if (helpfulMessage) {
if (err && err.message) {
helpfulMessage += ' ' + err.message;
}

if (err) {
err.message = helpfulMessage;
} else {
err = new Error(helpfulMessage);
(err as RequestError).code = response.statusCode;
protected requestAsync<T>(opts: AxiosRequestConfig, retry = false):
AxiosPromise<T> {
return super.requestAsync<T>(opts, retry).catch(e => {
const res = (e as AxiosError).response;
if (res && res.status) {
let helpfulMessage = null;
if (res.status === 403) {
helpfulMessage =
'A Forbidden error was returned while attempting to retrieve an access ' +
'token for the Compute Engine built-in service account. This may be because the Compute ' +
'Engine instance does not have the correct permission scopes specified.';
} else if (res.status === 404) {
helpfulMessage =
'A Not Found error was returned while attempting to retrieve an access' +
'token for the Compute Engine built-in service account. This may be because the Compute ' +
'Engine instance does not have any permission scopes specified.';
}
if (helpfulMessage) {
if (e && e.message && !retry) {
helpfulMessage += ' ' + e.message;
}
if (e) {
e.message = helpfulMessage;
} else {
e = new Error(helpfulMessage);
(e as RequestError).code = res.status.toString();
}
}
}
}
callback(err, result, response);
throw e;
});
}
}
9 changes: 8 additions & 1 deletion src/auth/credentials.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,17 @@
*/

export interface Credentials {
refresh_token?: string|null;
expiry_date?: number|null;
access_token?: string|null;
token_type?: string|null;
}

export interface CredentialRequest {
refresh_token?: string;
expiry_date?: number;
access_token?: string;
token_type?: string;
expires_in?: number;
}

export interface JWTInput {
Expand Down
Loading

0 comments on commit 98b2b1a

Please sign in to comment.