Skip to content

Commit

Permalink
fix(core): patch global fetch to write http logs
Browse files Browse the repository at this point in the history
  • Loading branch information
eliangcs committed Oct 29, 2024
1 parent 5d30882 commit 853d362
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
2 changes: 2 additions & 0 deletions packages/core/src/tools/create-lambda-handler.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ const createInput = require('./create-input');
const createLogger = require('./create-logger');
const createRpcClient = require('./create-rpc-client');
const environmentTools = require('./environment');
const patchGlobalFetch = require('./patch-global-fetch');
const schemaTools = require('./schema');
const ZapierPromise = require('./promise');

Expand Down Expand Up @@ -260,6 +261,7 @@ const createLambdaHandler = (appRawOrPath) => {
const httpPatch = createHttpPatch(event);
httpPatch(require('http'), logger);
httpPatch(require('https'), logger); // 'https' needs to be patched separately
patchGlobalFetch(logger);
}

// TODO: Avoid calling prepareApp(appRaw) repeatedly here as createApp()
Expand Down
51 changes: 51 additions & 0 deletions packages/core/src/tools/patch-global-fetch.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
const { ALLOWED_HTTP_DATA_CONTENT_TYPES, getContentType } = require('./http');

const normalizeRequestInfo = (input, init) => {
if (typeof input === 'string') {
const headers = init.headers || {};
const contentType = getContentType(headers);
const shouldIncludeData = ALLOWED_HTTP_DATA_CONTENT_TYPES.has(contentType);
return {
url: input,
method: init.method || 'GET',
headers: init.headers || {},
data: shouldIncludeData ? init.body || '' : '<unsupported format>',
};
} else if (input instanceof Request) {
// TODO: Handle Request object
return null;
}
return null;
};

const patchGlobalFetch = (logger) => {
if (!global.fetch || global.fetch.patchedByZapier) {
return;
}

const originalFetch = global.fetch;

global.fetch = async function (input, init) {
const response = await originalFetch(input, init);
const requestInfo = normalizeRequestInfo(input, init);
if (requestInfo) {
logger(`${response.status} ${requestInfo.method} ${requestInfo.url}`, {
log_type: 'http',
request_type: 'patched-devplatform-outbound',
request_url: requestInfo.url,
request_method: requestInfo.method,
request_headers: requestInfo.headers,
request_data: requestInfo.data,
request_via_client: false,
response_status_code: response.status,
response_headers: Object.fromEntries(response.headers.entries()),
// response_content: response.body,
});
}
return response;
};

global.fetch.patchedByZapier = true;
};

module.exports = patchGlobalFetch;

0 comments on commit 853d362

Please sign in to comment.