Created
May 28, 2024 17:21
-
-
Save gtrabanco/5a93c6b97bd768f4431cef5c7c71e137 to your computer and use it in GitHub Desktop.
Import function to send as string with post method
This file contains 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
import { existsSync } from 'node:fs'; | |
export async function importDefaultFunctionOrFunctionAsEdgeFunction(filePathOrFn: string | Function) { | |
let fnString = filePathOrFn; | |
if (typeof filePathOrFn === "string" && existsSync(filePathOrFn)) { | |
const { default: fn } = await import(filePathOrFn); | |
fnString = fn.toString(); | |
} | |
return `export default async function({ page, context }) { | |
const { | |
cookies = [], | |
userAgent = undefined, | |
userAgentMetadata = undefined, | |
sessionStorage: localValues = [], | |
localStorage: sessionValues = [], | |
...params | |
} = context ?? {}; | |
if(userAgent) { | |
page.setUserAgent(userAgent, userAgentMetadata); | |
} | |
await page.setCookie(...cookies); | |
if( localValues.lenght > 0 || sessionStorage.lenght > 0 ) { | |
await page.evaluate(({ localValues = [], sessionValues = [] } = {}) => { | |
for (const [key, value] of Object.entries(localValues)) { | |
localStorage.setItem(key, value); | |
} | |
for (const [key, value] of Object.entries(sessionValues)) { | |
sessionStorage.setItem(key, value); | |
} | |
}, { localValues, sessionValues }); | |
} | |
const promisedFnCall = (${fnString})({ page, context: params }); | |
const result = await Promise.resolve(promisedFnCall); | |
const storageValues = await page.evaluate(() => { | |
const local = JSON.parse(JSON.stringify(localStorage ?? [])); | |
const session = JSON.parse(JSON.stringify(sessionStorage ?? [])); | |
return { local, session} | |
}); | |
return { | |
data: result, | |
url: page.url(), | |
cookies: await page.cookies(), | |
localStorage: storageValues.local, | |
sessionStorage: storageValues.session, | |
type: "application/json", | |
} | |
}` | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment