Skip to content

Commit

Permalink
Updating comments
Browse files Browse the repository at this point in the history
  • Loading branch information
erdimaden committed May 14, 2024
1 parent f044870 commit ea3e0e5
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 23 deletions.
25 changes: 12 additions & 13 deletions src/coinbase/authenticator.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { JWK, JWS } from "node-jose";
import { InternalError, InvalidAPIKeyFormat } from "./errors";
import { InternalAxiosRequestConfig } from "axios";
import { JWK, JWS } from "node-jose";
import { InvalidAPIKeyFormat } from "./errors";

const pemHeader = "-----BEGIN EC PRIVATE KEY-----";
const pemFooter = "-----END EC PRIVATE KEY-----";
Expand All @@ -22,32 +22,31 @@ export class CoinbaseAuthenticator {
}

/**
* Middleware to intercept requests and add JWT to the Authorization header for AxiosInterceptor
* Middleware to intercept requests and add JWT to Authorization header.
* @param {MiddlewareRequestType} config - The request configuration.
* @returns {MiddlewareRequestType} The request configuration with the Authorization header added.
* @throws {InternalError} If there is an issue with the private key.
* @throws {InvalidAPIKeyFormat} If JWT could not be built.
*/
async authenticateRequest(
config: InternalAxiosRequestConfig,
debug = false,
debugging = false,
): Promise<InternalAxiosRequestConfig> {
const method = config.method?.toString().toUpperCase();
const token = await this.buildJWT(config.url || "", method);
if (debug) {
if (debugging) {
console.log(`API REQUEST: ${method} ${config.url}`);
}

config.headers["Authorization"] = `Bearer ${token}`;
config.headers["Content-Type"] = "application/json";
return config;
}

/**
* Builds the JWT for the given API endpoint URI. The JWT is signed with the API key's private key.
* @param {string} url - The URI of the API endpoint.
* @param {string} method - The HTTP method of the request.
* @returns {string} The JWT if successful or throws an error.
* @throws {InvalidAPIKeyFormat} If there is an issue with the private key.
* Builds the JWT for the given API endpoint URL.
* @param {string} url - URL of the API endpoint.
* @param {string} method - HTTP method of the request.
* @returns {string} JWT token.
* @throws {InvalidAPIKeyFormat} If the private key is not in the correct format.
*/
async buildJWT(url: string, method = "GET"): Promise<string> {
const pemPrivateKey = this.extractPemKey(this.privateKey);
Expand Down Expand Up @@ -87,7 +86,7 @@ export class CoinbaseAuthenticator {

return result as unknown as string;
} catch (err) {
throw new InternalError("Could not sign the JWT");
throw new InvalidAPIKeyFormat("Could not sign the JWT");
}
}

Expand Down
18 changes: 11 additions & 7 deletions src/coinbase/coinbase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { CoinbaseAuthenticator } from "./authenticator";
import { ApiClients } from "./types";
import { User } from "./user";
import { logApiResponse } from "./utils";
import { InternalError, InvalidConfiguration } from "./errors";
import { InvalidAPIKeyFormat, InvalidConfiguration } from "./errors";

// The Coinbase SDK.
export class Coinbase {
Expand All @@ -18,6 +18,10 @@ export class Coinbase {
* @constructor
* @param {string} apiKeyName - The API key name.
* @param {string} privateKey - The private key associated with the API key.
* @param {boolean} debugging - If true, logs API requests and responses to the console.
* @param {string} basePath - The base path for the API.
* @throws {InvalidConfiguration} If the configuration is invalid.
* @throws {InvalidAPIKeyFormat} If not able to create JWT token.
*/
constructor(
apiKeyName: string,
Expand All @@ -41,35 +45,35 @@ export class Coinbase {
}

/**
* Reads the API key and private key from a JSON file and returns a new instance of Coinbase.
* Reads the API key and private key from a JSON file and initializes the Coinbase SDK.
* @param {string} filePath - The path to the JSON file containing the API key and private key.
* @returns {Coinbase} A new instance of the Coinbase SDK.
* @throws {InternalError} If the file does not exist or the configuration values are missing.
* @throws {InvalidAPIKeyFormat} If the file does not exist or the configuration values are missing/invalid.
*/
static fromJsonConfig(
filePath: string = "coinbase_cloud_api_key.json",
debugging = false,
basePath: string = BASE_PATH,
): Coinbase {
if (!fs.existsSync(filePath)) {
throw new InternalError(`Invalid configuration: file not found at ${filePath}`);
throw new InvalidAPIKeyFormat(`Invalid configuration: file not found at ${filePath}`);
}
try {
const data = fs.readFileSync(filePath, "utf8");
const config = JSON.parse(data);
if (!config.name || !config.privateKey) {
throw new InternalError("Invalid configuration: missing configuration values");
throw new InvalidAPIKeyFormat("Invalid configuration: missing configuration values");
}

// Return a new instance of Coinbase
return new Coinbase(config.name, config.privateKey, debugging, basePath);
} catch (e) {
throw new InternalError(`Not able to parse the configuration file`);
throw new InvalidAPIKeyFormat(`Not able to parse the configuration file`);
}
}

/**
* Returns the default user.
* Returns User model for the default user.
* @returns {User} The default user.
* @throws {Error} If the user is not found or HTTP request fails.
*/
Expand Down
4 changes: 2 additions & 2 deletions src/coinbase/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ import { AxiosPromise } from "axios";
import { User as UserModel } from "./../client/api";

/**
* The User API client type definition
* UserAPI client type definition
*/
export type UserAPIClient = { getCurrentUser(options?): AxiosPromise<UserModel> };

/**
* The API clients type definition for the Coinbase SDK
* API clients type definition for the Coinbase SDK
*/
export type ApiClients = {
user?: UserAPIClient;
Expand Down
2 changes: 1 addition & 1 deletion src/coinbase/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { AxiosResponse } from "axios";

/**
* Prints Axios response to the console for debugging purposes.
* @param response
* @param response - The Axios response object.
*/
export const logApiResponse = (response: AxiosResponse, debugging = false): AxiosResponse => {
if (debugging) {
Expand Down

0 comments on commit ea3e0e5

Please sign in to comment.