【问题标题】:How should I dry up the following code?我应该如何干掉下面的代码?
【发布时间】:2016-01-11 23:57:28
【问题描述】:

我在节点客户端上使用superagent 来触发POSTPATCH 这样的请求(太丑了!):

if-else 中的两个代码块之间的唯一区别是 http verb 和 API 端点,在 patch 请求的情况下,URL 还附加了一个 /:id

if ( typeof resourceId === 'undefined' ){
  request
    .post('http://localhost:8080/api/resources/')
    .send(JSON.stringify(resource_json))
    .set('Accept', 'application/json')
    .set('Content-Type', 'application/json')
    .set('Authorization', 'Token token=3S4pREbMkMoEGG6zHeUJ7Qtt')
    .end(function(err, res) {
      if (!err && res.ok) {
        console.log(chalk.bold.cyan('Resource created successfully'));
        packageJson.resource_id = res.body.id;
        fs.writeFileSync('package.json', JSON.stringify(packageJson));
        process.exit(0);
      }

      var errorMessage;

      if (res && res.status === 401) {
        errorMessage = "Authentication failed! Bad username/password?";
      } else if (err) {
        errorMessage = err;
      } else {
        errorMessage = res.text;
      }
      console.error(chalk.red(errorMessage));
      process.exit(1);
    });
  } else {
  request
    .patch('http://localhost:8080/api/reources/' + resourceId)
    .send(JSON.stringify(resource_json))
    .set('Accept', 'application/json')
    .set('Content-Type', 'application/json')
    .set('Authorization', 'Token token=3S4pREbMkMoEGG6zHeUJ7Qtt')
    .end(function(err, res) {
      if (!err && res.ok) {
        console.log(chalk.bold.cyan('Resource created successfully'));
        packageJson.book_id = res.body.id;
        fs.writeFileSync('package.json', JSON.stringify(packageJson));
        process.exit(0);
      }

      var errorMessage;

      if (res && res.status === 401) {
        errorMessage = "Authentication failed! Bad username/password?";
      } else if (err) {
        errorMessage = err;
      } else {
        errorMessage = res.text;
      }
      console.error(chalk.red(errorMessage));
      process.exit(1);
    });

  }

我怎样才能把它弄干?

【问题讨论】:

    标签: node.js superagent


    【解决方案1】:

    可以通过变量访问方法。

    const baseUrl = 'http://localhost:8080/api/resources/';
    const isNew = undefined === resourceId;
    const method = isNew ? 'post' : 'patch';
    const url = isNew ? baseUrl : basseUrl + resourceId;
    
    request[method](url).send().end();
    

    或更具可读性。

    const baseUrl = 'http://localhost:8080/api/resources/';
    const isNew = undefined === resourceId;
    let method, url;
    
    if(isNew) {
        method = 'post'
        url = baseUrl;
    } else {
        method = 'patch'
        url = baseUrl + resourceId;
    }
    
    request[method](url).send().end();
    

    【讨论】:

      猜你喜欢
      • 2017-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-08
      • 1970-01-01
      相关资源
      最近更新 更多