Files
firecrawl/apps/api/src/controllers/v1/batch-scrape.ts
T

97 lines
2.3 KiB
TypeScript
Raw Normal View History

2024-10-17 19:40:18 +02:00
import { Response } from "express";
import { v4 as uuidv4 } from "uuid";
import {
2024-10-23 15:37:24 -03:00
BatchScrapeRequest,
batchScrapeRequestSchema,
2024-10-17 19:40:18 +02:00
CrawlResponse,
RequestWithAuth,
} from "./types";
import {
addCrawlJobs,
lockURLs,
saveCrawl,
StoredCrawl,
} from "../../lib/crawl-redis";
import { logCrawl } from "../../services/logging/crawl_log";
import { getScrapeQueue } from "../../services/queue-service";
import { getJobPriority } from "../../lib/job-priority";
2024-10-25 20:21:12 +02:00
import { addScrapeJobs } from "../../services/queue-jobs";
2024-10-17 19:40:18 +02:00
2024-10-23 15:37:24 -03:00
export async function batchScrapeController(
req: RequestWithAuth<{}, CrawlResponse, BatchScrapeRequest>,
2024-10-17 19:40:18 +02:00
res: Response<CrawlResponse>
) {
2024-10-23 15:37:24 -03:00
req.body = batchScrapeRequestSchema.parse(req.body);
2024-10-17 19:40:18 +02:00
const id = uuidv4();
await logCrawl(id, req.auth.team_id);
2024-11-07 20:57:33 +01:00
let { remainingCredits } = req.account!;
2024-10-17 19:40:18 +02:00
const useDbAuthentication = process.env.USE_DB_AUTHENTICATION === 'true';
if(!useDbAuthentication){
remainingCredits = Infinity;
}
const sc: StoredCrawl = {
crawlerOptions: null,
2024-11-07 20:57:33 +01:00
scrapeOptions: req.body,
internalOptions: {},
2024-10-17 19:40:18 +02:00
team_id: req.auth.team_id,
createdAt: Date.now(),
plan: req.auth.plan,
};
await saveCrawl(id, sc);
let jobPriority = 20;
// If it is over 1000, we need to get the job priority,
// otherwise we can use the default priority of 20
if(req.body.urls.length > 1000){
// set base to 21
jobPriority = await getJobPriority({plan: req.auth.plan, team_id: req.auth.team_id, basePriority: 21})
}
const jobs = req.body.urls.map((x) => {
return {
data: {
url: x,
2024-10-25 20:21:12 +02:00
mode: "single_urls" as const,
2024-10-17 19:40:18 +02:00
team_id: req.auth.team_id,
2024-11-07 20:57:33 +01:00
plan: req.auth.plan!,
2024-10-17 19:40:18 +02:00
crawlerOptions: null,
2024-11-07 20:57:33 +01:00
scrapeOptions: req.body,
2024-10-17 19:40:18 +02:00
origin: "api",
crawl_id: id,
sitemapped: true,
v1: true,
},
opts: {
2024-10-25 20:21:12 +02:00
jobId: uuidv4(),
2024-10-17 19:40:18 +02:00
priority: 20,
},
};
});
await lockURLs(
id,
jobs.map((x) => x.data.url)
);
await addCrawlJobs(
id,
jobs.map((x) => x.opts.jobId)
);
2024-10-25 20:21:12 +02:00
await addScrapeJobs(jobs);
2024-10-17 19:40:18 +02:00
const protocol = process.env.ENV === "local" ? req.protocol : "https";
return res.status(200).json({
success: true,
id,
2024-10-23 15:37:24 -03:00
url: `${protocol}://${req.get("host")}/v1/batch/scrape/${id}`,
2024-10-17 19:40:18 +02:00
});
}