Commit 3bdef90b authored by Kenneth Bolivar's avatar Kenneth Bolivar 💬
Browse files

Add plan C: Javascript way

parent 64ca601c
fetcher:
version: VERSION
js:
js/instagram.fetcher.js: {}
dependencies:
- core/jquery.once
(function ($) {
Drupal.behaviors.instagramFetcher = {
attach: function (context, settings) {
// Apply jQuery.once behavior.
$('.field--name-field-instagram-account', context)
.once('instagram-fetcher')
.each(function () {
// Verify instagram settings are available.
if (typeof drupalSettings.instagram === "object") {
// Consume Instagram account homepage by HTTP GET method.
var url = 'https://www.instagram.com/' + settings.instagram.account;
$.ajax({
type: 'GET',
url: url,
error: function (e) {
console.error(e);
},
success: function (response) {
var data = Drupal.behaviors.instagramFetcher.prepareResponse(response);
if (data !== null) {
var cards = Drupal.behaviors.instagramFetcher.buildCards(data);
console.log(cards);
}
}
});
}
});
},
prepareResponse: function (response) {
var data = null;
try {
var entry = JSON.parse(
response.split("window._sharedData = ")[1]
.split(";</script>")[0]
).entry_data;
if(entry.ProfilePage) {
data = entry.ProfilePage[0].graphql;
}
} catch (e) {
console.error(e);
}
return data;
},
buildCards: function (data) {
if (typeof data.user === 'object' &&
typeof data.user.edge_owner_to_timeline_media === 'object' &&
typeof data.user.edge_owner_to_timeline_media.edges === 'object') {
var cards = [];
var edges = data.user.edge_owner_to_timeline_media.edges;
for (var idx in edges) {
var edge = edges[idx].node;
cards.push({
'username': edge.owner.username,
'image_url': edge.display_url,
'image_caption': edge.accessibility_caption,
'description': edge.edge_media_to_caption.edges[0].node.text
});
if (cards.length >= 10) {
break;
}
}
return cards;
}
}
};
})(jQuery);
......@@ -33,6 +33,10 @@ public function viewElements(FieldItemListInterface $items, $langcode) {
'sharedData' => $this->getSharedData($item->value),
],
];
// Plan C: By Javascript...
$element[$delta]['#attached']['drupalSettings']['instagram']['account'] = $item->value;
$element[$delta]['#attached']['library'][] = 'instagram_graphql/fetcher';
}
return $element;
......@@ -84,7 +88,7 @@ protected function getSharedData($username) {
'text',
]),
];
}, $rawData);
}, $rawData ?? []);
}
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment