typescript - 如何使此更新 API 更高效、更短且不重复
问题描述
以下是更新帐户的 API 服务中的方法。我如何缩短代码而不是 if 条件中的这么多附加对象?
async updateAccount(uuid: string, body: IUpdateAccountDto) {
const found = await this.getAccountById(uuid);
const update = (resolve, reject) => {
if (
found.username ||
found.password ||
found.email ||
found.phone ||
found.product
) {
resolve(
'account updated',
((found.username = body.username),
(found.password = body.password),
(found.email = body.email),
(found.phone = body.phone),
(found.product = body.product)),
);
} else {
reject('cannot update username');
}
};
const updateAccount = new Promise(update);
return updateAccount;
}
解决方案
您可以使用Object.values(obj)
andArray.some(fn)
来实现这一点。注意:使用 Array.every(fn) 将达到 && 条件
var notValidFound = {
username: "",
password: undefined,
email: "",
phone: null,
product: ""
};
var notValidValue = Object.values(notValidFound).some(o => o);
console.log(notValidValue);
var validFound = {
username: "some_username",
password: undefined,
email: "a@abc.com",
phone: null,
product: ""
};
var validValue = Object.values(validFound).some(o => o);
console.log(validValue);
推荐阅读
- sql - 以 YYYY-MM-DD 格式获取上个月的第一天
- angular - ng serve 在 npm install 后无法运行
- php - 此路由不支持 POST 方法。(带有ajax的Laravel)
- angular - 离子幻灯片问题错误错误:未捕获(承诺):错误:模板解析错误:
- ios - “不嵌入”、“嵌入并签名”、“不签名嵌入”。这些是什么?。他们做什么?
- java - 使用 OpenCV 4.1.1 和 Java 进行自动透视校正
- python - 检查列表中所有第 N 个 idx 元素的惯用方法
- shell - zsh:参数列表太长:sudo
- java - 共享首选项在传递给另一个活动后不会加载
- java - 如何列出 JAR 中的文件?