Class: Rails::Contact::Google::SyncService

Inherits:
Object
  • Object
show all
Defined in:
lib/rails/contact/google/sync_service.rb

Instance Method Summary collapse

Constructor Details

#initialize(token_store: TokenStore.new, client: nil) ⇒ SyncService

Returns a new instance of SyncService.



5
6
7
8
# File 'lib/rails/contact/google/sync_service.rb', line 5

def initialize(token_store: TokenStore.new, client: nil)
  @token_store = token_store
  @client = client || Client.new(access_token: @token_store.access_token)
end

Instance Method Details

#sync!Object



10
11
12
13
14
# File 'lib/rails/contact/google/sync_service.rb', line 10

def sync!
  Rails::Contact::Contact.sync_window.includes(:emails, :phones, :addresses).each do |contact|
    sync_contact(contact)
  end
end

#sync_contact(contact) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/rails/contact/google/sync_service.rb', line 32

def sync_contact(contact)
  payload = PayloadMapper.new(contact).to_people_payload
  response = if contact.google_resource_name.present?
               body = payload.merge(
                 resourceName: contact.google_resource_name,
                 etag: contact.google_etag
               ).compact
               @client.update_contact(contact.google_resource_name, body)
  else
               @client.create_contact(payload)
  end

  contact.update!(
    google_resource_name: response["resourceName"] || contact.google_resource_name,
    google_etag: response["etag"] || contact.google_etag,
    google_last_modified_at: Time.current,
    last_synced_at: Time.current
  )
end

#sync_unsynced!Object



20
21
22
23
24
25
26
27
28
29
30
# File 'lib/rails/contact/google/sync_service.rb', line 20

def sync_unsynced!
  unsynced_contacts_scope.in_batches(of: 100) do |batch|
    batch.preload(:emails, :phones, :addresses).each do |contact|
      sync_contact(contact)
    rescue StandardError => e
      Rails.logger.error(
        "[Rails::Contact] Google sync_unsynced failed for contact #{contact.id}: #{e.class}: #{e.message}"
      )
    end
  end
end

#unsynced_contacts_scopeObject



16
17
18
# File 'lib/rails/contact/google/sync_service.rb', line 16

def unsynced_contacts_scope
  Rails::Contact::Contact.where("google_resource_name IS NULL OR google_resource_name = ?", "")
end