UNPKG

node-express-mongodb-jwt-rest-api-skeleton

Version:

Node.js express.js MongoDB JWT REST API - This is a basic API REST skeleton written on JavaScript using async/await. Great for building a starter web API for your front-end (Android, iOS, Vue, react, angular, or anything that can consume an API)

44 lines (41 loc) 1.18 kB
const { buildErrObject } = require('../../middleware/utils') /** * Checks the query string for filtering records * query.filter should be the text to search (string) * query.fields should be the fields to search into (array) * @param {Object} query - query object */ const checkQueryString = (query = {}) => { return new Promise((resolve, reject) => { try { if ( typeof query.filter !== 'undefined' && typeof query.fields !== 'undefined' ) { const data = { $or: [] } const array = [] // Takes fields param and builds an array by splitting with ',' const arrayFields = query.fields.split(',') // Adds SQL Like %word% with regex arrayFields.map((item) => { array.push({ [item]: { $regex: new RegExp(query.filter, 'i') } }) }) // Puts array result in data data.$or = array resolve(data) } else { resolve({}) } } catch (err) { console.log(err.message) reject(buildErrObject(422, 'ERROR_WITH_FILTER')) } }) } module.exports = { checkQueryString }