UNPKG

als-mongo-list

Version:

A flexible, lightweight MongoDB query utility for Node.js applications. Simplifies database operations with intuitive filtering, pagination, sorting, and field selection. Ideal for REST API endpoints, providing a primary List class that abstracts complex

43 lines (37 loc) 1.69 kB
class Sort { constructor(listObj) { this.input = null this.init(listObj); } init({ tree, sortKeys }) { if (sortKeys.size === 0) return null const options = []; Array.from(sortKeys).forEach((key) => { const fieldType = tree[key]?.type?.name; if (!fieldType) return; // Пропустить ключи без типа if (fieldType === 'String') { options.push({ value: key, text: 'a_z',key }) options.push({ value: '-' + key, text: 'z_a',key }) } else if (fieldType === 'Number') { options.push({ value: '-' + key, text: 'small_big',key }) options.push({ value: key, text: 'big_small',key }) } else if (fieldType === 'Boolean') { options.push({ value: key, text: 'yes_first',key }) options.push({ value: '-' + key, text: 'no_first',key }) } else if (fieldType === 'Date') { options.push({ value: '-' + key, text:'new_first',key }) options.push({ value: key, text: 'old_first',key }) } }); this.input = { tag: 'select', name: 'orderBy', options }; // Создание элемента select } getSort(query) { const value = query.orderBy if (this.input === null || !value) return null if (!this.input.options.find((option) => option.value === value)) return null; // Неверное значение orderBy const direction = value.startsWith('-') ? -1 : 1; const field = value.startsWith('-') ? value.slice(1) : value; return { [field]: direction } } } module.exports = Sort;