首页 > 解决方案 > 如何使此更新 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;
  }

标签: typescriptapibackendnestjs

解决方案


您可以使用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);

你可以阅读更多关于Object.values(obj)Array.prototype.some(fn)


推荐阅读