cnfs-core 0.0.1.alpha
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +7 -0
- data/MIT-LICENSE +20 -0
- data/README.md +3 -0
- data/Rakefile +22 -0
- data/app/controllers/cloud_event_subjects_controller.rb +25 -0
- data/app/controllers/concerns/ros/application_controller_concern.rb +155 -0
- data/app/controllers/file_fingerprints_controller.rb +26 -0
- data/app/controllers/tenants_controller.rb +4 -0
- data/app/jobs/ros/application_job.rb +33 -0
- data/app/jobs/ros/chown_job.rb +9 -0
- data/app/jobs/ros/cloud_event_stream_job.rb +5 -0
- data/app/jobs/ros/platform_event_process_job.rb +6 -0
- data/app/jobs/ros/storage_document_process_job.rb +6 -0
- data/app/jobs/ros/tenant_producer_event_job.rb +13 -0
- data/app/models/cloud_event_subject.rb +20 -0
- data/app/models/concerns/association_resource.rb +112 -0
- data/app/models/concerns/association_resource/association_interface.rb +30 -0
- data/app/models/concerns/association_resource/belongs_to_resource.rb +56 -0
- data/app/models/concerns/association_resource/has_many_resources.rb +49 -0
- data/app/models/concerns/association_resource/has_one_resource.rb +22 -0
- data/app/models/concerns/association_resource/included_resource.rb +58 -0
- data/app/models/concerns/association_resource/resource_helper.rb +221 -0
- data/app/models/concerns/ros/application_record_concern.rb +61 -0
- data/app/models/concerns/ros/tenant_concern.rb +110 -0
- data/app/models/concerns/ros/urn_concern.rb +40 -0
- data/app/models/file_fingerprint.rb +33 -0
- data/app/models/policy_user.rb +24 -0
- data/app/operations/ros/activity_base.rb +42 -0
- data/app/operations/ros/activity_params_validator.rb +49 -0
- data/app/operations/ros/activity_saver.rb +30 -0
- data/app/operations/ros/cloud_event_stream.rb +25 -0
- data/app/operations/ros/operation_result.rb +30 -0
- data/app/operations/ros/platform_event_process.rb +14 -0
- data/app/operations/ros/storage_document_process.rb +31 -0
- data/app/policies/cloud_event_subject_policy.rb +3 -0
- data/app/policies/concerns/ros/tenant_policy_concern.rb +27 -0
- data/app/policies/file_fingerprint_policy.rb +3 -0
- data/app/policies/ros/application_policy.rb +148 -0
- data/app/policies/tenant_policy.rb +3 -0
- data/app/resources/cloud_event_subject_resource.rb +6 -0
- data/app/resources/file_fingerprint_resource.rb +6 -0
- data/app/resources/ros/application_resource.rb +23 -0
- data/app/resources/tenant_resource.rb +6 -0
- data/app/validators/api_absence_validator.rb +8 -0
- data/app/validators/api_presence_validator.rb +13 -0
- data/app/validators/json_schema_validator.rb +50 -0
- data/config/environment.rb +0 -0
- data/config/initializers/config.rb +56 -0
- data/config/locales/en.yml +5 -0
- data/config/routes.rb +15 -0
- data/config/settings.local.yml +12 -0
- data/config/settings.yml +96 -0
- data/config/spring.rb +3 -0
- data/db/migrate/20190215014353_create_tenants.rb +13 -0
- data/db/migrate/20190215100158_create_tenant_events.rb +9 -0
- data/db/migrate/20190215104922_create_platform_events.rb +9 -0
- data/lib/generators/avro/avro_builder.rb +75 -0
- data/lib/generators/avro/avro_generator.rb +22 -0
- data/lib/generators/ros/api_doc/api_doc_generator.rb +20 -0
- data/lib/generators/ros/controller/controller_generator.rb +30 -0
- data/lib/generators/ros/endpoint/USAGE +14 -0
- data/lib/generators/ros/endpoint/endpoint_generator.rb +54 -0
- data/lib/generators/ros/generators.rb +3 -0
- data/lib/generators/ros/generators_helper.rb +17 -0
- data/lib/generators/ros/integration_test/integration_test_generator.rb +29 -0
- data/lib/generators/ros/locust_endpoint/locust_endpoint_generator.rb +84 -0
- data/lib/generators/ros/model/USAGE +11 -0
- data/lib/generators/ros/model/model_generator.rb +25 -0
- data/lib/generators/ros/model_spec/USAGE +8 -0
- data/lib/generators/ros/model_spec/model_spec_generator.rb +18 -0
- data/lib/generators/ros/policy/USAGE +8 -0
- data/lib/generators/ros/policy/policy_generator.rb +18 -0
- data/lib/generators/ros/policy_spec/USAGE +8 -0
- data/lib/generators/ros/policy_spec/policy_spec_generator.rb +15 -0
- data/lib/generators/ros/request_spec/USAGE +8 -0
- data/lib/generators/ros/request_spec/request_spec_generator.rb +145 -0
- data/lib/generators/ros/resource/USAGE +8 -0
- data/lib/generators/ros/resource/resource_generator.rb +22 -0
- data/lib/generators/ros/resource_spec/USAGE +8 -0
- data/lib/generators/ros/resource_spec/resource_spec_generator.rb +15 -0
- data/lib/generators/ros/route/USAGE +8 -0
- data/lib/generators/ros/route/route_generator.rb +11 -0
- data/lib/generators/ros/sdk_endpoint/sdk_endpoint_generator.rb +19 -0
- data/lib/migrations.rb +19 -0
- data/lib/ros/api_token_strategy.rb +69 -0
- data/lib/ros/cloudevents/fluentd_avro_logger.rb +110 -0
- data/lib/ros/core.rb +109 -0
- data/lib/ros/core/console.rb +253 -0
- data/lib/ros/core/engine.rb +284 -0
- data/lib/ros/core/version.rb +7 -0
- data/lib/ros/dtrace_middleware.rb +19 -0
- data/lib/ros/infra.rb +32 -0
- data/lib/ros/infra/aws/mq.rb +113 -0
- data/lib/ros/infra/aws/settings.rb +29 -0
- data/lib/ros/infra/aws/storage.rb +191 -0
- data/lib/ros/infra/mq.rb +13 -0
- data/lib/ros/infra/storage.rb +19 -0
- data/lib/ros/jsonapi_authorization/authorizer.rb +24 -0
- data/lib/ros/jwt.rb +67 -0
- data/lib/ros/prometheus_exporter/middleware.rb +38 -0
- data/lib/ros/prometheus_exporter/web_collector.rb +40 -0
- data/lib/ros/request_logger/fluentd.rb +68 -0
- data/lib/ros/routes.rb +20 -0
- data/lib/ros/scheduler/tenant_handler.rb +64 -0
- data/lib/ros/tenant_middleware.rb +51 -0
- data/lib/ros/url_builder.rb +21 -0
- data/lib/ros/urn.rb +46 -0
- data/lib/tasks/avro.rake +32 -0
- data/lib/tasks/cloud_event_stream.rake +56 -0
- data/lib/tasks/db.rake +41 -0
- data/lib/tasks/doc.rake +84 -0
- data/lib/tasks/erd.rake +12 -0
- data/lib/tasks/ros/core_tasks.rake +6 -0
- data/lib/template/controller.yml.erb +4 -0
- data/lib/template/integration_test.yml.erb +29 -0
- data/lib/template/locust_endpoint.yml.erb +17 -0
- metadata +607 -0
checksums.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
1
|
+
---
|
2
|
+
SHA256:
|
3
|
+
metadata.gz: e700244fc700f1b3cb08fd1981698701d5c763a17032180bd47fc5a7e428a954
|
4
|
+
data.tar.gz: 9d2e770e4bbf2650df30f0ddf946b5a8d9d69e73081215c7c55c8b3ba395c505
|
5
|
+
SHA512:
|
6
|
+
metadata.gz: 7625d8b1bb1167ae4f26cbc465f22c9f51a68cdfa3b8ff805d46585a3627021c5c0cf7f88924a0e91dd1e9d24c54c297232b2e9b3f66dcc01149324ee20b2f00
|
7
|
+
data.tar.gz: 867d4fcd103ad2e74e3030a272f29fda2502d710aaa790ab3bf983161785d1664158dca975b8a4f4fcf75f3f02e78ee7f34a88b55c840561bd9bb8cfa81f24a3
|
data/MIT-LICENSE
ADDED
@@ -0,0 +1,20 @@
|
|
1
|
+
Copyright 2019 Robert Roach
|
2
|
+
|
3
|
+
Permission is hereby granted, free of charge, to any person obtaining
|
4
|
+
a copy of this software and associated documentation files (the
|
5
|
+
"Software"), to deal in the Software without restriction, including
|
6
|
+
without limitation the rights to use, copy, modify, merge, publish,
|
7
|
+
distribute, sublicense, and/or sell copies of the Software, and to
|
8
|
+
permit persons to whom the Software is furnished to do so, subject to
|
9
|
+
the following conditions:
|
10
|
+
|
11
|
+
The above copyright notice and this permission notice shall be
|
12
|
+
included in all copies or substantial portions of the Software.
|
13
|
+
|
14
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
15
|
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
16
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
17
|
+
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
18
|
+
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
19
|
+
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
20
|
+
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
data/README.md
ADDED
data/Rakefile
ADDED
@@ -0,0 +1,22 @@
|
|
1
|
+
begin
|
2
|
+
require 'bundler/setup'
|
3
|
+
rescue LoadError
|
4
|
+
puts 'You must `gem install bundler` and `bundle install` to run rake tasks'
|
5
|
+
end
|
6
|
+
|
7
|
+
require 'rdoc/task'
|
8
|
+
|
9
|
+
RDoc::Task.new(:rdoc) do |rdoc|
|
10
|
+
rdoc.rdoc_dir = 'rdoc'
|
11
|
+
rdoc.title = 'Ros::Core'
|
12
|
+
rdoc.options << '--line-numbers'
|
13
|
+
rdoc.rdoc_files.include('README.md')
|
14
|
+
rdoc.rdoc_files.include('lib/**/*.rb')
|
15
|
+
end
|
16
|
+
|
17
|
+
APP_RAKEFILE = File.expand_path("spec/dummy/Rakefile", __dir__)
|
18
|
+
load 'rails/tasks/engine.rake'
|
19
|
+
|
20
|
+
load 'rails/tasks/statistics.rake'
|
21
|
+
|
22
|
+
require 'bundler/gem_tasks'
|
@@ -0,0 +1,25 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
class CloudEventSubjectsController < ApplicationController
|
4
|
+
skip_before_action :authenticate_it!, only: [:index]
|
5
|
+
skip_after_action :set_headers!, only: [:index]
|
6
|
+
|
7
|
+
def index
|
8
|
+
render json: json_resources(resource_class: CloudEventSubjectResource, records: resources)
|
9
|
+
end
|
10
|
+
|
11
|
+
private
|
12
|
+
|
13
|
+
def resources
|
14
|
+
path = "#{Settings.event_logging.config.schemas_path}/#{Settings.service.name}"
|
15
|
+
Dir["#{path}/*.avsc"].map do |file_path|
|
16
|
+
CloudEventSubject.new(name(file_path))
|
17
|
+
end.compact
|
18
|
+
end
|
19
|
+
|
20
|
+
def name(file_path)
|
21
|
+
file_name = file_path.split('/').last
|
22
|
+
file_name.slice!('.avsc')
|
23
|
+
"#{Settings.service.name}.#{file_name}"
|
24
|
+
end
|
25
|
+
end
|
@@ -0,0 +1,155 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module Ros
|
4
|
+
module ApplicationControllerConcern
|
5
|
+
extend ActiveSupport::Concern
|
6
|
+
|
7
|
+
included do
|
8
|
+
include JSONAPI::ActsAsResourceController
|
9
|
+
|
10
|
+
before_action :authenticate_it!
|
11
|
+
before_action :set_tenant_context
|
12
|
+
before_action :set_raven_context, if: -> { ENV['SENTRY_DSN'] }
|
13
|
+
after_action :set_headers!
|
14
|
+
|
15
|
+
def authenticate_it!
|
16
|
+
Ros::Sdk::Credential.authorization = request.env['HTTP_AUTHORIZATION']
|
17
|
+
return unless (@current_user = request.env['warden'].authenticate!(:api_token))
|
18
|
+
|
19
|
+
if auth_type.eql?('basic')
|
20
|
+
@current_jwt = Jwt.new(current_user.jwt_payload)
|
21
|
+
elsif auth_type.eql?('bearer')
|
22
|
+
@current_jwt = Jwt.new(request.env['HTTP_AUTHORIZATION'])
|
23
|
+
if (sub_cognito = current_jwt.claims['sub_cognito'])
|
24
|
+
@cognito_user_urn = Ros::Urn.from_urn(sub_cognito)
|
25
|
+
@cognito_user_id = cognito_user_urn.resource_id
|
26
|
+
end
|
27
|
+
end
|
28
|
+
# TODO: Credential.authorization must be an instance variable
|
29
|
+
current_jwt.add_claims(user: current_user.to_json) unless current_jwt.claims.key?(:user)
|
30
|
+
Ros::Sdk::Credential.authorization = "Bearer #{current_jwt.encode(:internal)}"
|
31
|
+
end
|
32
|
+
|
33
|
+
def set_headers!
|
34
|
+
return unless current_jwt
|
35
|
+
|
36
|
+
response.set_header('Authorization', "Bearer #{current_jwt.encode}")
|
37
|
+
response.set_header('Access-Control-Expose-Headers', 'Authorization')
|
38
|
+
end
|
39
|
+
|
40
|
+
def cognito_user_urn
|
41
|
+
@cognito_user_urn
|
42
|
+
end
|
43
|
+
|
44
|
+
def cognito_user_id
|
45
|
+
@cognito_user_id
|
46
|
+
end
|
47
|
+
|
48
|
+
def cognito_user
|
49
|
+
@cognito_user ||= set_cognito_user
|
50
|
+
end
|
51
|
+
|
52
|
+
# NOTE: Unless this is called on the initial request then only internal services will make this call
|
53
|
+
# meaning that if the initial request spawns several internal requests that need the cognito_user object
|
54
|
+
# then the call will be made several times rather than just on the initial request
|
55
|
+
# TODO: Keep an eye on usage patterns and udpate if necessary
|
56
|
+
def set_cognito_user
|
57
|
+
return unless cognito_user_urn
|
58
|
+
|
59
|
+
user = Ros::Cognito::User.find(cognito_user_urn.resource_id).first
|
60
|
+
current_jwt.add_claims(cognito_user: user.to_json)
|
61
|
+
Ros::Sdk::Credential.authorization = "Bearer #{current_jwt.encode(:internal)}"
|
62
|
+
# NOTE: Swallow the error and return nil
|
63
|
+
# TODO: This should probably be logged as a bug since the user should exist
|
64
|
+
rescue JsonApiClient::Errors::NotFound => _e
|
65
|
+
nil
|
66
|
+
end
|
67
|
+
|
68
|
+
def current_user
|
69
|
+
@current_user
|
70
|
+
end
|
71
|
+
|
72
|
+
def current_jwt
|
73
|
+
@current_jwt
|
74
|
+
end
|
75
|
+
|
76
|
+
def auth_type
|
77
|
+
@auth_type ||= request.env.fetch('HTTP_AUTHORIZATION', '').split[0]&.downcase
|
78
|
+
end
|
79
|
+
|
80
|
+
# Next method is for Pundit;
|
81
|
+
# inside JSONAPI resources can reference user with context[:user]
|
82
|
+
def context
|
83
|
+
{ user: ::PolicyUser.new(current_user, cognito_user_id, params: params) }
|
84
|
+
end
|
85
|
+
|
86
|
+
# Custom Array resource serializer:
|
87
|
+
# render json: json_resources(resource_class: SomeResource, records: query.all)
|
88
|
+
def json_resources(resource_class:, records:, context: nil)
|
89
|
+
resource = Array.wrap(records).map { |record| resource_class.new(record, context) }
|
90
|
+
serialize_resource(resource_class, resource)
|
91
|
+
end
|
92
|
+
|
93
|
+
# Custom Single resource serializer:
|
94
|
+
# render json: json_resource(resource_class: SomeResource, record: query.first)
|
95
|
+
def json_resource(resource_class:, record:, context: nil)
|
96
|
+
resource = resource_class.new(record, context)
|
97
|
+
serialize_resource(resource_class, resource)
|
98
|
+
end
|
99
|
+
|
100
|
+
# TODO: Will internal errors still be reported to Sentry.io?
|
101
|
+
if Rails.env.production?
|
102
|
+
# Return JSONAPI Error objects on common errors
|
103
|
+
# https://jsonapi.org/examples/#error-objects-basics
|
104
|
+
rescue_from StandardError do |_error|
|
105
|
+
render(status: :internal_server_error,
|
106
|
+
json: { errors: [{ status: '500', code: :internal_server_error, title: 'Internal Server Error' }] })
|
107
|
+
end
|
108
|
+
end
|
109
|
+
|
110
|
+
# Wrap validation errors with JSONAPI::Exceptions::ValidationErrors for non resource calls
|
111
|
+
rescue_from ActiveRecord::RecordInvalid, with: :handle_validation_errors
|
112
|
+
|
113
|
+
# Return JSONAPI Error objects on common errors
|
114
|
+
# https://jsonapi.org/examples/#error-objects-basics
|
115
|
+
rescue_from Pundit::NotAuthorizedError do |_error|
|
116
|
+
render(status: :forbidden,
|
117
|
+
json: { errors: [{ status: '403', code: :forbidden, title: 'Forbidden' }] })
|
118
|
+
end
|
119
|
+
|
120
|
+
# This method is invoked on 404s from application's routes.rb if it extends
|
121
|
+
# Ros::Routes and includes 'catch_not_found' at the bottom of the routes.rb file
|
122
|
+
def not_found
|
123
|
+
render(status: :not_found,
|
124
|
+
json: { errors: [{ status: '404', code: :not_found, title: 'Not Found' }] })
|
125
|
+
# render jsonapi: nil, code: 404, title: 'Invalid Path', detail: params[:path], status: :not_found
|
126
|
+
end
|
127
|
+
|
128
|
+
private
|
129
|
+
|
130
|
+
def handle_validation_errors(error)
|
131
|
+
resource = ApplicationResource.new(error.record, nil)
|
132
|
+
handle_exceptions JSONAPI::Exceptions::ValidationErrors.new(resource)
|
133
|
+
end
|
134
|
+
|
135
|
+
def jsonapi_params
|
136
|
+
params.require(:data).require(:attributes)
|
137
|
+
end
|
138
|
+
|
139
|
+
def serialize_resource(klass, resource)
|
140
|
+
JSONAPI::ResourceSerializer.new(klass).serialize_to_hash(resource)
|
141
|
+
end
|
142
|
+
|
143
|
+
def set_raven_context
|
144
|
+
# Raven.user_context(id: session[:current_user_id]) # or anything else in session
|
145
|
+
Raven.extra_context(params: params.to_unsafe_h, url: request.url, tenant: Apartment::Tenant.current)
|
146
|
+
end
|
147
|
+
|
148
|
+
def set_tenant_context
|
149
|
+
request.env['X-TenantSchema'] = Apartment::Tenant.current
|
150
|
+
request.env['X-CognitoUserId'] = cognito_user_id
|
151
|
+
request.env['X-IAMUserId'] = current_user&.id
|
152
|
+
end
|
153
|
+
end
|
154
|
+
end
|
155
|
+
end
|
@@ -0,0 +1,26 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
class FileFingerprintsController < ApplicationController
|
4
|
+
def index
|
5
|
+
render json: json_resources(resource_class: FileFingerprintResource, records: resources)
|
6
|
+
end
|
7
|
+
|
8
|
+
private
|
9
|
+
|
10
|
+
def resources
|
11
|
+
# @TODO: Add proper filters based on resource class
|
12
|
+
if params.dig(:filter, :model_name)
|
13
|
+
models.select! { |model| model.model_name.downcase == params[:filter][:model_name].downcase }
|
14
|
+
end
|
15
|
+
models.map! { |model| FileFingerprintResource.new(model, nil) }
|
16
|
+
end
|
17
|
+
|
18
|
+
# This method smells of :reek:ManualDispatch
|
19
|
+
def models
|
20
|
+
@models ||= Ros.table_names.map do |table|
|
21
|
+
klass = table.classify.constantize
|
22
|
+
columns = klass.respond_to?(:file_fingerprint_attributes) ? klass.file_fingerprint_attributes : klass.column_names
|
23
|
+
FileFingerprint.new(table.classify, columns)
|
24
|
+
end.compact
|
25
|
+
end
|
26
|
+
end
|
@@ -0,0 +1,33 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
# NOTE:
|
4
|
+
# Automatically retry jobs that encountered a deadlock:
|
5
|
+
# retry_on ActiveRecord::Deadlocked
|
6
|
+
# Most jobs are safe to ignore if the underlying records are no longer available:
|
7
|
+
# discard_on ActiveJob::DeserializationError
|
8
|
+
|
9
|
+
module Ros
|
10
|
+
class ApplicationJob < ActiveJob::Base
|
11
|
+
attr_accessor :tenant
|
12
|
+
|
13
|
+
queue_as "#{Settings.service.name}_default"
|
14
|
+
|
15
|
+
before_perform do
|
16
|
+
schema_name = Apartment::Tenant.current
|
17
|
+
next unless (@tenant = Tenant.find_by(schema_name: schema_name))
|
18
|
+
|
19
|
+
@tenant.set_role_credential
|
20
|
+
# TODO: Fix this. Use tenant's settings instead of static zone
|
21
|
+
Time.zone = 'Asia/Singapore'
|
22
|
+
end
|
23
|
+
|
24
|
+
def perform(*params)
|
25
|
+
operation_class.call(params)
|
26
|
+
end
|
27
|
+
|
28
|
+
def operation_class
|
29
|
+
job_name = self.class.name.gsub('Job', '')
|
30
|
+
job_name.constantize
|
31
|
+
end
|
32
|
+
end
|
33
|
+
end
|
@@ -0,0 +1,13 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module Ros
|
4
|
+
class TenantProducerEventJob < Ros::ApplicationJob
|
5
|
+
def perform(object)
|
6
|
+
_data = { event: object.persisted?, data: object }.to_json
|
7
|
+
# Have any notifications been configured for this object+event combination?
|
8
|
+
# If no then return, otherwise execute the notification
|
9
|
+
# This will be a read of the database table 'tenant_notifications'
|
10
|
+
# and then execute an http(s) POST to the configured endpoint
|
11
|
+
end
|
12
|
+
end
|
13
|
+
end
|
@@ -0,0 +1,20 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
class CloudEventSubject
|
4
|
+
include ActiveModel::Model
|
5
|
+
|
6
|
+
attr_reader :id, :name
|
7
|
+
|
8
|
+
def initialize(name)
|
9
|
+
@id = SecureRandom.uuid
|
10
|
+
@name = name
|
11
|
+
end
|
12
|
+
|
13
|
+
def readonly?
|
14
|
+
true
|
15
|
+
end
|
16
|
+
|
17
|
+
def persisted?
|
18
|
+
false
|
19
|
+
end
|
20
|
+
end
|
@@ -0,0 +1,112 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module AssociationResource
|
4
|
+
extend ActiveSupport::Concern
|
5
|
+
|
6
|
+
def method_missing(method, *params)
|
7
|
+
association = self.class.find_resource(method)
|
8
|
+
return super if association.blank?
|
9
|
+
|
10
|
+
association.call(self)
|
11
|
+
rescue JsonApiClient::Errors::ApiError => _e
|
12
|
+
nil
|
13
|
+
end
|
14
|
+
|
15
|
+
def respond_to_missing?(method, include_private = false)
|
16
|
+
self.class.find_resource(method).present? || super
|
17
|
+
end
|
18
|
+
|
19
|
+
# Returns new instance of the resource or nil
|
20
|
+
# @model.resource(:resource)&.tap do {|resource| resource.name = 'name'; resource.save}
|
21
|
+
def resource(name)
|
22
|
+
resource_klass = _resource_class(name)
|
23
|
+
return unless resource_klass
|
24
|
+
|
25
|
+
resource_klass.new
|
26
|
+
end
|
27
|
+
|
28
|
+
# yields query for a given resource
|
29
|
+
# @model.query_resource(:resource) {|query| query.where(some: 'hing')}
|
30
|
+
def query_resource(name)
|
31
|
+
resource_klass = self.class.find_resource(name)
|
32
|
+
return unless resource_klass
|
33
|
+
|
34
|
+
resource_klass.query_resource(self) do |query|
|
35
|
+
yield query
|
36
|
+
end
|
37
|
+
rescue JsonApiClient::Errors::ApiError => _e
|
38
|
+
nil
|
39
|
+
end
|
40
|
+
|
41
|
+
private
|
42
|
+
|
43
|
+
def _resource_class(name)
|
44
|
+
association = self.class.find_resource(name)
|
45
|
+
return if association.nil?
|
46
|
+
|
47
|
+
association._resource_class(self)
|
48
|
+
end
|
49
|
+
|
50
|
+
class_methods do
|
51
|
+
def resource_associations
|
52
|
+
@resource_associations ||= []
|
53
|
+
end
|
54
|
+
|
55
|
+
# Adds link to external ONE_ONE association.
|
56
|
+
# :resource_name required. Model will respond this name to query external resource
|
57
|
+
# :class_name required for non-polymorphic associations. Should respond to `where` and `find`
|
58
|
+
def belongs_to_resource(resource_name, class_name: nil, foreign_key: nil, polymorphic: false)
|
59
|
+
return if find_resource(resource_name).present?
|
60
|
+
|
61
|
+
resource_associations << BelongsToResource.new(
|
62
|
+
name: resource_name,
|
63
|
+
class_name: class_name,
|
64
|
+
foreign_key: foreign_key,
|
65
|
+
polymorphic: polymorphic
|
66
|
+
)
|
67
|
+
end
|
68
|
+
|
69
|
+
# Adds link to external ONE_ONE association. Oposite of belongs_to_resource
|
70
|
+
# :resource_name required. Model will respond this name to query external resources
|
71
|
+
# :class_name required. Should respond to `where` and `find`
|
72
|
+
# :as represents polymorphic relation. type will be added to query:
|
73
|
+
# User.has_one_resource(:some_resource, class_name: 'Some::Resource', as: :external) ->
|
74
|
+
# Some::Resource.where(external_type: 'User', external_id: user.id)
|
75
|
+
# rubocop:disable Naming/PredicateName
|
76
|
+
def has_one_resource(resource_name, class_name:, foreign_key: nil, as: nil)
|
77
|
+
return if find_resource(resource_name).present?
|
78
|
+
|
79
|
+
resource_associations << HasOneResource.new(
|
80
|
+
name: resource_name,
|
81
|
+
class_name: class_name,
|
82
|
+
foreign_key: foreign_key,
|
83
|
+
associated_name: as
|
84
|
+
)
|
85
|
+
end
|
86
|
+
# rubocop:enable Naming/PredicateName
|
87
|
+
|
88
|
+
# Adds link to external ONE_MANY association.
|
89
|
+
# :resource_name required. Model will respond this name to query external resources
|
90
|
+
# :class_name required. Should respond to `where` and `find`
|
91
|
+
# :as represents polymorphic relation. type will be added to query:
|
92
|
+
# User.has_many_resources(:some_resource, class_name: 'Some::Resource', as: :external) ->
|
93
|
+
# Some::Resource.where(external_type: 'User', external_id: user.id)
|
94
|
+
|
95
|
+
# rubocop:disable Naming/PredicateName
|
96
|
+
def has_many_resources(resource_name, class_name:, foreign_key: nil, as: nil)
|
97
|
+
return if find_resource(resource_name).present?
|
98
|
+
|
99
|
+
resource_associations << HasManyResources.new(
|
100
|
+
name: resource_name,
|
101
|
+
class_name: class_name,
|
102
|
+
foreign_key: foreign_key,
|
103
|
+
associated_name: as
|
104
|
+
)
|
105
|
+
end
|
106
|
+
# rubocop:enable Naming/PredicateName
|
107
|
+
|
108
|
+
def find_resource(resource_name)
|
109
|
+
resource_associations.find { |resource| resource.name == resource_name }
|
110
|
+
end
|
111
|
+
end
|
112
|
+
end
|