Skip to content

Instantly share code, notes, and snippets.

@danseethaler
Created July 7, 2017 04:01
Show Gist options
  • Save danseethaler/0951d5fa1316aa5f42e4d2bc21f1a8ae to your computer and use it in GitHub Desktop.
Save danseethaler/0951d5fa1316aa5f42e4d2bc21f1a8ae to your computer and use it in GitHub Desktop.
AWS Revert File Version Rework
import { promisify } from 'util';
const readFilePromise = promisify(fs.readFile);
AwsFinder.prototype.revertFileVersion = async function(data, cb) {
log('aws', ['Reverting version:', data.id]);
// Get the current file buffer for diff comparison
try {
let originalBuffer = await readFilePromise(data.remote);
} catch (e) {
let originalBuffer = '';
}
var params = {
localFile: data.remote,
s3Params: {
Bucket: 'userlitelink',
Key: idToKey(data.id)
}
};
var downloader = client.downloadFile(params);
downloader.on('error', function(err) {
log('error_trace', { message: 'unable to download:', err });
cb({ success: false });
});
downloader.on('end', () => {
await readFilePromise(data.remote, function(err, buffer) {
if (err) throw err;
// Create a new version with the updated file
this.upload({
user: connection.user,
path: data.remote,
size: buffer.length,
comment: 'Revert to version ' + data.version,
diffs: JSON.stringify(
diffs.getHTMLDiffs(originalBuffer, buffer)
)
});
cb({ success: true, buffer });
});
});
};
AwsFinder.prototype.revertFileVersion = function(data, cb) {
log('aws', ['Reverting version:', data.id]);
// Get the current file buffer for diff comparison
fs.readFile(data.remote, function(err, originalBuffer) {
if (err) originalBuffer = '';
var params = {
localFile: data.remote,
s3Params: {
Bucket: 'userlitelink',
Key: idToKey(data.id)
}
};
var downloader = client.downloadFile(params);
downloader.on('error', function(err) {
log('error_trace', { message: 'unable to download:', err });
cb({ success: false });
});
downloader.on('end', () => {
console.log('Reading file...', data.remote);
fs.readFile(data.remote, function(err, buffer) {
if (err) throw err;
// Create a new version with the updated file
this.upload({
user: connection.user,
path: data.remote,
size: buffer.length,
comment: 'Revert to version ' + data.version,
diffs: JSON.stringify(
diffs.getHTMLDiffs(originalBuffer, buffer)
)
});
cb({ success: true, buffer });
});
});
});
};
@danseethaler
Copy link
Author

This is an example of using the async and await keywords to flatten nested callbacks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment