Skip to content

Instantly share code, notes, and snippets.

@mudafar
Last active May 8, 2018 22:53
Show Gist options
  • Save mudafar/276db92a49cb21c5852db875643dbdc9 to your computer and use it in GitHub Desktop.
Save mudafar/276db92a49cb21c5852db875643dbdc9 to your computer and use it in GitHub Desktop.
Google picker wrapper class - simplifying it to just setting keys and a response callback with basic picked file's properties: onPickSuccessCallback({docs, url, name})
const SCOPES = {ALL_ITEMS_RO: "https://www.googleapis.com/auth/drive.readonly"};
const DEVELOPER_KEY = 'YOUR_DEVELOPER_KEY...';
const CLIENT_ID = 'YOUR_CLIENT_ID...apps.googleusercontent.com';
export default class GooglePicker {
constructor(developerKey = DEVELOPER_KEY, clientId = CLIENT_ID, scope = SCOPES.ALL_ITEMS_RO) {
this.developerKey = developerKey;
this.clientId = clientId;
this.scope = scope;
this.pickerApiLoaded = false;
this.clientApiLoaded = false;
this.oauthToken = undefined;
this.onPickSuccessCallback = undefined;
this.onApiLoad();
}
pick({success: onPickSuccess}) {
if (this.oauthToken && this.pickerApiLoaded) {
this.createPicker();
} else if (this.clientApiLoaded) {
this.GoogleAuth.signIn().then(() => {
const user = this.GoogleAuth.currentUser.get();
this.oauthToken = user.getAuthResponse().access_token;
this.createPicker();
});
}
this.onPickSuccessCallback = onPickSuccess;
}
onApiLoad() {
gapi.load('client', () => this.onClientApiLoad());
gapi.load('picker', () => this.onPickerApiLoad());
}
onClientApiLoad() {
gapi.client.init({client_id: this.clientId, scope: this.scope}).then(() => {
this.GoogleAuth = gapi.auth2.getAuthInstance();
this.clientApiLoaded = true;
});
}
onPickerApiLoad() {
this.pickerApiLoaded = true;
}
handleAuthResult(authResult) {
if (authResult && !authResult.error) {
this.oauthToken = authResult.access_token;
this.createPicker();
}
}
createPicker() {
if (this.pickerApiLoaded && this.oauthToken) {
const picker = new google.picker.PickerBuilder()
.addView(google.picker.ViewId.DOCS)
.setOAuthToken(this.oauthToken)
.setDeveloperKey(this.developerKey)
.setCallback((data) => this.pickerCallback(data)).build();
picker.setVisible(true);
console.log("created")
}
}
pickerCallback(data) {
if (data[google.picker.Response.ACTION] === google.picker.Action.PICKED) {
const docs = data[google.picker.Response.DOCUMENTS];
const url = docs[0][google.picker.Document.URL];
const name = docs[0][google.picker.Document.NAME];
this.onPickSuccessCallback({docs: docs, url: url, name: name});
}
}
}
/* Usage example - logging the selected file name
const googlePicker = new GooglePicker();
googlePicker.pick({ success: (data) => { console.log(data.name) } });
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment