UNPKG

@tasolutions/express-core

Version:
143 lines (119 loc) 5.54 kB
'use strict'; const _ = require('lodash'); const mongoose = require('mongoose'); module.exports = { searchByObjectIdField: async (query, req, collection) => { const { search } = req.query; if (search) { const regexSearch = { $regex: search, $options: 'i' }; const objectIdTypes = ['ObjectId', 'ObjectID']; // Lấy tất cả các trường có kiểu ObjectId từ schema const objectIdFields = Object.keys(collection.schema.tree).filter(key => { const path = collection.schema.path(key); return path && objectIdTypes.includes(path.instance) && path.options && path.options.ref; // Kiểm tra nếu có ref }); // Tìm kiếm trên mỗi trường ObjectId mà có ref for (const field of objectIdFields) { const modelName = collection.schema.path(field).options.ref; // Lấy tên model từ options.ref const Model = getModelFromRef(modelName); // Nhận mô hình // Lấy các trường của Model để tìm kiếm let keySchema = Object.keys(Model.schema.tree); keySchema = _.without(keySchema, 'id', '_id', '__v'); const keyVirtuals = Object.keys(Model.schema.virtuals); keySchema = keySchema.filter(item => !keyVirtuals.includes(item)); // Tạo điều kiện tìm kiếm cho tất cả các trường của model const searchConditions = keySchema.map(key => { const path = Model.schema.path(key); if (path && path.instance === 'String') { return { [key]: regexSearch }; // Tìm kiếm cho các trường kiểu String } return null; // Tránh thêm điều kiện nếu không phải String }).filter(condition => condition !== null); // Lọc các điều kiện null // Thực hiện tìm kiếm nếu có điều kiện if (searchConditions.length > 0) { const foundDocument = await Model.findOne({ $or: searchConditions }).select('_id'); if (foundDocument) { query[field] = foundDocument._id; // Cập nhật query với ObjectId tìm được } } } } return query; }, parseFormData: (data) => { if (!data) return {}; // Kiểm tra nếu data là array thực sự if (Array.isArray(data)) { return data; } // Kiểm tra nếu data có format object với key là index (0, 1, 2...) const keys = Object.keys(data); const numericKeys = keys.filter(key => { const num = parseInt(key); return !isNaN(num) && num >= 0; }); const nonNumericKeys = keys.filter(key => { const num = parseInt(key); return isNaN(num); }); // Nếu có numeric keys và non-numeric keys, xử lý đặc biệt if (numericKeys.length > 0 && nonNumericKeys.length > 0) { const result = { items: [], ...data }; // Chuyển numeric keys thành array items numericKeys.forEach(key => { const index = parseInt(key); result.items[index] = data[key]; }); // Xóa các numeric keys khỏi result numericKeys.forEach(key => { delete result[key]; }); return result; } // Nếu chỉ có numeric keys, chuyển về array if (numericKeys.length > 0 && nonNumericKeys.length === 0) { const result = []; numericKeys.forEach(key => { const index = parseInt(key); result[index] = data[key]; }); return result; } const result = {}; Object.keys(data).forEach(key => { const matches = key.match(/([^\[]+)\[([^\]]*)\]/); // Tìm nhóm và subKey if (matches) { const group = matches[1]; // Phần trước dấu '[' const subKey = matches[2]; // Phần giữa dấu '[' và ']' if (!result[group]) { if (subKey === "") { result[group] = []; // Khởi tạo mảng nếu không có subKey } else { result[group] = {}; // Khởi tạo đối tượng nếu có subKey } } if (subKey === "") { // Nếu subKey rỗng if (data[key] !== null) { result[group] = result[group].concat(data[key]); // Kết hợp mảng nếu không phải null } // Nếu null, không làm gì cả, giữ nguyên mảng rỗng } else { result[group][subKey] = data[key]; // Gán giá trị cho khóa con } } else { result[key] = data[key]; // Nếu không có lồng nhau thì thêm trực tiếp } }); return result; }, }; const getModelFromRef = (modelName) => { if (mongoose.models[modelName]) { return mongoose.models[modelName]; } else { throw new Error(`Model ${modelName} not defined`); } };