I'm using superagent on a node client to fire POST
or PATCH
requests like so (it's ugly!):
Between the two code blocks in if-else
the only difference is the http verb
and the API endpoint, which in case of patch
request also has a /:id
appended to the 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);
});
}
How can I DRY this up?
Methods can be accessed through a variable.
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();
Or more readable.
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();