@tasolutions/express-core
Version:
All libs for express
219 lines (195 loc) • 8.86 kB
JavaScript
const _ = require('lodash');
const { apiUserService } = require('../clients/userService');
module.exports = {
/**
* Map Headers To Query and Filter Unavailable Fields
* @param req
* @param Collection
* @returns {Promise<boolean>}
*/
mapHeadersToQuery: async (req, Collection) => {
const headersToFieldsMap = {
'st-user-id': 'user',
'st-agency-id': 'agency',
'st-organization-id': 'organization',
'st-company-admin': 'company_admin',
'st-admin': 'admin',
'st-agency-level': 'agency_level',
'st-location-type': 'location_type',
'st-location-id': 'location',
'st-current-agency-id': 'current_agency',
};
const allowedFields = Object.keys(Collection.schema.paths);
// Hàm kiểm tra ID hợp lệ
const isValidAgencyId = (id) => id && id !== 'null' && id.trim() !== '';
// Kiểm tra và loại bỏ header không hợp lệ
for (const header in headersToFieldsMap) {
if (!isValidAgencyId(req.headers[header])) {
delete req.headers[header];
}
}
// Xử lý trường hợp st-agency-level
if (req.headers['st-agency-level'] === '1') {
req.headers['st-organization-id'] = req.headers['st-organization-id'] || req.headers['st-agency-id'];
delete headersToFieldsMap['st-agency-id'];
}
// Xử lý trường hợp st-admin
if (req.headers['st-admin'] === 'yes') {
const agencyId = req.headers['st-current-agency-id'];
if (isValidAgencyId(agencyId)) {
const orgID = await apiUserService.getOrgIDByAgID(agencyId);
if (orgID) {
req.headers['st-organization-id'] = orgID;
}
} else {
delete headersToFieldsMap['st-organization-id'];
}
delete headersToFieldsMap['st-agency-id'];
}
// Thêm điều kiện is_deleted cho GET và PUT
if (['GET', 'PUT'].includes(req.method) && allowedFields.includes('is_deleted')) {
req.query['is_deleted'] = false;
}
// Xử lý headers tùy thuộc vào phương thức
const processHeaders = (method) => {
for (const header in headersToFieldsMap) {
if (req.headers[header]) {
const field = headersToFieldsMap[header] === 'current_agency' ? 'agency' : headersToFieldsMap[header];
const id = req.headers[header];
const field_full = `${field}_identifier`;
const field_identifiers = `${field}_identifiers`;
// Tạo điều kiện query
if (allowedFields.includes(field_full) && allowedFields.includes(field_identifiers)) {
req.query = {
...req.query,
$or: [
{ [field_full]: id },
{ [field_identifiers]: id },
],
};
} else if (allowedFields.includes(field_full)) {
req.query[field_full] = id;
} else if (allowedFields.includes(field_identifiers)) {
req.query[field_identifiers] = id;
}
}
}
};
// Xử lý cho phương thức GET
if (req.method === 'GET') {
processHeaders(req.method);
Object.keys(req.query).forEach((key) => {
if (key.startsWith("sort_")) {
delete req.query[key];
}
});
delete req.query.search;
delete req.query.access_token;
return req.query;
}
// Xử lý cho POST, PUT, PATCH
else if (['POST', 'PUT', 'PATCH'].includes(req.method)) {
processHeaders(req.method);
for (const header in headersToFieldsMap) {
if (req.headers[header]) {
const field = headersToFieldsMap[header] === 'current_agency' ? 'agency' : headersToFieldsMap[header];
req.body[`${field}_identifier`] = req.headers[header];
}
}
return req.body;
}
return false;
},
/**
* Map Headers To Query and Check Authorization
* @param req
* @param payloadFilter
* @param Collection
* @returns {Promise<boolean>}
*/
mapHeadersAndCheckAuthorization: async (req, payloadFilter, Collection, isRestore = false) => {
const headersToFieldsMap = {
'st-user-id': 'user',
'st-agency-id': 'agency',
'st-organization-id': 'organization',
'st-company-admin': 'company_admin',
'st-admin': 'admin',
'st-agency-level': 'agency_level',
'st-location-type': 'location_type',
'st-location-id': 'location'
};
const fieldIds = {}; // Lưu trữ tất cả ID từ headers
const bodyFields = {}; // Lưu trữ ID cho body
const allowedFields = Object.keys(Collection.schema.paths); // Lấy danh sách các trường từ Collection
const agLevel = req.headers['st-agency-level'];
if (agLevel == 1) {
req.headers['st-organization-id'] = req.headers['st-organization-id'] ? req.headers['st-organization-id'] : req.headers['st-agency-id'];
delete headersToFieldsMap['st-agency-id'];
}
const isAdmin = req.headers['st-admin'];
if (isAdmin == 'yes') {
delete headersToFieldsMap['st-organization-id'];
delete headersToFieldsMap['st-agency-id'];
}
if (req.method === 'GET' && allowedFields.includes('is_deleted')) {
req.query['is_deleted'] = false;
}
// Xử lý các header tùy thuộc vào phương thức
const processHeaders = (method) => {
for (const header in headersToFieldsMap) {
if (req.headers[header]) {
const field = headersToFieldsMap[header];
const id = req.headers[header];
if (method === 'GET') {
const field_full = `${field}_identifier`;
const field_identifiers = `${field}_identifiers`;
// Chỉ lưu trữ nếu trường hợp nằm trong allowedFields
if (allowedFields.includes(field_full)) {
req.query[field_full] = id; // Thay vì dùng $or,Assign trực tiếp vào req.query
}
if (allowedFields.includes(field_identifiers)) {
req.query[field_identifiers] = id; // Cũng tương tự với trường _identifiers
}
} else {
// Cho POST, PUT, PATCH và DELETE
req.body[`${field}_identifier`] = id;
if (field === 'user' && method === 'DELETE') {
req.body['deleted_by_identifier'] = id;
}
if (field === 'user' && isRestore) {
req.body['restored_by_identifier'] = id;
}
}
// Lưu trữ ID cho từng trường
fieldIds[field] = id;
bodyFields[`${field}_identifier`] = id;
}
}
};
// Chạy hàm xử lý cho phương thức hiện tại
processHeaders(req.method);
// Lọc bodyFields dựa trên trường hợp trong Collection
const filteredBodyFields = Object.keys(bodyFields).reduce((acc, key) => {
if (allowedFields.includes(key)) {
acc[key] = bodyFields[key];
}
return acc;
}, {});
// Kiểm tra quyền truy cập nếu có trường ID
if (Object.keys(bodyFields).length > 0) {
const count = await Collection.countDocuments({ ...payloadFilter, ...filteredBodyFields });
return count > 0; // Trả về true nếu có ít nhất một bản ghi hợp lệ
}
return true; // Nếu không cần kiểm tra quyền truy cập
},
headersToInclude: (schema, includeFields) => {
const headers = [];
for (const path of includeFields) {
const fieldSchema = schema.paths[path];
if (fieldSchema) {
headers.push(path);
}
}
return headers;
},
}