Skip to content

Instantly share code, notes, and snippets.

@supersupermomonga
Created October 12, 2015 02:14
Show Gist options
  • Save supersupermomonga/bfc177a2aaaa9a8e62a1 to your computer and use it in GitHub Desktop.
Save supersupermomonga/bfc177a2aaaa9a8e62a1 to your computer and use it in GitHub Desktop.
MYkfPTbIKGEDQ4CBIBKtjfMLo7O4tWOsV
'use strict';
function getInstance(service) {
return new HatenaBookmark_(service);
}
var HatenaBookmark_ = (function() {
var root = 'http://api.b.hatena.ne.jp';
var validates = {
url: function(value) {
var regexp = /^(https?|ftp)(:\/\/[-_.!~*\'()a-zA-Z0-9;\/?:\@&=+\$,%#]+)$/;
if (!regexp.test(value)) throw new Error(JSON.stringify({message: 'url is invalid'}));
}
}
var getUrl = {
get: {
bookmark: function(params) {
validates.url(params.url);
return root + Utilities.formatString('/1/my/bookmark?url=%s', encodeURIComponent(params.url));
},
entry: function(params) {
validates.url(params.url);
return root + Utilities.formatString('/1/entry?url=%s', encodeURIComponent(params.url));
},
tags: function(params) {
return root + '/1/my/tags';
},
my: function(params) {
return root + '/1/my';
}
},
post: {
bookmark: function(params) {
validates.url(params.url);
return root + '/1/my/bookmark';
}
},
destroy: {
bookmark: function(params) {
validates.url(params.url);
return root + Utilities.formatString('/1/my/bookmark?url=%s', encodeURIComponent(params.url));
}
}
}
function InnerHatenaBookmark(service) {
if (service === undefined) throw new Error('Service is required');
this.service = service.getService();
}
InnerHatenaBookmark.prototype.get = function(resource, params) {
if (!getUrl.get[resource]) throw new Error(JSON.stringify({message: 'undefined resource'}));
var response = this.service.fetch(getUrl.get[resource](params), { muteHttpExceptions: true });
if (response.getResponseCode() !== 200) throw new Error(response);
return response;
}
InnerHatenaBookmark.prototype.post = function(resource, params) {
if (!getUrl.post[resource]) throw new Error(JSON.stringify({message: 'undefined resource'}));
var response = this.service.fetch(getUrl.post[resource](params), { method: 'post', payload: params, muteHttpExceptions: true });
if (response.getResponseCode() !== 200) throw new Error(response);
return response;
}
InnerHatenaBookmark.prototype.destroy = function(resource, params) {
if (!getUrl.destroy[resource]) throw new Error(JSON.stringify({message: 'undefined resource'}));
var response = this.service.fetch(getUrl.destroy[resource](params), { method: 'delete', muteHttpExceptions: true });
if (response.getResponseCode() !== 204) throw new Error(response);
return JSON.stringify({message: 'success'});
}
return InnerHatenaBookmark;
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment