title: How should I dry up the following code?
body: <p>I'm using <a href="https://visionmedia.github.io/superagent/" rel="nofollow">superagent</a> on a node client to fire <code>POST</code> or <code>PATCH</code> requests like so (it's ugly!):</p>
  
  <p>Between the two code blocks in <code>if-else</code> the only difference is the <code>http verb</code> and the API endpoint, which in case of <code>patch</code> request also has a <code>/:id</code> appended to the url.</p>
  
  <pre><code>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 &amp;&amp; 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 &amp;&amp; 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 &amp;&amp; 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 &amp;&amp; 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);
      });
  
    }
  </code></pre>
  
  <p>How can I DRY this up? </p>