Skip to content

Instantly share code, notes, and snippets.

@Lubdhak
Last active September 12, 2020 16:08
Show Gist options
  • Save Lubdhak/3258603c2997b745bae96fde6c757f6a to your computer and use it in GitHub Desktop.
Save Lubdhak/3258603c2997b745bae96fde6c757f6a to your computer and use it in GitHub Desktop.
"app/graphql/resolvers/mutation/custom_story_upload.rb"
module Resolvers
module Mutation
class CustomStoryUpload < Base
attr_accessor :user, :workspace, :ctx, :temp_file
def initialize(inputs, ctx)
@ctx = ctx
@user = ctx[:current_user]
@temp_file = ctx[:file]
@workspace = ctx[:workspace]
end
def resolve
graphql_exception_handler(@ctx[:current_user].id) {
return unless temp_file.present?
validate_file
save_file
report_object
upload_to_s3 unless Rails.env.development?
validate_file_content
sync_token
run_task
return report_object
}
end
private
def validate_file
Validator::UploadFileValidator.new(temp_file).validate(origin: "custom_story_upload", user_id: user.id)
end
def save_file
@file_metadata = Util::FileSaveService.new(temp_file,save_path: "./log/custom_upload_files").save_file
file = File.open(@file_metadata.pathname)
@file_path = file.path.to_s
end
def report_object
@report_object ||= UserUpload.create!(user_id: user.id, filename: @file_metadata.original_filename, size: temp_file.size, status: "unprocessed", uploaded_at: Time.now, details: { workspace_id: workspace.id, source: "custom_story_upload", object_type: "story-sheet", bucket: bucket_name}, scan_status: "unprocessed")
end
def upload_to_s3
uploaded_file = Util::S3FileUploadService.new({ file_path: @file_path, bucket: bucket_name, s3_path: report_s3_path, delete_local_file: false }).upload
report_object.update!(s3key: uploaded_file.s3key, etag: uploaded_file.etag) if uploaded_file.present?
end
def validate_file_content
begin
Validator::CustomStorySheetValidator.new(@file_path).validate
rescue StandardError => ex
File.delete(@file_path) if report_object.s3key.present?
ex.class.name.match(/FormatError/i).present? ? (raise ::GraphQL::ExecutionError.new(ex.message, options: {status: :bad_request})) : (raise ex)
end
end
def sync_token
@token = Sync::TokenSyncService.new(user_id: user.id, workspace_id: workspace.id, api_source:"custom_upload").sync!(token: { bucket: bucket_name,s3_path: report_s3_path, type: "custom_story_upload" }, expires_at: 3.months.from_now, status: :active)
report_object.update!(details: report_object.details.merge(user_token_id: @token.id))
end
def run_task
WorkspaceDataInjectorJob.perform_later({ token_id: @token.id, file: @file_path })
broadcast(:custom_story_uploaded, workspace.id)
end
def report_s3_path
"#{Rails.env}/#{workspace.external_id}"
end
def bucket_name
AppConstant::S3Bucket::CUSTOM_UPLOAD_EXPENSE_REPORTS
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment