Class: Kabk::RestEngine
- Inherits:
-
Object
- Object
- Kabk::RestEngine
- Defined in:
- lib/kabk/rest_engine.rb
Overview
Generic CRUD engine for any registered resource, agnostic to the underlying database
Instance Method Summary collapse
-
#create(params, context: {}) ⇒ Hash
Create a new resource.
-
#delete(id, context: {}) ⇒ Hash
Delete a resource by ID.
-
#get(id, context: {}) ⇒ Hash
Get single resource by ID.
-
#initialize(resource_name) ⇒ RestEngine
constructor
A new instance of RestEngine.
-
#list(params, context: {}) ⇒ Hash
List resources with pagination, sorting, filtering.
-
#update(id, params, context: {}) ⇒ Hash
Update an existing resource.
Constructor Details
#initialize(resource_name) ⇒ RestEngine
Returns a new instance of RestEngine.
9 10 11 12 13 14 15 |
# File 'lib/kabk/rest_engine.rb', line 9 def initialize(resource_name) @resource = Registry.instance.get(resource_name) raise NotFoundError, "Resource not found" unless @resource @adapter = @resource.adapter raise StandardError, "Resource has no adapter configured" unless @adapter end |
Instance Method Details
#create(params, context: {}) ⇒ Hash
Create a new resource. Executes lifecycle hooks, validates parameters, and delegates to the adapter.
41 42 43 44 45 46 47 48 49 50 |
# File 'lib/kabk/rest_engine.rb', line 41 def create(params, context: {}) @resource.hooks[:before_create]&.call(params, context) sanitized = Validator.validate_and_sanitize!(@resource, params) result = @adapter.create(sanitized, context: context) @resource.hooks[:after_create]&.call(result[:data], context) result rescue ApiError => e e.to_h end |
#delete(id, context: {}) ⇒ Hash
Delete a resource by ID. Executes lifecycle hooks and delegates to the adapter.
74 75 76 77 78 79 80 81 82 |
# File 'lib/kabk/rest_engine.rb', line 74 def delete(id, context: {}) @resource.hooks[:before_delete]&.call(id, context) result = @adapter.delete(id, context: context) @resource.hooks[:after_delete]&.call(id, context) result rescue ApiError => e e.to_h end |
#get(id, context: {}) ⇒ Hash
Get single resource by ID.
32 33 34 |
# File 'lib/kabk/rest_engine.rb', line 32 def get(id, context: {}) @adapter.get(id, context: context) end |
#list(params, context: {}) ⇒ Hash
List resources with pagination, sorting, filtering.
22 23 24 |
# File 'lib/kabk/rest_engine.rb', line 22 def list(params, context: {}) @adapter.list(params, context: context) end |
#update(id, params, context: {}) ⇒ Hash
Update an existing resource. Executes lifecycle hooks and validates Optimistic Concurrency Control (OCC).
58 59 60 61 62 63 64 65 66 67 |
# File 'lib/kabk/rest_engine.rb', line 58 def update(id, params, context: {}) @resource.hooks[:before_update]&.call(id, params, context) sanitized = Validator.validate_and_sanitize!(@resource, params, is_update: true) result = @adapter.update(id, sanitized, context: context) @resource.hooks[:after_update]&.call(result[:data], context) result rescue ApiError => e e.to_h end |