71 lines
2.9 KiB
JavaScript
71 lines
2.9 KiB
JavaScript
const { addActivityLogJob } = require('../queue');
|
|
|
|
exports.activityLogger = (defaultAction) => {
|
|
return (req, res, next) => {
|
|
res.on('finish', () => {
|
|
if (res.statusCode >= 200 && res.statusCode < 300) {
|
|
try {
|
|
const params = req.body?.params || {};
|
|
|
|
const projectId = params.projectId || req.baseUrl.split('/')[1] || '-';
|
|
const activity = params.activity || defaultAction || '-';
|
|
|
|
let userId = 'system';
|
|
if (params.userInfoString) {
|
|
try {
|
|
const userInfo = JSON.parse(params.userInfoString);
|
|
userId = userInfo.user_id || 'system';
|
|
} catch (e) {}
|
|
} else if (req.user?.user_id) {
|
|
userId = req.user.user_id;
|
|
}
|
|
|
|
const userIp = req.ip || req.headers['x-forwarded-for'] || req.socket.remoteAddress;
|
|
|
|
let targetPath = '-';
|
|
if (params.resourcePath) {
|
|
targetPath = params.resourcePath;
|
|
} else if (Array.isArray(params.resourcePathArr) && params.resourcePathArr.length > 0) {
|
|
targetPath = params.resourcePathArr[0];
|
|
} else if (Array.isArray(params.fromPathArr) && params.fromPathArr.length > 0) {
|
|
targetPath = params.fromPathArr[0];
|
|
}
|
|
|
|
let dataId = null;
|
|
if (params.dataId) {
|
|
dataId = params.dataId;
|
|
} else if (Array.isArray(params.dataIdArr) && params.dataIdArr.length > 0) {
|
|
dataId = params.dataIdArr[0];
|
|
}
|
|
|
|
const logData = {
|
|
projectId,
|
|
activity,
|
|
userId,
|
|
userIp,
|
|
targetPath,
|
|
status: 'SUCCESS',
|
|
logDate: new Date(),
|
|
metaData: {
|
|
method: req.method,
|
|
url: req.originalUrl,
|
|
dataIdArr: params.dataIdArr || (dataId ? [dataId] : []),
|
|
dataType: params.dataType || '-',
|
|
newName: params.newName || '-',
|
|
oldName: params.oldName || '-'
|
|
}
|
|
};
|
|
|
|
addActivityLogJob(logData).catch(err => {
|
|
console.error("[ActivityLogger Middleware] Queue Error:", err);
|
|
});
|
|
|
|
} catch (err) {
|
|
console.error("[ActivityLogger Middleware] Intercept Error:", err);
|
|
}
|
|
}
|
|
});
|
|
next();
|
|
};
|
|
};
|