Skip to content

Commit 74d8064

Browse files
committed
fix: Add logging interceptors for request and response in stack function
1 parent 026d7bc commit 74d8064

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

src/lib/contentstack.ts

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,67 @@ export function stack(config: StackConfig): StackClass {
104104
});
105105
};
106106
}
107+
// LogHandler interceptors
108+
if (config.debug) {
109+
// Request interceptor for logging
110+
client.interceptors.request.use((requestConfig: any) => {
111+
config.logHandler!('info', {
112+
type: 'request',
113+
method: requestConfig.method?.toUpperCase(),
114+
url: requestConfig.url,
115+
headers: requestConfig.headers,
116+
params: requestConfig.params,
117+
timestamp: new Date().toISOString()
118+
});
119+
return requestConfig;
120+
});
121+
122+
// Response interceptor for logging
123+
client.interceptors.response.use(
124+
(response: any) => {
125+
const level = getLogLevelFromStatus(response.status);
126+
config.logHandler!(level, {
127+
type: 'response',
128+
status: response.status,
129+
statusText: response.statusText,
130+
url: response.config?.url,
131+
method: response.config?.method?.toUpperCase(),
132+
headers: response.headers,
133+
data: response.data,
134+
timestamp: new Date().toISOString()
135+
});
136+
return response;
137+
},
138+
(error: any) => {
139+
const status = error.response?.status || 0;
140+
const level = getLogLevelFromStatus(status);
141+
config.logHandler!(level, {
142+
type: 'response_error',
143+
status: status,
144+
statusText: error.response?.statusText || error.message,
145+
url: error.config?.url,
146+
method: error.config?.method?.toUpperCase(),
147+
error: error.message,
148+
timestamp: new Date().toISOString()
149+
});
150+
throw error;
151+
}
152+
);
153+
}
154+
155+
// Helper function to determine log level based on HTTP status code
156+
function getLogLevelFromStatus(status: number): string {
157+
if (status >= 200 && status < 300) {
158+
return 'info';
159+
} else if (status >= 300 && status < 500) {
160+
return 'warn';
161+
} else if (status >= 500) {
162+
return 'error';
163+
} else {
164+
return 'debug';
165+
}
166+
}
167+
107168
// Retry policy handlers
108169
const errorHandler = (error: any) => {
109170
return retryResponseErrorHandler(error, config, client);

0 commit comments

Comments
 (0)