Repository URL to install this package:
|
Version:
0.11.1 ▾
|
module ActionSprout
module Facebook
class PagePosts
PER_PAGE_LIMIT = 100
DEFAULT_SINCE = 2.weeks
POST_FIELDS = 'created_time,message,shares,reactions.limit(0).summary(true),comments.limit(0).summary(true),attachments{title,description,media_type,unshimmed_url}'.freeze
def initialize(id, **options)
@id = id
raise ArgumentError.new('"id" must be a non-empty string'.freeze) unless id.present?
@options = options
end
def each(&block)
response = initial_response.parsed_response
stream_posts(response, block)
get_more_posts response, block unless single_page?
end
private
attr_reader :id, :options
def initial_response
api.get posts_url, query: posts_query
end
def api
@_api ||= options[:api] || API.new
end
def stream_posts(response, block)
response['data'].each(&block)
end
def get_more_posts(response, block)
while (url = next_url(response)).present?
response = api.get(url).parsed_response
stream_posts(response, block)
end
end
def single_page?
options[:since].nil? && options[:until].nil?
end
def posts_url
"#{id}/posts"
end
def posts_query
{
fields: options[:fields] || POST_FIELDS,
since: since_unix,
until: until_unix,
limit: options[:limit] || PER_PAGE_LIMIT,
}.compact
end
def since_unix
options[:since]&.to_i
end
def until_unix
options[:until]&.to_i
end
def next_url(response)
response.dig('paging', 'next')
end
end
end
end