这是一个很长的问题,所以请忍受
我们有一个可以在 Express , Mongo , React 和 Redux 上运行的应用程序。我已经编写了通过获取查询字符串来处理传入请求的中间件和路由处理程序。
这是后端的代码:
Peopleservices.js
const people = require("../models/Person");
// creating the filter function
const findBy = filter => {
// loop on filter props
const query = {};
for (prop in filter) {
// if the prop contains gt or lt we should change it to mongo style query
if (prop.includes("_")) {
let finalQuery = {};
let parts = prop.split("_");
query[parts[0]] = parts[1];
finalQuery[`$${parts[1]}`] = filter[prop];
query[parts[0]] = finalQuery;
} else {
// if the prop does not containg gt or lt, just return the same query
query[prop] = filter[prop];
}
}
// finally, return the query
return people.find(query);
};
module.exports = {
findBy
};
这是我们获取查询字符串并将其转换为mongo可理解查询的地方。
PeopleRouters.js
module.exports = app => {
// calling services
const service = require("../services/peopleService");
// Route to handle everyone
app.get(["/everyone"], async (req, res) => {
try {
const filter = req.query || {};
const all = await service.findBy(filter);
res.status(200).send(all);
} catch (ex) {
next(ex);
}
});
};
然后我们用正确的查询呼叫路由器
2。前端:React,Redux
我们将通过用户交互来创建查询字符串,其中有三个输入字段,分别是名称,性别和年龄。基于给定的组合,我们创建最终查询字符串以发送到服务器。这是通过以下方式完成的:
用于捕获用户数据的表单:
App.js
render() {
// the form, ideally could have it's own component
return (
<div className="ui container">
<div className="row" />
<div className="row">
<div className="ui two column centered grid">
<div className="column">
<div className="ui form">
<form className="ui form" onSubmit={this.handleSubmit}>
<div className="field">
<label>Name:</label>
<input
type="text"
name="name"
value={this.state.name}
onChange={this.handleChange}
/>
</div>
<div className="field">
<select
name="age"
value={this.state.age}
onChange={this.handleChange}
>
<option value="">Select Age Range</option>
<option value="_gte=20">Above 20</option>
<option value="_lt=20">Below 20</option>
</select>
</div>
<div className="field">
<select
className="ui fluid dropdown"
name="gender"
value={this.state.gender}
onChange={this.handleChange}
>
<option value="">Select Gender</option>
<option value="female">Female</option>
<option value="male">Male</option>
</select>
</div>
<div className="ui buttons">
<button type="submit" className="ui positive button active">
Search
</button>
</div>
</form>
</div>
</div>
</div>
</div>
<div className="ui link cards">{this.renderContent()}</div>
</div>
);
}
完成后,接收元素,在应用程序的 Redux 一侧处理要发送给我们的动作创建者的请求:
handleChange = event => {
this.setState({
[event.target.name]: event.target.value
});
};
// submitting the form
handleSubmit = event => {
event.preventDefault();
this.props.fetchPeople(this.state.name, this.state.age, this.state.gender);
};
一旦所有用户数据都存储在状态中,我们会将其传递给动作创建者:
import axios from "axios";
import { FETCH_PEOPLE } from "./types";
export const fetchPeople = (...args) => async dispatch => {
// launching the default state
if (!args[0] && !args[1] && !args[2]) {
const response = await axios.get(`/everyone`);
dispatch({ type: FETCH_PEOPLE, payload: response });
}
// if the name is empty, we will run the query for the gender and age
else if (!args[0] && args[1] && args[2]) {
console.log("we here?");
const response = await axios.get(
`/everyone?age${args[1]}&gender=${args[2]}`
);
dispatch({ type: FETCH_PEOPLE, payload: response });
} else {
// populating with user's input
const response = await axios.get(
`/everyone?name=${args[0]}&age${args[1]}&gender=${args[2]}`
);
dispatch({ type: FETCH_PEOPLE, payload: response });
}
};
动作创建者使用 Axios 发出请求,并显示结果。但正如您所看到的,我只能做一点 if and else ,只涉及一些组合。因此,我正在寻找一种更好的方法。
我尝试了什么?
尽管该代码目前尚可,并且许多应用程序(例如Jira)也面临相同的问题,并且通过首先强制使用类别来简化了过程!我坚持要提出一个神奇的算法!
我亲爱的朋友工程师,明智的人,在这件事上启发了我!我真的不喜欢那些 if and else !那是罪过!
答案 0 :(得分:2)
您可以这样简化:-
//Pass object with keys and values from form values as arguments
this.props.fetchPeople({
name: this.state.name,
age: this.state.age,
gender: this.state.gender
});
// or more flexible approach will be to spread user input values
this.props.fetchPeople({...this.state});
// Make a genQueryString function
const genQueryString = (args={}) => {
let queryString = "";
Object.keys(args).forEach((key) => {
if(args[key]) {
if(key === "age") {
queryString+= `${key}${args[key]}&`;
} else {
queryString+= `${key}=${args[key]}&`
}
}
});
return queryString;
}
export const fetchPeople = (args) => async dispatch => {
const response = await axios.get(
`/everyone?${genQueryString(args)}`
);
dispatch({ type: FETCH_PEOPLE, payload: response });
}
};
或者您也可以使用像qs这样的npm库从参数中生成查询字符串,这将提供更多方法: https://www.npmjs.com/package/qs