All files / services/crawler-service-api/src/routes index.js

49.45% Statements 91/184
30% Branches 3/10
100% Functions 0/0
49.45% Lines 91/184

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 1851x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x     4x 4x 4x 4x 4x 4x 4x 4x               1x 1x 1x 1x                                                                                                                     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     1x 1x 1x 1x           1x 1x 1x 1x           1x 1x 1x 1x 1x 1x 1x               1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x               1x 1x 1x  
/**
 * Crawler API routes
 */
 
const express = require('express');
const { v4: uuidv4 } = require('uuid');
const { CrawlerConfig } = require('../models');
const { requireAuth, getOrganizationId } = require('../middleware/auth');
const {
  launchCrawlingWorkflow,
} = require('./helpers');
 
const router = express.Router({ mergeParams: true });
 
// GET /crawlers - List all crawler configurations
router.get('/crawlers', requireAuth, async (req, res) => {
  try {
    const query = {
      isActive: true,
    };
    
    // Organisation courante : path `/:organizationId` (JWT) ou contexte gateway
    // (`x-organization-id`, API-key). On ne se fie PAS au seul claim JWT : il peut
    // être périmé après un changement d'organisation dans le sélecteur.
    const orgId = getOrganizationId(req);
    if (orgId) {
      query.organizationId = orgId;
    } else {
      query.userId = req.userId;
    }
 
    const crawlers = await CrawlerConfig.find(query).sort({ createdAt: -1 });
 
    res.json({
      success: true,
      data: crawlers,
    });
  } catch (error) {
    console.error('[CrawlerAPI] Error listing crawlers:', error);
    res.status(500).json({
      success: false,
      message: 'Error retrieving crawlers',
      error: error.message,
    });
  }
});
 
// POST /crawlers - Create a new crawler configuration
router.post('/crawlers', requireAuth, async (req, res) => {
  try {
    const { name, description, prompt, startUrl, config, organizationId } = req.body;

    if (!name) {
      return res.status(400).json({
        success: false,
        message: 'Name is required',
      });
    }

    // Accept organizationId from body (multi-tenant) or from the request context
    // (path `/:organizationId` ou header `x-organization-id`).
    const orgId = organizationId || getOrganizationId(req);
    if (!orgId) {
      return res.status(400).json({
        success: false,
        message: 'organizationId is required',
      });
    }

    const crawler = new CrawlerConfig({
      userId: req.userId,
      organizationId: orgId,
      name,
      description: description || '',
      prompt: prompt || '',
      startUrl: startUrl || '',
      config: {
        maxPages: config?.maxPages ?? 10,
        maxDepth: config?.maxDepth ?? 3,
        pageThreshold: config?.pageThreshold ?? 60,
        linkThreshold: config?.linkThreshold ?? 40,
        crawlDelay: config?.crawlDelay ?? 100,
        llmModel: config?.llmModel || 'deepseek/deepseek-v4-flash',
        reasoning: config?.reasoning !== false,
        maxTokens: config?.maxTokens ?? null,
        sameDomain: config?.sameDomain === true,
        enableSynthesis: config?.enableSynthesis !== false,
        destinations: config?.destinations || [],
      },
    });

    await crawler.save();

    res.status(201).json({
      success: true,
      message: 'Crawler configuration created successfully',
      data: crawler.toObject(),
    });
  } catch (error) {
    console.error('[CrawlerAPI] Error creating crawler:', error);

    res.status(500).json({
      success: false,
      message: 'Error creating crawler',
      error: error.message,
    });
  }
});
 
// POST /crawlers/:crawlerId/start - Start a crawling job
router.post('/crawlers/:crawlerId/start', requireAuth, async (req, res) => {
  try {
    const { crawlerId } = req.params;
    const { startUrl, scheduleId } = req.body;
 
    // Fetch configuration
    const query = {
      _id: crawlerId,
      isActive: true,
    };
    
    // Organisation courante : path `/:organizationId` (JWT) ou contexte gateway.
    const orgId = getOrganizationId(req);
    if (orgId) {
      query.organizationId = orgId;
    } else {
      query.userId = req.userId;
    }
    
    const crawlerConfig = await CrawlerConfig.findOne(query);
 
    if (!crawlerConfig) {
      return res.status(404).json({
        success: false,
        message: 'Crawler configuration not found',
      });
    }
 
    const url = startUrl || crawlerConfig.startUrl;
 
    if (!url) {
      return res.status(400).json({
        success: false,
        message: 'startUrl is required (provide in body or in crawler config)',
      });
    }
 
    const jobId = uuidv4();
 
    // Launch Temporal workflow — le job-manager crée le doc `jobs` (statut/progression)
    try {
      await launchCrawlingWorkflow(jobId, [url], crawlerConfig, req.userId, crawlerConfig.organizationId, scheduleId);
    } catch (workflowError) {
      console.error('[CrawlerAPI] Failed to launch workflow:', workflowError);
      return res.status(500).json({
        success: false,
        message: 'Failed to start crawling workflow',
        error: workflowError.message,
      });
    }
 
    // Update config run count
    crawlerConfig.runCount = (crawlerConfig.runCount || 0) + 1;
    await crawlerConfig.save();
 
    res.json({
      success: true,
      data: {
        jobId,
        status: 'running',
        crawlerId,
      },
    });
  } catch (error) {
    console.error('[CrawlerAPI] Error starting crawl:', error);
    res.status(500).json({
      success: false,
      message: 'Error starting crawling job',
      error: error.message,
    });
  }
});
 
module.exports = router;