61 lines
1.4 KiB
TypeScript
61 lines
1.4 KiB
TypeScript
import axios from "axios";
|
|
|
|
const agentid = process.env.AGENT_ID;
|
|
|
|
axios.defaults.headers.common["X-Phantombuster-Key"] = process.env
|
|
.API_KEY as string;
|
|
axios.defaults.headers.common["Content-Type"] = "application/json";
|
|
|
|
const MAX_TIME_TO_RUN = 10000;
|
|
|
|
type FetchOutputResult = {
|
|
containerId: string;
|
|
status: string;
|
|
output: string;
|
|
outputPos: number;
|
|
mostRecentEndedAt: number;
|
|
isAgentRunning: boolean;
|
|
canSoftAbort: boolean;
|
|
};
|
|
|
|
async function getUntilRunStop(
|
|
url: string,
|
|
startTime: number
|
|
): Promise<FetchOutputResult> {
|
|
const timeRunning = Date.now() - startTime;
|
|
|
|
if (timeRunning > MAX_TIME_TO_RUN) {
|
|
throw new Error("TIMEOUT: phantom run for too long");
|
|
}
|
|
|
|
return await axios
|
|
.get<FetchOutputResult>(url)
|
|
.then((res) =>
|
|
res.data.status !== "finished"
|
|
? getUntilRunStop(url, startTime)
|
|
: res.data
|
|
);
|
|
}
|
|
|
|
axios
|
|
.post<{ containerId: string }>(
|
|
"https://api.phantombuster.com/api/v2/agents/launch",
|
|
{ id: agentid }
|
|
)
|
|
.then((res) => res.data.containerId)
|
|
.then(() =>
|
|
getUntilRunStop(
|
|
`https://api.phantombuster.com/api/v2/agents/fetch-output?id=${agentid}`,
|
|
Date.now()
|
|
)
|
|
.then(console.log)
|
|
.catch(async (err) => {
|
|
console.error(err);
|
|
console.log("stopping agent");
|
|
await axios.post("https://api.phantombuster.com/api/v2/agents/stop", {
|
|
id: agentid,
|
|
});
|
|
process.exit();
|
|
})
|
|
);
|