Skip to content

Instantly share code, notes, and snippets.

@arufian
Last active August 29, 2015 14:07
Show Gist options
  • Save arufian/325d2f77eb821c58d187 to your computer and use it in GitHub Desktop.
Save arufian/325d2f77eb821c58d187 to your computer and use it in GitHub Desktop.
Apexトリガー上でYQLのデータを取得する ref: http://qiita.com/arufian/items/99a5e974549422ad0235
global class YQLBridge {
@future (callout=true)
public static void searchGoogleBooks(String bookId) {
Book__c book = [SELECT Name, Id FROM Book__c WHERE Id=:bookId];
Http http = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint('https://query.yahooapis.com/v1/public/yql?q=SELECT%20*%20FROM%20google.books%20WHERE%20q%3D%22'
+book.Name+
'%22%20AND%20maxResults%3D1&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&format=json');
req.setMethod('GET');
HttpResponse res = http.send(req);
Map<String, Object> root = (Map<String, Object>)JSON.deserializeUntyped(res.getBody());
Map<String, Object> query = (Map<String, Object>)root.get('query');
Map<String, Object> results = (Map<String, Object>)query.get('results');
Map<String, Object> jsonItem = (Map<String, Object>)results.get('json');
Map<String, Object> items = (Map<String, Object>)jsonItem.get('items');
Map<String, Object> volumeInfo = (Map<String, Object>)items.get('volumeInfo');
String richStr = 'title :'+volumeInfo.get('title')+'<br >'+
'subtitle :'+volumeInfo.get('subtitle')+'<br >'+
'author :'+volumeInfo.get('authors')+'<br >'+
'thumbnail : <img src="'+((Map<String, Object>)volumeInfo.get('imageLinks')).get('thumbnail')+'" />';
book.Web_Results__c = richStr;
update book;
}
}
public static void populateInternetBooks(Book__c book) {
YQLBridge.searchGoogleBooks(book.Id);
}
trigger PopulateWebResults on Book__c (before insert, before update) {
Book__c[] books = Trigger.new;
for (Book__c b :books){
if(b.Web_Results__c == NULL || b.Web_Results__c.trim().equals('')) {
BookController.populateInternetBooks(b);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment