|
| 1 | +const { Project } = require('@urbackend/common/src/models'); |
| 2 | +const { forwardToPythonService } = require('../utils/internalPythonClient'); |
| 3 | +const { AppError } = require('@urbackend/common'); |
| 4 | + |
| 5 | +/** |
| 6 | + * Controller to handle AI Query Builder requests. |
| 7 | + */ |
| 8 | +const queryBuilder = async (req, res, next) => { |
| 9 | + try { |
| 10 | + const { projectId } = req.params; |
| 11 | + const { collectionName, prompt } = req.body; |
| 12 | + |
| 13 | + const mongoose = require('mongoose'); |
| 14 | + if (!mongoose.Types.ObjectId.isValid(projectId)) { |
| 15 | + throw new AppError(400, "Invalid project ID"); |
| 16 | + } |
| 17 | + |
| 18 | + if (typeof collectionName !== 'string' || typeof prompt !== 'string') { |
| 19 | + throw new AppError(400, "Collection name and prompt must be strings"); |
| 20 | + } |
| 21 | + |
| 22 | + const safeCollectionName = collectionName.trim(); |
| 23 | + const safePrompt = prompt.trim(); |
| 24 | + |
| 25 | + if (!safeCollectionName || !safePrompt) { |
| 26 | + throw new AppError(400, "Collection name and prompt are required"); |
| 27 | + } |
| 28 | + |
| 29 | + if (safeCollectionName === 'users') { |
| 30 | + throw new AppError(403, "Cannot query the users collection via AI"); |
| 31 | + } |
| 32 | + |
| 33 | + // 1. Fetch the project and specifically the requested collection schema |
| 34 | + const project = await Project.findOne( |
| 35 | + { _id: projectId, owner: req.user._id, "collections.name": safeCollectionName }, |
| 36 | + { "collections.$": 1 } |
| 37 | + ); |
| 38 | + |
| 39 | + if (!project || !project.collections || project.collections.length === 0) { |
| 40 | + throw new AppError(404, "Collection not found or access denied"); |
| 41 | + } |
| 42 | + |
| 43 | + const collection = project.collections[0]; |
| 44 | + const allowedFields = new Set([ |
| 45 | + ...collection.model.map(field => field.key), |
| 46 | + '_id', |
| 47 | + 'createdAt', |
| 48 | + 'updatedAt' |
| 49 | + ]); |
| 50 | + |
| 51 | + // 2. Extract simplified schema fields for the LLM |
| 52 | + // We only send key and type to save tokens and prevent confusion |
| 53 | + const schemaFields = collection.model.map(field => ({ |
| 54 | + key: field.key, |
| 55 | + type: field.type |
| 56 | + })); |
| 57 | + |
| 58 | + // Add implicit MongoDB fields |
| 59 | + schemaFields.push( |
| 60 | + { key: "_id", type: "OBJECTID" }, |
| 61 | + { key: "createdAt", type: "DATE" }, |
| 62 | + { key: "updatedAt", type: "DATE" } |
| 63 | + ); |
| 64 | + |
| 65 | + // 3. Forward request to Python Service |
| 66 | + const aiResponse = await forwardToPythonService('/ai/query-builder', { |
| 67 | + prompt: safePrompt, |
| 68 | + schema_fields: schemaFields |
| 69 | + }); |
| 70 | + |
| 71 | + // 4. Return the structured JSON to the frontend |
| 72 | + // Ensure filters is always an array to prevent frontend crash |
| 73 | + const rawFilters = Array.isArray(aiResponse.filters) ? aiResponse.filters : []; |
| 74 | + const allowedOperators = new Set(['=', '_gt', '_lt', '_gte', '_lte', '_ne', '_regex']); |
| 75 | + const safeFilters = rawFilters.filter(f => { |
| 76 | + const isPrimitiveValue = ['string', 'number', 'boolean'].includes(typeof f?.value); |
| 77 | + return ( |
| 78 | + f && |
| 79 | + typeof f.field === 'string' && |
| 80 | + typeof f.operator === 'string' && |
| 81 | + allowedFields.has(f.field) && |
| 82 | + allowedOperators.has(f.operator) && |
| 83 | + isPrimitiveValue |
| 84 | + ); |
| 85 | + }); |
| 86 | + |
| 87 | + res.status(200).json({ |
| 88 | + success: true, |
| 89 | + data: { |
| 90 | + filters: safeFilters, |
| 91 | + sort: typeof aiResponse.sort === 'string' ? aiResponse.sort : '-createdAt' |
| 92 | + }, |
| 93 | + message: "Query built successfully" |
| 94 | + }); |
| 95 | + |
| 96 | + } catch (error) { |
| 97 | + // Forward expected AppErrors |
| 98 | + if (error instanceof AppError) { |
| 99 | + return next(error); |
| 100 | + } |
| 101 | + |
| 102 | + // Wrap Python/Axios errors |
| 103 | + if (error.response && error.response.data) { |
| 104 | + console.error("AI Service returned error:", error.response.status, error.response.data); |
| 105 | + |
| 106 | + let errorMessage = "AI Service Error"; |
| 107 | + if (typeof error.response.data === 'string') { |
| 108 | + errorMessage = error.response.data; |
| 109 | + } else if (error.response.data.detail) { |
| 110 | + errorMessage = typeof error.response.data.detail === 'string' ? error.response.data.detail : JSON.stringify(error.response.data.detail); |
| 111 | + } else { |
| 112 | + errorMessage = JSON.stringify(error.response.data); |
| 113 | + } |
| 114 | + |
| 115 | + return next(new AppError(error.response.status || 500, errorMessage)); |
| 116 | + } |
| 117 | + |
| 118 | + next(new AppError(500, "Failed to build query via AI")); |
| 119 | + } |
| 120 | +}; |
| 121 | + |
| 122 | +module.exports = { |
| 123 | + queryBuilder |
| 124 | +}; |
0 commit comments