下面的代码应该怎么干?

How should I dry up the following code?

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

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

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);
    });

  }

我怎样才能把它擦干?

可以通过变量访问方法。

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();