-
Notifications
You must be signed in to change notification settings - Fork 5
Relocates OAuth token management #12
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,152 @@ | ||
| /** | ||
| * Base HTTP Client for SFCC API requests | ||
| * | ||
| * This module provides a foundation for making authenticated HTTP requests to SFCC APIs. | ||
| * It handles common concerns like authentication, request/response formatting, and error handling. | ||
| */ | ||
|
|
||
| import { Logger } from '../../utils/logger.js'; | ||
|
|
||
| /** | ||
| * HTTP request options interface | ||
| */ | ||
| export interface HttpRequestOptions extends RequestInit { | ||
| headers?: Record<string, string>; | ||
| } | ||
|
|
||
| /** | ||
| * Base HTTP client for SFCC API communication | ||
| */ | ||
| export abstract class BaseHttpClient { | ||
| protected baseUrl: string; | ||
| protected logger: Logger; | ||
|
|
||
| constructor(baseUrl: string, loggerContext: string) { | ||
| this.baseUrl = baseUrl; | ||
| this.logger = new Logger(loggerContext); | ||
| } | ||
|
|
||
| /** | ||
| * Get authentication headers - must be implemented by subclasses | ||
| */ | ||
| protected abstract getAuthHeaders(): Promise<Record<string, string>>; | ||
|
|
||
| /** | ||
| * Handle authentication errors - can be overridden by subclasses | ||
| */ | ||
| protected async handleAuthError(): Promise<void> { | ||
| // Default implementation does nothing | ||
| // Subclasses can override to clear tokens, retry, etc. | ||
| } | ||
|
|
||
| /** | ||
| * Make an authenticated HTTP request | ||
| */ | ||
| protected async makeRequest<T>( | ||
| endpoint: string, | ||
| options: HttpRequestOptions = {}, | ||
| ): Promise<T> { | ||
| const url = `${this.baseUrl}${endpoint}`; | ||
| const method = options.method ?? 'GET'; | ||
|
|
||
| this.logger.debug(`Making ${method} request to: ${endpoint}`); | ||
|
|
||
| // Get authentication headers | ||
| const authHeaders = await this.getAuthHeaders(); | ||
|
|
||
| const requestOptions: RequestInit = { | ||
| ...options, | ||
| headers: { | ||
| 'Content-Type': 'application/json', | ||
| ...authHeaders, | ||
| ...options.headers, | ||
| }, | ||
| }; | ||
|
|
||
| try { | ||
| const response = await fetch(url, requestOptions); | ||
|
|
||
| if (!response.ok) { | ||
| // Handle authentication errors | ||
| if (response.status === 401) { | ||
| this.logger.debug('Received 401, attempting to handle auth error'); | ||
| await this.handleAuthError(); | ||
|
|
||
| // Retry with fresh authentication | ||
| const newAuthHeaders = await this.getAuthHeaders(); | ||
| requestOptions.headers = { | ||
| ...requestOptions.headers, | ||
| ...newAuthHeaders, | ||
| }; | ||
|
|
||
| const retryResponse = await fetch(url, requestOptions); | ||
| if (!retryResponse.ok) { | ||
| const errorText = await retryResponse.text(); | ||
| throw new Error( | ||
| `Request failed after retry: ${retryResponse.status} ${retryResponse.statusText} - ${errorText}`, | ||
| ); | ||
| } | ||
|
|
||
| this.logger.debug('Retry request successful'); | ||
| return retryResponse.json(); | ||
| } | ||
|
|
||
| const errorText = await response.text(); | ||
| throw new Error(`Request failed: ${response.status} ${response.statusText} - ${errorText}`); | ||
| } | ||
|
|
||
| this.logger.debug(`Request to ${endpoint} completed successfully`); | ||
| return response.json(); | ||
| } catch (error) { | ||
| this.logger.error(`Network error during request to ${endpoint}: ${error}`); | ||
| throw error; | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * GET request | ||
| */ | ||
| protected async get<T>(endpoint: string): Promise<T> { | ||
| return this.makeRequest<T>(endpoint, { method: 'GET' }); | ||
| } | ||
|
|
||
| /** | ||
| * POST request | ||
| */ | ||
| protected async post<T>(endpoint: string, data?: any): Promise<T> { | ||
| const options: HttpRequestOptions = { method: 'POST' }; | ||
| if (data) { | ||
| options.body = JSON.stringify(data); | ||
| } | ||
| return this.makeRequest<T>(endpoint, options); | ||
| } | ||
|
|
||
| /** | ||
| * PUT request | ||
| */ | ||
| protected async put<T>(endpoint: string, data?: any): Promise<T> { | ||
| const options: HttpRequestOptions = { method: 'PUT' }; | ||
| if (data) { | ||
| options.body = JSON.stringify(data); | ||
| } | ||
| return this.makeRequest<T>(endpoint, options); | ||
| } | ||
|
|
||
| /** | ||
| * PATCH request | ||
| */ | ||
| protected async patch<T>(endpoint: string, data?: any): Promise<T> { | ||
| const options: HttpRequestOptions = { method: 'PATCH' }; | ||
| if (data) { | ||
| options.body = JSON.stringify(data); | ||
| } | ||
| return this.makeRequest<T>(endpoint, options); | ||
| } | ||
|
|
||
| /** | ||
| * DELETE request | ||
| */ | ||
| protected async delete<T>(endpoint: string): Promise<T> { | ||
| return this.makeRequest<T>(endpoint, { method: 'DELETE' }); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
| @@ -0,0 +1,120 @@ | ||||||
| /** | ||||||
| * OCAPI Authentication Client | ||||||
| * | ||||||
| * This module handles OAuth 2.0 authentication specifically for SFCC OCAPI requests. | ||||||
| * It extends the base HTTP client with OCAPI-specific authentication logic. | ||||||
| */ | ||||||
|
|
||||||
| import { OCAPIConfig, OAuthTokenResponse } from '../../types/types.js'; | ||||||
| import { TokenManager } from './oauth-token.js'; | ||||||
| import { BaseHttpClient } from './http-client.js'; | ||||||
|
|
||||||
| // OCAPI authentication constants | ||||||
| const OCAPI_AUTH_CONSTANTS = { | ||||||
| AUTH_URL: 'https://account.demandware.com/dwsso/oauth2/access_token', | ||||||
| GRANT_TYPE: 'client_credentials', | ||||||
| FORM_CONTENT_TYPE: 'application/x-www-form-urlencoded', | ||||||
| } as const; | ||||||
|
|
||||||
| /** | ||||||
| * OCAPI Authentication Client | ||||||
| * Handles OAuth 2.0 Client Credentials flow for OCAPI access | ||||||
| */ | ||||||
| export class OCAPIAuthClient extends BaseHttpClient { | ||||||
| private config: OCAPIConfig; | ||||||
| private tokenManager: TokenManager; | ||||||
|
|
||||||
| constructor(config: OCAPIConfig) { | ||||||
| super('', 'OCAPIAuthClient'); // Initialize BaseHttpClient with logger | ||||||
|
||||||
| super('', 'OCAPIAuthClient'); // Initialize BaseHttpClient with logger | |
| super(OCAPI_AUTH_CONSTANTS.AUTH_URL, 'OCAPIAuthClient'); // Initialize BaseHttpClient with logger and baseUrl |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[nitpick] Consider extracting the method assignment outside the log statement to improve readability and make debugging easier.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Not needed