gpt4 book ai didi

javascript - 有没有办法在 Op.op sequelize 中循环遍历许多参数的对象

转载 作者:行者123 更新时间:2023-12-03 22:37:17 26 4
gpt4 key购买 nike

我正在设置一个搜索API,就是搜索; id、type、originCity、destinationCity、departmentDate、reason、accommodation、approvalStatus...,之后列表可能会增加

const options = {
id,
type,
originCity,
destinationCity,
departureDate,
reason,
accommodation,
boolApprovalStatus
};

我正在使用 sequelize Op 运算符,我希望我的代码可重用,我不喜欢将所有这些参数转储到 sequelize Op.op 运算符中。
{ where:{ [Op.or]: [{id}, {type}, {originCity}, {destinationCity}, {departureDate}, {reason}, {accommodation}, {approvalStatus}] } }
我尝试使用没有返回任何结果的 Object.value(options) 方法,并保持我的服务器正常运行,直到超时

这是我下面的代码

import { Op } from 'sequelize';
import Request from '../database/models/request';

/**
* @param {object} options query option
* @param {object} Request model /table
* @returns {Promise} Promise resolved or rejected
* @description get all rows where option matches
*/
findRequest(options) {
return Request.findAll({ where: { [Op.or]: Object.values(options) } });
},
};

import DbServices from '../services/dbServices';
const { findRequest } = DbServices;

/**
* search requested trip and approval trip controller
* @param {Object} req - server request
* @param {Object} res - server response
* @returns {Object} - custom response
*/
const searchRequest = async (req, res) => {
try {
const {
id, type, originCity, destinationCity, departureDate, reason, accommodation, approvalStatus
} = req.params;

if (id || type || originCity || destinationCity || departureDate || reason || accommodation
|| approvalStatus || approvalStatus) {
const boolApprovalStatus = JSON.parse(approvalStatus);

const options = {
id,
type,
originCity,
destinationCity,
departureDate,
reason,
accommodation,
boolApprovalStatus
};

const searchResult = await findRequest(options);
if (searchResult.length <= 0) return response(res, 404, 'error', { message: messages.noResult });
return response(res, 201, 'success', searchResult);
}
} catch (error) {
return response(res, 400, 'error', { message: messages.error });
}
};

export default {
requestTrip,
searchRequest
};

最佳答案

解决方法很简单:

//converting properties of object into an array of small objects
const arrayOptions = Object.entries(options).map(([k, v]) => ({ [k]: v }));

//findRequest function
findRequest(options) {
return Request.findAll({ where: { [Op.or]: arrayOptions } });
},

关于javascript - 有没有办法在 Op.op sequelize 中循环遍历许多参数的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57644206/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com