Class: Kidspire::PcoClient

Inherits:
Object
  • Object
show all
Defined in:
lib/kidspire/pco_client.rb

Constant Summary collapse

PCO_BASE_URL =
"https://api.planningcenteronline.com"
PCO_TOKEN_URL =
"https://api.planningcenteronline.com/oauth/token"
PAGE_SIZE =
100

Instance Method Summary collapse

Constructor Details

#initialize(integration = nil) ⇒ PcoClient

Returns a new instance of PcoClient.



9
10
11
12
# File 'lib/kidspire/pco_client.rb', line 9

def initialize(integration = nil)
  @integration = integration || ChurchIntegration.current
  validate_integration!
end

Instance Method Details

#delete(path) ⇒ Object



67
68
69
# File 'lib/kidspire/pco_client.rb', line 67

def delete(path)
  request(:delete, path)
end

#get(path, params = {}) ⇒ Object

Single-page GET — returns parsed response hash



15
16
17
# File 'lib/kidspire/pco_client.rb', line 15

def get(path, params = {})
  request(:get, path, query: params)
end

#get_all(path, params = {}) ⇒ Object

Fetches every page and returns the full flat array of “data” objects



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/kidspire/pco_client.rb', line 43

def get_all(path, params = {})
  results  = []
  next_url = "#{PCO_BASE_URL}#{path}"
  query    = params.merge(per_page: PAGE_SIZE)

  while next_url
    response = raw_request(:get, next_url, query: query, full_url: true)
    body     = parse!(response)
    results.concat(Array(body["data"]))
    next_url = body.dig("links", "next").presence
    query    = {}  # subsequent pages use the full next_url, no extra params
  end

  results
end

#paginate(path, params = {}) ⇒ Object

Fetches every page; returns { “data” => […], “included” => […] } Use this when sync jobs need JSON:API ‘included` side-loaded records.



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/kidspire/pco_client.rb', line 21

def paginate(path, params = {})
  result = { "data" => [], "included" => [] }
  query  = params.merge(per_page: PAGE_SIZE)
  path   = path  # mutable below

  loop do
    response = get(path, query)
    result["data"].concat(response["data"] || [])
    result["included"].concat(response["included"] || [])

    next_link = response.dig("links", "next").presence
    break unless next_link

    uri   = URI.parse(next_link)
    path  = uri.path
    query = URI.decode_www_form(uri.query.to_s).to_h
  end

  result
end

#patch(path, body = {}) ⇒ Object



63
64
65
# File 'lib/kidspire/pco_client.rb', line 63

def patch(path, body = {})
  request(:patch, path, body: body.to_json)
end

#post(path, body = {}) ⇒ Object



59
60
61
# File 'lib/kidspire/pco_client.rb', line 59

def post(path, body = {})
  request(:post, path, body: body.to_json)
end