Skip to content

Commit

Permalink
chore(commons): update Powertools UA middleware detection (#1762)
Browse files Browse the repository at this point in the history
* chore(commons): fix double ua detection

* chore(commons): fix unit test
  • Loading branch information
dreamorosi authored Oct 21, 2023
1 parent 665fff4 commit 68fc758
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 8 deletions.
25 changes: 18 additions & 7 deletions packages/commons/src/awsSdk/userAgentMiddleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,25 @@ const customUserAgentMiddleware = (feature: string) => {
};
};

/**
* @internal
* Checks if the middleware stack already has the Powertools UA middleware
*/
const hasPowertools = (middlewareStack: string[]): boolean => {
let found = false;
for (const middleware of middlewareStack) {
if (middleware.includes('addPowertoolsToUserAgent')) {
found = true;
}
}

return found;
};

const addUserAgentMiddleware = (client: unknown, feature: string): void => {
try {
if (isSdkClient(client)) {
if (
client.middlewareStack
.identify()
.includes('addPowertoolsToUserAgent: POWERTOOLS,USER_AGENT')
) {
if (hasPowertools(client.middlewareStack.identify())) {
return;
}
client.middlewareStack.addRelativeTo(
Expand All @@ -49,8 +60,8 @@ const addUserAgentMiddleware = (client: unknown, feature: string): void => {
`The client provided does not match the expected interface`
);
}
} catch (e) {
console.warn('Failed to add user agent middleware', e);
} catch (error) {
console.warn('Failed to add user agent middleware', error);
}
};

Expand Down
4 changes: 3 additions & 1 deletion packages/commons/tests/unit/awsSdk.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,9 @@ describe('Helpers: awsSdk', () => {
// Prepare
const client = {
middlewareStack: {
identify: () => 'addPowertoolsToUserAgent: POWERTOOLS,USER_AGENT',
identify: () => [
'addPowertoolsToUserAgent: after getUserAgentMiddleware',
],
addRelativeTo: jest.fn(),
},
send: jest.fn(),
Expand Down

0 comments on commit 68fc758

Please sign in to comment.