Skip to content

Instantly share code, notes, and snippets.

@SheepTester
Last active February 20, 2019 22:05
Show Gist options
  • Select an option

  • Save SheepTester/3ac9f05611cc18ab15cfb00d3519084f to your computer and use it in GitHub Desktop.

Select an option

Save SheepTester/3ac9f05611cc18ab15cfb00d3519084f to your computer and use it in GitHub Desktop.
Schoology portfolio getter and setter
const ps = new PortfolioStorer(); // creates new portfolio
ps.ready.then(id => {
ps.setContent('Hello world!').then(() => {
ps.getContent().then(console.log);
});
});
const PortfolioStorer = (() => {
function fetchJSON(path, headers, method = 'GET', body = undefined) {
return fetch('https://pausd.schoology.com/portfolios/' + path, {method, headers, body: body && JSON.stringify(body)})
.then(r => r.json())
.then(({data}) => data);
}
class PortfolioStorer {
constructor(id, uid) {
this.uid = uid || siteNavigationUiProps.props.user.uid;
this.ready = this.getCSRFToken().then(() => {
return (this.id = id) || this.createPortfolio()
.then(ids => this.id = this.uid + '-' + ids.join('-'))
.then(() => this.setupPortfolio());
});
}
getCSRFToken() {
return fetchJSON('init')
.then(({csrfToken}) => this.csrfToken = csrfToken);
}
createPortfolio() {
return fetchJSON(`users/${this.uid}/portfolios`, {'X-Csrf-Token': this.csrfToken}, 'POST')
.then(({id: portfolioID}) => fetchJSON(`users/${this.uid}/portfolios/${portfolioID}/items`,
{'X-Csrf-Token': this.csrfToken}, 'POST', {item_type: "page", metadata: {}})
.then(({id: pageID, portfolio: {public_hash}}) => [portfolioID, pageID, public_hash]));
}
setupPortfolio() {
const [uid, portfolioID, pageID, public_hash] = this.id.split('-');
return Promise.all([
fetchJSON(`users/${uid}/portfolios/${portfolioID}`, {'X-Csrf-Token': this.csrfToken}, 'PUT',
{title: 'Communications', description: 'Your ID: ' + this.id}),
fetchJSON(`users/${this.uid}/portfolios/${portfolioID}/items/${pageID}`,
{'X-Csrf-Token': this.csrfToken}, 'PUT', {title: 'User data', description: 'Don\'t edit this page!'})
]);
}
setContent(content) {
const [, portfolioID, pageID] = this.id.split('-');
return fetchJSON(`users/${this.uid}/portfolios/${portfolioID}/items/${pageID}`, {'X-Csrf-Token': this.csrfToken}, 'PUT', {metadata: {content}});
}
getContent(id = this.id) {
const [uid, portfolioID, pageID, public_hash] = id.split('-');
return fetchJSON(`users/${uid}/portfolios/${portfolioID}/items/${pageID}`,
{'X-Csrf-Token': this.csrfToken, 'X-Public-Hash': public_hash})
.then(({metadata: {content}}) => content);
}
getID() {
return this.id;
}
}
return PortfolioStorer;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment