Skip to content

Instantly share code, notes, and snippets.

@cadecairos
Created June 8, 2015 19:13
Show Gist options
  • Save cadecairos/85149518545550adf8a0 to your computer and use it in GitHub Desktop.
Save cadecairos/85149518545550adf8a0 to your computer and use it in GitHub Desktop.
Holy Promises, Watman
server.method('projects.remix', function(userId, remixData, done) {
var project;
var transaction;
var transactionErr;
getTransactionClient().then(function(t) {
transaction = t;
return begin(transaction);
}).then(function() {
return executeTransaction(transaction, queries.projects.create,
[
userId,
remixData.id,
server.methods.utils.version(),
remixData.title,
remixData.thumbnail
]
);
}).then(function(result) {
project = server.methods.utils.formatProject(result.rows[0]);
return Promise.resolve(remixData.pages.map(function(page) {
return new Promise(function(resolve, reject) {
var remixPage;
executeTransaction(transaction, queries.pages.create,
[
project.id,
page.x,
page.y,
page.styles
]
).then(function(result) {
remixPage = result.rows[0];
return Promise.resolve(page.elements.map(function(element) {
return executeTransaction(transaction, queries.elements.create,
[
remixPage.id,
element.type,
element.attributes,
element.styles
]
);
}));
}).then(function(elementPromises) {
return Promise.all(elementPromises);
}).then(resolve)
.catch(reject);
});
}));
}).then(function(pagePromises) {
return Promise.all(pagePromises);
}).then(function() {
return commit(transaction);
}).then(function() {
done(null, project);
}).catch(function(err) {
transactionErr = err;
return rollback(transaction);
}).then(function() {
done(transactionErr);
}).catch(function(err) {
done(err);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment