demarches-normaliennes/app/services/demarches_publiques_export_service.rb

69 lines
1.3 KiB
Ruby
Raw Normal View History

2022-06-14 13:05:19 +02:00
class DemarchesPubliquesExportService
2022-07-13 10:41:22 +02:00
attr_reader :gzip_filename
def initialize(gzip_filename)
@gzip_filename = gzip_filename
2022-06-14 13:05:19 +02:00
end
def call
2022-07-13 10:41:22 +02:00
Zlib::GzipWriter.open(gzip_filename) do |gz|
generate_json(gz)
end
end
private
def generate_json(io)
2022-06-14 13:05:19 +02:00
end_cursor = nil
first = true
2022-07-13 10:41:22 +02:00
write_array_opening(io)
2022-06-14 13:05:19 +02:00
loop do
2022-07-13 10:41:22 +02:00
write_demarches_separator(io) if !first
2022-06-14 13:05:19 +02:00
execute_query(cursor: end_cursor)
end_cursor = last_cursor
io.write(jsonify(demarches))
first = false
break if !has_next_page?
end
2022-07-13 10:41:22 +02:00
write_array_closing(io)
2022-06-14 13:05:19 +02:00
io.close
end
def execute_query(cursor: nil)
@graphql_data = SerializerService.demarches_publiques(after: cursor)
rescue => e
raise DemarchesPubliquesExportService::Error.new(e.message)
2022-06-14 13:05:19 +02:00
end
def last_cursor
@graphql_data["pageInfo"]["endCursor"]
2022-06-14 13:05:19 +02:00
end
def has_next_page?
@graphql_data["pageInfo"]["hasNextPage"]
2022-06-14 13:05:19 +02:00
end
def demarches
@graphql_data["nodes"]
2022-06-14 13:05:19 +02:00
end
def jsonify(demarches)
demarches.map(&:to_json).join(',')
end
2022-07-13 10:41:22 +02:00
def write_array_opening(io)
2022-06-14 13:05:19 +02:00
io.write('[')
end
2022-07-13 10:41:22 +02:00
def write_array_closing(io)
2022-06-14 13:05:19 +02:00
io.write(']')
end
2022-07-13 10:41:22 +02:00
def write_demarches_separator(io)
2022-06-14 13:05:19 +02:00
io.write(',')
end
end
class DemarchesPubliquesExportService::Error < StandardError
end