Techioz Blog

すでに取得した属性を使用して 2 番目の API 呼び出しを行う - Facebook API

概要

Facebook との API 呼び出しの次の部分にどのようにアプローチすればよいかわかりません。現時点では、ユーザー ID を使用してすべての投稿を取得しています。

"https://graph.facebook.com/#{VANDALS_ID}/posts/?access_token=#{FB_ACCESS_TOKEN}"

ただし、最初の API 呼び出しから返された object_id を使用して、各投稿に関連付けられた画像も取得したいと考えています。

"https://graph.facebook.com/#{object_id}/picture

したがって、現時点では、最初の API 呼び出しを処理し、返されたデータをモデルに保存するクラスがあります。

class FacebookFeed
#Constants
VANDALS_ID = ENV['VANDALS_FB_ID']
FB_ACCESS_TOKEN = ENV['FACEBOOK_ACCESS_TOKEN']
FACEBOOK_URL = "https://graph.facebook.com/#{VANDALS_ID}/posts/?access_token=#{FB_ACCESS_TOKEN}"

def get_feed
  uri = URI(FACEBOOK_URL)
  response = HTTParty.get(uri)
  results = JSON.parse(response.body)
  puts formatted_data(results)
end

def formatted_data(results)
  
 return unless results

    results['data'].map { |m| 
    attrs = { message: m['message'], 
              picture: m['picture'], 
              link: m['link'], 
              object_id: m['object_id']
      }.compact 
      
     
     Post.where(attrs).first_or_create! do |post|
        post.attributes = attrs
     end
   }
   end

  def get_large_photo(object_id)
  #added this to handle the second api request and pass through the object_id

  end

したがって、最初の API 呼び出しで必要な情報はすべて attrs というハッシュ内にあり、attrs[‘object_id’] を介して object_id にアクセスできます。あれは正しいですか?

ハッシュから各 object_id を取得し、別の呼び出しでそれに関連付けられた画像を取得し、キー :picture に割り当てられた値を保存し、それを attrs ハッシュに戻して保存する方法に行き詰まっています。私の投稿モデルのすべて。

解決策

私は次のようなことをしますが、あなたが何を達成しようとしているのかについてはまだ混乱しています。

def formatted_data(results)
    if results[:data]
        for record in results[:data] do
             attrs = {
                 message: record[:message],
                 picture: record[:picture],
                 link: record[:link],
                 object_id: record[:object_id]
             }
             Post.where(attrs).first_or_create!(attrs)

             #perform second call
             if record[:object_id]
                post = Post.find_by object_id: record[:object_id] 
                if post
                    fb_large_picture_url = get_large_photo(record[:object_id])
                    post.update_attribute(large_image_url: fb_large_picture_url)
                end
             end
        end
    end
 end

 def get_large_photo(object_id)
     uri = URI("https://graph.facebook.com/#{object_id}/picture")
     response = HTTParty.get(uri)
     results = JSON.parse(response.body)
     return formatted_picture_data(results) #new method to handle response from second api call
 end

Skype でリッチと話し合ったところ、本当の問題は、彼が API を再度呼び出して、より大きな画像を投稿するために object_id のレコードを持つようにデータベースを修正しようとしていることのようです。

これはかなり非効率ですが、それでも機能するはずです