Skip to content

Commit

Permalink
Respect api key header config (#196)
Browse files Browse the repository at this point in the history
respect api key header config
  • Loading branch information
0xmaayan authored Nov 17, 2023
1 parent 7b6e1cc commit 2ea8589
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 4 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ All notable changes to the Aptos TypeScript SDK will be captured in this file. T

# Unreleased

- Respect `API_KEY` option in `clientConfig` when making indexer and/or fullnode queries

## 0.0.7 (2023-11-16)

- Adds additional ANS APIs
Expand Down
10 changes: 6 additions & 4 deletions src/client/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ export async function request<Req, Res>(options: ClientRequest<Req>, client: Cli
if (overrides?.AUTH_TOKEN && url.includes("faucet")) {
headers.Authorization = `Bearer ${overrides?.AUTH_TOKEN}`;
}
if (overrides?.API_KEY && !url.includes("faucet")) {
headers.Authorization = `Bearer ${overrides?.API_KEY}`;
}

/*
* make a call using the @aptos-labs/aptos-client package
Expand Down Expand Up @@ -99,15 +102,14 @@ export async function aptosRequest<Req extends {}, Res extends {}>(

let errorMessage: string;

// If it is the shape of an AptosApiError, convert it properly
if ("message" in response.data && "error_code" in response.data) {
errorMessage = JSON.stringify(response.data);
if (result && result.data && "message" in result.data && "error_code" in result.data) {
errorMessage = JSON.stringify(result.data);
} else if (result.status in errors) {
// If it's not an API type, it must come form infra, these are prehandled
errorMessage = errors[result.status];
} else {
// Everything else is unhandled
errorMessage = `Unhandled Error ${response.status} : ${response.statusText}`;
errorMessage = `Unhandled Error ${result.status} : ${result.statusText}`;
}

throw new AptosApiError(options, result, errorMessage);
Expand Down
25 changes: 25 additions & 0 deletions tests/e2e/client/aptosRequest.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,31 @@ describe("aptos request", () => {
);
});

describe("api key", () => {
test(
"should set api_token for full node requests",
async () => {
try {
const response = await aptosRequest(
{
url: `${NetworkToNodeAPI[config.network]}`,
method: "GET",
path: "accounts/0x1",
overrides: { API_KEY: "my-api-key" },
originMethod: "test when token is set",
},
config,
);
expect(response.config.headers).toHaveProperty("authorization", "Bearer my-api-key");
} catch (error: any) {
// should not get here
expect(true).toBe(false);
}
},
longTestTimeout,
);
});

describe("full node", () => {
describe("200 response", () => {
test(
Expand Down

0 comments on commit 2ea8589

Please sign in to comment.