Created
September 25, 2015 16:25
-
-
Save supersupermomonga/3f16d478c9bdc4b1dffa to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* == HatenaBookmarkWebhook == | |
* library to handle params for Google Apps Script | |
* | |
* @doc http://developer.hatena.ne.jp/ja/documents/bookmark/apis/webhook | |
*/ | |
/* constructs an HatenaBookmarkWebhook | |
* | |
* @constructor | |
* @return {HatenaBookmarkWebhook} | |
*/ | |
function getInstance() { | |
return new HatenaBookmarkWebhook(); | |
} | |
/* constructs an HatenaBookmarkWebhook | |
* | |
* @constructor | |
*/ | |
function HatenaBookmarkWebhook() {} | |
/* handle params from Hatena Bookmark | |
* | |
* @param {e} event object after post request | |
* @throws {Object} | |
* @return {Object} | |
*/ | |
HatenaBookmarkWebhook.prototype.requestHandler = function (e) { | |
try { | |
if (!e.parameter) throw new Error('Missing required parameters.'); | |
var res = e.parameter; | |
res['tags'] = this.parseTags(res.comment); | |
res['comment'] = this.parseComment(res.comment); | |
return (this.onSuccess === undefined) ? res : this.onSuccess(res); | |
} catch(ex) { | |
var res = { parameter: { message: ex.toString() } }; | |
return (this.onFailure === undefined) ? res : this.onFailure(res); | |
} | |
} | |
/* parse tags from comment | |
* | |
* @param {String} comment in params | |
* @return {String} comma separated values | |
*/ | |
HatenaBookmarkWebhook.prototype.parseTags = function (comment) { | |
var matches_array = comment.match(/(\[.+?\])/g); | |
if (!matches_array) { | |
return null; | |
} else { | |
return Object.keys(matches_array).map(function(i) { | |
return matches_array[i].replace(/^\[(.+)\]/, '$1'); | |
}).join(', '); | |
} | |
} | |
/* parse comment from comment | |
* | |
* @param {String} comment in params | |
* @return {String} stripped tags from comment | |
*/ | |
HatenaBookmarkWebhook.prototype.parseComment = function (comment) { | |
var matches_array = comment.match(/^\[.+\]\s(.+)$/); | |
if (!matches_array) { | |
return null; | |
} else { | |
return matches_array[1]; | |
} | |
} | |
/* register callback on success | |
* | |
* @param {function} callback on success | |
* @return {this instance} | |
*/ | |
HatenaBookmarkWebhook.prototype.onSuccessHandler = function (_callback) { | |
this.onSuccess = _callback; | |
return this; | |
} | |
/* register callback on failure | |
* | |
* @param {function} callback on success | |
* @return {this instance} | |
*/ | |
HatenaBookmarkWebhook.prototype.onFailureHandler = function (_callback) { | |
this.onFailure = _callback; | |
return this; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment