Class: Apiwork::Contract::Base
- Inherits:
-
Object
- Object
- Apiwork::Contract::Base
- Includes:
- Abstractable
- Defined in:
- lib/apiwork/contract/base.rb
Overview
Base class for contracts.
Validates requests and defines response shapes. Drives type generation and request parsing. Types are defined manually per action or auto-generated from a linked representation.
Class Attribute Summary collapse
- .building ⇒ Object writeonly
-
.representation_class ⇒ Class<Representation::Base>?
readonly
The representation class for this contract.
Instance Attribute Summary collapse
- #action_name ⇒ Object readonly
-
#issues ⇒ Array<Issue>
readonly
The issues for this contract.
- #request ⇒ Object readonly
Class Method Summary collapse
-
.abstract! ⇒ void
Marks this contract as abstract.
-
.abstract? ⇒ Boolean
Whether this contract is abstract.
-
.action(name, replace: false) {|action| ... } ⇒ Contract::Action
Defines or extends an action on this contract.
- .action_for(action_name) ⇒ Object
- .actions ⇒ Object
- .api_class ⇒ Object
- .build_synthetic_contract(representation_class, api_class) ⇒ Object
- .building? ⇒ Boolean
- .contract_for(representation_class) ⇒ Object
-
.enum(name, deprecated: false, description: nil, example: nil, values: nil) ⇒ void
Defines or extends an enum for this contract.
- .enum?(name) ⇒ Boolean
- .enum_values(enum_name, visited: Set.new) ⇒ Object
-
.fragment(name) {|object| ... } ⇒ void
Defines a fragment type for this contract.
-
.identifier(value = nil) ⇒ String?
Prefixes types, enums, and unions in introspection output.
-
.import(klass, as:) ⇒ void
Imports types from another contract for reuse.
- .imports ⇒ Object
-
.introspect(expand: false, locale: nil) ⇒ Introspection::Contract
Returns introspection data for this contract.
-
.object(name, deprecated: false, description: nil, example: nil) {|object| ... } ⇒ void
Defines or extends an object type for this contract.
- .parse_response(response, action) ⇒ Object
-
.representation(klass) ⇒ void
Configures the representation class for this contract.
- .representation? ⇒ Boolean
- .resolve_custom_type(type_name, visited: Set.new) ⇒ Object
- .scope_prefix ⇒ Object
- .scoped_enum_name(name) ⇒ Object
- .scoped_type_name(name) ⇒ Object
- .synthetic? ⇒ Boolean
- .synthetic_contracts ⇒ Object
- .type?(name) ⇒ Boolean
-
.union(name, deprecated: false, description: nil, discriminator: nil, example: nil) {|union| ... } ⇒ void
Defines or extends a discriminated union for this contract.
Instance Method Summary collapse
-
#body ⇒ Hash
The body for this contract.
-
#initialize(action_name, request, coerce: false) ⇒ Base
constructor
A new instance of Base.
-
#invalid? ⇒ Boolean
Whether this contract is invalid.
-
#query ⇒ Hash
The query for this contract.
-
#valid? ⇒ Boolean
Whether this contract is valid.
Constructor Details
#initialize(action_name, request, coerce: false) ⇒ Base
Returns a new instance of Base.
675 676 677 678 679 680 681 |
# File 'lib/apiwork/contract/base.rb', line 675 def initialize(action_name, request, coerce: false) request = normalize_request(request) result = RequestParser.parse(self.class, action_name, request, coerce:) @request = prepare_request(result.request) @action_name = action_name.to_sym @issues = result.issues end |
Class Attribute Details
.building=(value) ⇒ Object (writeonly)
502 503 504 |
# File 'lib/apiwork/contract/base.rb', line 502 def building=(value) @building = value end |
.representation_class ⇒ Class<Representation::Base>? (readonly)
The representation class for this contract.
97 98 99 |
# File 'lib/apiwork/contract/base.rb', line 97 def representation_class @representation_class end |
Instance Attribute Details
#action_name ⇒ Object (readonly)
54 55 56 |
# File 'lib/apiwork/contract/base.rb', line 54 def action_name @action_name end |
#issues ⇒ Array<Issue> (readonly)
The issues for this contract.
54 55 56 |
# File 'lib/apiwork/contract/base.rb', line 54 attr_reader :action_name, :issues, :request |
#request ⇒ Object (readonly)
54 55 56 |
# File 'lib/apiwork/contract/base.rb', line 54 def request @request end |
Class Method Details
.abstract! ⇒ void
This method returns an undefined value.
Marks this contract as abstract.
Abstract contracts serve as base classes for other contracts. Use this when creating application-wide base contracts that define shared imports or configuration. Subclasses automatically become non-abstract.
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 |
# File 'lib/apiwork/contract/base.rb', line 47 class Base include Abstractable # @!attribute [r] issues # @api public # The issues for this contract. # @return [Array<Issue>] attr_reader :action_name, :issues, :request # @!method body # @api public # The body for this contract. # # Use this in controller actions to access validated request data. # Contains type-coerced values matching your contract definition. # Invalid requests are rejected before the action runs. # # @return [Hash] # # @example # def create # Invoice.create!(contract.body[:invoice]) # end # # @!method query # @api public # The query for this contract. # # Use this in controller actions to access validated request data. # Contains type-coerced values matching your contract definition. # Invalid requests are rejected before the action runs. # # @return [Hash] # # @example # def index # Invoice.where(status: contract.query[:status]) # end delegate :body, :query, to: :request class << self # @api public # The representation class for this contract. # # @return [Class<Representation::Base>, nil] # @see .representation attr_reader :representation_class # @api public # Prefixes types, enums, and unions in introspection output. # # Must be unique within the API. Derived from the contract class # name when not set (e.g., `RecurringInvoiceContract` becomes # `recurring_invoice`). # # @param value [Symbol, String, nil] (nil) # The identifier prefix. # @return [String, nil] # # @example # class InvoiceContract < Apiwork::Contract::Base # identifier :billing # # object :address do # string :street # end # # In introspection: :address becomes :billing_address # end def identifier(value = nil) return @identifier if value.nil? @identifier = value.to_s end # @api public # Configures the representation class for this contract. # # Adapters use the representation to auto-generate request/response # types. Use {.representation_class} to retrieve. # # @param klass [Class<Representation::Base>] # The representation class. # @return [void] # @raise [ArgumentError] if klass is not a Representation subclass # # @example # class InvoiceContract < Apiwork::Contract::Base # representation InvoiceRepresentation # end def representation(klass) unless klass.is_a?(Class) raise ConfigurationError, "representation must be a Representation class, got #{klass.class}. " \ "Use: representation InvoiceRepresentation (not 'InvoiceRepresentation' or :invoice)" end unless klass < Representation::Base raise ConfigurationError, 'representation must be a Representation class (subclass of Apiwork::Representation::Base), ' \ "got #{klass}" end @representation_class = klass end # @api public # Defines or extends an object type for this contract. # # Subclasses inherit parent types. In introspection, types are prefixed with the # contract's {.identifier} (e.g., `:item` in `InvoiceContract` becomes `:invoice_item`). # # Multiple calls with the same name merge fields (declaration merging). # # @param name [Symbol] # The object name. # @param deprecated [Boolean] (false) # Whether deprecated. Metadata included in exports. # @param description [String, nil] (nil) # The description. Metadata included in exports. # @param example [Object, nil] (nil) # The example. Metadata included in exports. # @yieldparam object [API::Object] # @return [void] # # @example Define and reference # object :item do # string :description # decimal :amount # end # # action :create do # request do # body do # array :items do # reference :item # end # end # end # end # # @example Different shapes for request and response # object :invoice do # uuid :id # string :number # string :status # end # # object :invoice_payload do # string :number # string :status # end # # action :create do # request do # body do # reference :invoice, to: :invoice_payload # end # end # response do # body do # reference :invoice # end # end # end def object( name, deprecated: false, description: nil, example: nil, &block ) api_class.register_object( name, deprecated:, description:, example:, scope: self, &block ) end # @api public # Defines a fragment type for this contract. # # Fragments are only available for merging into other types and never appear as standalone types. Use # fragments to define reusable field groups. # # @param name [Symbol] # The fragment name. # @yieldparam object [API::Object] # @return [void] # # @example Reusable timestamps # fragment :timestamps do # datetime :created_at # datetime :updated_at # end # # object :invoice do # merge :timestamps # string :number # end def fragment(name, &block) api_class.register_fragment(name, scope: self, &block) end # @api public # Defines or extends an enum for this contract. # # Subclasses inherit parent enums. In introspection, enums are prefixed with the # contract's {.identifier} (e.g., `:status` in `InvoiceContract` becomes `:invoice_status`). # # Multiple calls with the same name merge values (declaration merging). # # @param name [Symbol] # The enum name. # @param deprecated [Boolean] (false) # Whether deprecated. Metadata included in exports. # @param description [String, nil] (nil) # The description. Metadata included in exports. # @param example [String, nil] (nil) # The example. Metadata included in exports. # @param values [Array<String>, nil] (nil) # The allowed values. # @return [void] # # @example Define and reference # enum :status, values: %w[draft sent paid] # # action :update do # request do # body do # string :status, enum: :status # end # end # end # # @example Inline values (without separate definition) # action :index do # request do # query do # string? :priority, enum: %w[low medium high] # end # end # end def enum( name, deprecated: false, description: nil, example: nil, values: nil ) api_class.register_enum( name, deprecated:, description:, example:, values:, scope: self, ) end # @api public # Defines or extends a discriminated union for this contract. # # Subclasses inherit parent unions. In introspection, unions are prefixed with the # contract's {.identifier} (e.g., `:payment_method` in `InvoiceContract` becomes `:invoice_payment_method`). # # Multiple calls with the same name merge variants (declaration merging). # # @param name [Symbol] # The union name. # @param deprecated [Boolean] (false) # Whether deprecated. Metadata included in exports. # @param description [String, nil] (nil) # The description. Metadata included in exports. # @param discriminator [Symbol, nil] (nil) # The discriminator field name. # @param example [Object, nil] (nil) # The example. Metadata included in exports. # @yieldparam union [API::Union] # @return [void] # # @example Define and reference # union :payment_method, discriminator: :type do # variant tag: 'card' do # object do # string :last_four # end # end # variant tag: 'bank_transfer' do # object do # string :bank_name # string :account_number # end # end # end # # action :create do # request do # body do # reference :payment_method # end # end # end def union( name, deprecated: false, description: nil, discriminator: nil, example: nil, &block ) api_class.register_union( name, deprecated:, description:, discriminator:, example:, scope: self, &block ) end # @api public # Imports types from another contract for reuse. # # Imported types are accessed with a prefix matching the alias. # # @param klass [Class<Contract::Base>] # The contract class to import types from. # @param as [Symbol] # The alias prefix. # @return [void] # @raise [ArgumentError] if klass is not a Contract subclass # @raise [ArgumentError] if as is not a Symbol # # @example # import UserContract, as: :user # # UserContract's :address becomes :user_address def import(klass, as:) unless klass.is_a?(Class) raise ConfigurationError, "import must be a Class constant, got #{klass.class}. " \ "Use: import UserContract, as: :user (not 'UserContract' or :user_contract)" end unless klass < Contract::Base raise ConfigurationError, 'import must be a Contract class (subclass of Apiwork::Contract::Base), ' \ "got #{klass}" end unless as.is_a?(Symbol) raise ConfigurationError, "import alias must be a Symbol, got #{as.class}. " \ 'Use: import UserContract, as: :user' end imports[as] = klass return if klass.building? return unless klass.representation? && klass.api_class klass.building = true begin klass.api_class.ensure_contract_built!(klass) ensure klass.building = false end end # @api public # Defines or extends an action on this contract. # # Multiple calls with the same name merge definitions (declaration merging). # # @param name [Symbol] # The action name. Matches your controller action. # @param replace [Boolean] (false) # Whether to discard any existing definition and start fresh. Use when overriding # auto-generated actions from representation. # @yieldparam action [Contract::Action] # @return [Contract::Action] # # @example Query parameters # action :index do # request do # query do # string? :search # integer? :page # end # end # end # # @example Request body with custom type # action :create do # request do # body do # reference :invoice, to: :invoice_payload # end # end # response do # body do # reference :invoice # end # end # end # # @example Override auto-generated action # action :destroy, replace: true do # response do # body do # reference :invoice # end # end # end # # @example No content response # action :destroy do # response { no_content! } # end def action(name, replace: false, &block) name = name.to_sym action = if replace Action.new(self, name, replace: true) else actions[name] ||= Action.new(self, name) end if block_given? block.arity.positive? ? yield(action) : action.instance_eval(&block) end actions[name] = action end # @api public # Returns introspection data for this contract. # # @param expand [Boolean] (false) # Whether to expand all types inline. # @param locale [Symbol, nil] (nil) # The locale for translations. # @return [Introspection::Contract] # # @example # InvoiceContract.introspect def introspect(expand: false, locale: nil) api_class.introspect_contract(self, expand:, locale:) end attr_writer :building def actions @actions ||= {} end def imports @imports ||= {} end def building? @building end def synthetic_contracts @synthetic_contracts ||= {} end def synthetic? @synthetic == true end def contract_for(representation_class) return nil unless representation_class&.name contract_name = representation_class.name.sub(/Representation\z/, 'Contract') contract_class = contract_name.safe_constantize return contract_class if contract_class.is_a?(Class) && contract_class < Contract::Base synthetic_contracts[representation_class] ||= build_synthetic_contract(representation_class, api_class) end def build_synthetic_contract(representation_class, api_class) Class.new(Contract::Base) do @synthetic = true @representation_class = representation_class @api_class = api_class end end def representation? representation_class.present? end def scope_prefix return @identifier if @identifier if name name .demodulize .delete_suffix('Contract') .underscore elsif representation_class representation_class.name .demodulize .delete_suffix('Representation') .underscore end end def resolve_custom_type(type_name, visited: Set.new) raise ConfigurationError, "Circular import detected while resolving :#{type_name}" if visited.include?(self) if api_class result = api_class.type_definition(type_name, scope: self) return result if result end result = resolve_imported_type(type_name, visited: visited.dup.add(self)) return result if result resolve_parent_type(type_name, visited: visited.dup.add(self)) end def action_for(action_name) api_class.ensure_contract_built!(self) action_name = action_name.to_sym actions[action_name] end def api_class return @api_class if @api_class return nil unless name namespace = name.deconstantize return nil if namespace.blank? API.find("/#{namespace.underscore.tr('::', '/')}") end def parse_response(response, action) ResponseParser.parse(self, action, response) end def type?(name) resolve_custom_type(name).present? end def enum?(name) enum_values(name).present? end def enum_values(enum_name, visited: Set.new) return nil if visited.include?(self) if api_class result = api_class.enum_values(enum_name, scope: self) return result if result end result = resolve_imported_enum_values(enum_name, visited: visited.dup.add(self)) return result if result resolve_parent_enum_values(enum_name, visited: visited.dup.add(self)) end def scoped_type_name(name) api_class.scoped_type_name(self, name) end def scoped_enum_name(name) api_class.scoped_enum_name(self, name) end private def resolve_imported_type(type_name, visited:) type_string = type_name.to_s imports.each do |import_alias, imported_contract| prefix = "#{import_alias}_" next unless type_string.start_with?(prefix) unprefixed_name = type_string.delete_prefix(prefix).to_sym result = imported_contract.resolve_custom_type(unprefixed_name, visited:) return result if result end nil end def resolve_parent_type(type_name, visited:) parent = superclass return nil unless parent < Contract::Base parent.resolve_custom_type(type_name, visited:) end def resolve_imported_enum_values(enum_name, visited:) enum_string = enum_name.to_s imports.each do |import_alias, imported_contract| prefix = "#{import_alias}_" next unless enum_string.start_with?(prefix) unprefixed_name = enum_string.delete_prefix(prefix).to_sym result = imported_contract.enum_values(unprefixed_name, visited:) return result if result end nil end def resolve_parent_enum_values(enum_name, visited:) parent = superclass return nil unless parent < Contract::Base parent.enum_values(enum_name, visited:) end end def initialize(action_name, request, coerce: false) request = normalize_request(request) result = RequestParser.parse(self.class, action_name, request, coerce:) @request = prepare_request(result.request) @action_name = action_name.to_sym @issues = result.issues end # @api public # Whether this contract is valid. # # @return [Boolean] def valid? issues.empty? end # @api public # Whether this contract is invalid. # # @return [Boolean] def invalid? issues.any? end private def normalize_request(request) api_class = self.class.api_class result = api_class.normalize_request(request) api_class.adapter.apply_request_transformers(result, phase: :before) end def prepare_request(request) api_class = self.class.api_class result = api_class.prepare_request(request) api_class.adapter.apply_request_transformers(result, phase: :after) end end |
.abstract? ⇒ Boolean
Whether this contract is abstract.
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 |
# File 'lib/apiwork/contract/base.rb', line 47 class Base include Abstractable # @!attribute [r] issues # @api public # The issues for this contract. # @return [Array<Issue>] attr_reader :action_name, :issues, :request # @!method body # @api public # The body for this contract. # # Use this in controller actions to access validated request data. # Contains type-coerced values matching your contract definition. # Invalid requests are rejected before the action runs. # # @return [Hash] # # @example # def create # Invoice.create!(contract.body[:invoice]) # end # # @!method query # @api public # The query for this contract. # # Use this in controller actions to access validated request data. # Contains type-coerced values matching your contract definition. # Invalid requests are rejected before the action runs. # # @return [Hash] # # @example # def index # Invoice.where(status: contract.query[:status]) # end delegate :body, :query, to: :request class << self # @api public # The representation class for this contract. # # @return [Class<Representation::Base>, nil] # @see .representation attr_reader :representation_class # @api public # Prefixes types, enums, and unions in introspection output. # # Must be unique within the API. Derived from the contract class # name when not set (e.g., `RecurringInvoiceContract` becomes # `recurring_invoice`). # # @param value [Symbol, String, nil] (nil) # The identifier prefix. # @return [String, nil] # # @example # class InvoiceContract < Apiwork::Contract::Base # identifier :billing # # object :address do # string :street # end # # In introspection: :address becomes :billing_address # end def identifier(value = nil) return @identifier if value.nil? @identifier = value.to_s end # @api public # Configures the representation class for this contract. # # Adapters use the representation to auto-generate request/response # types. Use {.representation_class} to retrieve. # # @param klass [Class<Representation::Base>] # The representation class. # @return [void] # @raise [ArgumentError] if klass is not a Representation subclass # # @example # class InvoiceContract < Apiwork::Contract::Base # representation InvoiceRepresentation # end def representation(klass) unless klass.is_a?(Class) raise ConfigurationError, "representation must be a Representation class, got #{klass.class}. " \ "Use: representation InvoiceRepresentation (not 'InvoiceRepresentation' or :invoice)" end unless klass < Representation::Base raise ConfigurationError, 'representation must be a Representation class (subclass of Apiwork::Representation::Base), ' \ "got #{klass}" end @representation_class = klass end # @api public # Defines or extends an object type for this contract. # # Subclasses inherit parent types. In introspection, types are prefixed with the # contract's {.identifier} (e.g., `:item` in `InvoiceContract` becomes `:invoice_item`). # # Multiple calls with the same name merge fields (declaration merging). # # @param name [Symbol] # The object name. # @param deprecated [Boolean] (false) # Whether deprecated. Metadata included in exports. # @param description [String, nil] (nil) # The description. Metadata included in exports. # @param example [Object, nil] (nil) # The example. Metadata included in exports. # @yieldparam object [API::Object] # @return [void] # # @example Define and reference # object :item do # string :description # decimal :amount # end # # action :create do # request do # body do # array :items do # reference :item # end # end # end # end # # @example Different shapes for request and response # object :invoice do # uuid :id # string :number # string :status # end # # object :invoice_payload do # string :number # string :status # end # # action :create do # request do # body do # reference :invoice, to: :invoice_payload # end # end # response do # body do # reference :invoice # end # end # end def object( name, deprecated: false, description: nil, example: nil, &block ) api_class.register_object( name, deprecated:, description:, example:, scope: self, &block ) end # @api public # Defines a fragment type for this contract. # # Fragments are only available for merging into other types and never appear as standalone types. Use # fragments to define reusable field groups. # # @param name [Symbol] # The fragment name. # @yieldparam object [API::Object] # @return [void] # # @example Reusable timestamps # fragment :timestamps do # datetime :created_at # datetime :updated_at # end # # object :invoice do # merge :timestamps # string :number # end def fragment(name, &block) api_class.register_fragment(name, scope: self, &block) end # @api public # Defines or extends an enum for this contract. # # Subclasses inherit parent enums. In introspection, enums are prefixed with the # contract's {.identifier} (e.g., `:status` in `InvoiceContract` becomes `:invoice_status`). # # Multiple calls with the same name merge values (declaration merging). # # @param name [Symbol] # The enum name. # @param deprecated [Boolean] (false) # Whether deprecated. Metadata included in exports. # @param description [String, nil] (nil) # The description. Metadata included in exports. # @param example [String, nil] (nil) # The example. Metadata included in exports. # @param values [Array<String>, nil] (nil) # The allowed values. # @return [void] # # @example Define and reference # enum :status, values: %w[draft sent paid] # # action :update do # request do # body do # string :status, enum: :status # end # end # end # # @example Inline values (without separate definition) # action :index do # request do # query do # string? :priority, enum: %w[low medium high] # end # end # end def enum( name, deprecated: false, description: nil, example: nil, values: nil ) api_class.register_enum( name, deprecated:, description:, example:, values:, scope: self, ) end # @api public # Defines or extends a discriminated union for this contract. # # Subclasses inherit parent unions. In introspection, unions are prefixed with the # contract's {.identifier} (e.g., `:payment_method` in `InvoiceContract` becomes `:invoice_payment_method`). # # Multiple calls with the same name merge variants (declaration merging). # # @param name [Symbol] # The union name. # @param deprecated [Boolean] (false) # Whether deprecated. Metadata included in exports. # @param description [String, nil] (nil) # The description. Metadata included in exports. # @param discriminator [Symbol, nil] (nil) # The discriminator field name. # @param example [Object, nil] (nil) # The example. Metadata included in exports. # @yieldparam union [API::Union] # @return [void] # # @example Define and reference # union :payment_method, discriminator: :type do # variant tag: 'card' do # object do # string :last_four # end # end # variant tag: 'bank_transfer' do # object do # string :bank_name # string :account_number # end # end # end # # action :create do # request do # body do # reference :payment_method # end # end # end def union( name, deprecated: false, description: nil, discriminator: nil, example: nil, &block ) api_class.register_union( name, deprecated:, description:, discriminator:, example:, scope: self, &block ) end # @api public # Imports types from another contract for reuse. # # Imported types are accessed with a prefix matching the alias. # # @param klass [Class<Contract::Base>] # The contract class to import types from. # @param as [Symbol] # The alias prefix. # @return [void] # @raise [ArgumentError] if klass is not a Contract subclass # @raise [ArgumentError] if as is not a Symbol # # @example # import UserContract, as: :user # # UserContract's :address becomes :user_address def import(klass, as:) unless klass.is_a?(Class) raise ConfigurationError, "import must be a Class constant, got #{klass.class}. " \ "Use: import UserContract, as: :user (not 'UserContract' or :user_contract)" end unless klass < Contract::Base raise ConfigurationError, 'import must be a Contract class (subclass of Apiwork::Contract::Base), ' \ "got #{klass}" end unless as.is_a?(Symbol) raise ConfigurationError, "import alias must be a Symbol, got #{as.class}. " \ 'Use: import UserContract, as: :user' end imports[as] = klass return if klass.building? return unless klass.representation? && klass.api_class klass.building = true begin klass.api_class.ensure_contract_built!(klass) ensure klass.building = false end end # @api public # Defines or extends an action on this contract. # # Multiple calls with the same name merge definitions (declaration merging). # # @param name [Symbol] # The action name. Matches your controller action. # @param replace [Boolean] (false) # Whether to discard any existing definition and start fresh. Use when overriding # auto-generated actions from representation. # @yieldparam action [Contract::Action] # @return [Contract::Action] # # @example Query parameters # action :index do # request do # query do # string? :search # integer? :page # end # end # end # # @example Request body with custom type # action :create do # request do # body do # reference :invoice, to: :invoice_payload # end # end # response do # body do # reference :invoice # end # end # end # # @example Override auto-generated action # action :destroy, replace: true do # response do # body do # reference :invoice # end # end # end # # @example No content response # action :destroy do # response { no_content! } # end def action(name, replace: false, &block) name = name.to_sym action = if replace Action.new(self, name, replace: true) else actions[name] ||= Action.new(self, name) end if block_given? block.arity.positive? ? yield(action) : action.instance_eval(&block) end actions[name] = action end # @api public # Returns introspection data for this contract. # # @param expand [Boolean] (false) # Whether to expand all types inline. # @param locale [Symbol, nil] (nil) # The locale for translations. # @return [Introspection::Contract] # # @example # InvoiceContract.introspect def introspect(expand: false, locale: nil) api_class.introspect_contract(self, expand:, locale:) end attr_writer :building def actions @actions ||= {} end def imports @imports ||= {} end def building? @building end def synthetic_contracts @synthetic_contracts ||= {} end def synthetic? @synthetic == true end def contract_for(representation_class) return nil unless representation_class&.name contract_name = representation_class.name.sub(/Representation\z/, 'Contract') contract_class = contract_name.safe_constantize return contract_class if contract_class.is_a?(Class) && contract_class < Contract::Base synthetic_contracts[representation_class] ||= build_synthetic_contract(representation_class, api_class) end def build_synthetic_contract(representation_class, api_class) Class.new(Contract::Base) do @synthetic = true @representation_class = representation_class @api_class = api_class end end def representation? representation_class.present? end def scope_prefix return @identifier if @identifier if name name .demodulize .delete_suffix('Contract') .underscore elsif representation_class representation_class.name .demodulize .delete_suffix('Representation') .underscore end end def resolve_custom_type(type_name, visited: Set.new) raise ConfigurationError, "Circular import detected while resolving :#{type_name}" if visited.include?(self) if api_class result = api_class.type_definition(type_name, scope: self) return result if result end result = resolve_imported_type(type_name, visited: visited.dup.add(self)) return result if result resolve_parent_type(type_name, visited: visited.dup.add(self)) end def action_for(action_name) api_class.ensure_contract_built!(self) action_name = action_name.to_sym actions[action_name] end def api_class return @api_class if @api_class return nil unless name namespace = name.deconstantize return nil if namespace.blank? API.find("/#{namespace.underscore.tr('::', '/')}") end def parse_response(response, action) ResponseParser.parse(self, action, response) end def type?(name) resolve_custom_type(name).present? end def enum?(name) enum_values(name).present? end def enum_values(enum_name, visited: Set.new) return nil if visited.include?(self) if api_class result = api_class.enum_values(enum_name, scope: self) return result if result end result = resolve_imported_enum_values(enum_name, visited: visited.dup.add(self)) return result if result resolve_parent_enum_values(enum_name, visited: visited.dup.add(self)) end def scoped_type_name(name) api_class.scoped_type_name(self, name) end def scoped_enum_name(name) api_class.scoped_enum_name(self, name) end private def resolve_imported_type(type_name, visited:) type_string = type_name.to_s imports.each do |import_alias, imported_contract| prefix = "#{import_alias}_" next unless type_string.start_with?(prefix) unprefixed_name = type_string.delete_prefix(prefix).to_sym result = imported_contract.resolve_custom_type(unprefixed_name, visited:) return result if result end nil end def resolve_parent_type(type_name, visited:) parent = superclass return nil unless parent < Contract::Base parent.resolve_custom_type(type_name, visited:) end def resolve_imported_enum_values(enum_name, visited:) enum_string = enum_name.to_s imports.each do |import_alias, imported_contract| prefix = "#{import_alias}_" next unless enum_string.start_with?(prefix) unprefixed_name = enum_string.delete_prefix(prefix).to_sym result = imported_contract.enum_values(unprefixed_name, visited:) return result if result end nil end def resolve_parent_enum_values(enum_name, visited:) parent = superclass return nil unless parent < Contract::Base parent.enum_values(enum_name, visited:) end end def initialize(action_name, request, coerce: false) request = normalize_request(request) result = RequestParser.parse(self.class, action_name, request, coerce:) @request = prepare_request(result.request) @action_name = action_name.to_sym @issues = result.issues end # @api public # Whether this contract is valid. # # @return [Boolean] def valid? issues.empty? end # @api public # Whether this contract is invalid. # # @return [Boolean] def invalid? issues.any? end private def normalize_request(request) api_class = self.class.api_class result = api_class.normalize_request(request) api_class.adapter.apply_request_transformers(result, phase: :before) end def prepare_request(request) api_class = self.class.api_class result = api_class.prepare_request(request) api_class.adapter.apply_request_transformers(result, phase: :after) end end |
.action(name, replace: false) {|action| ... } ⇒ Contract::Action
Defines or extends an action on this contract.
Multiple calls with the same name merge definitions (declaration merging).
472 473 474 475 476 477 478 479 480 481 482 483 484 485 |
# File 'lib/apiwork/contract/base.rb', line 472 def action(name, replace: false, &block) name = name.to_sym action = if replace Action.new(self, name, replace: true) else actions[name] ||= Action.new(self, name) end if block_given? block.arity.positive? ? yield(action) : action.instance_eval(&block) end actions[name] = action end |
.action_for(action_name) ⇒ Object
577 578 579 580 581 582 |
# File 'lib/apiwork/contract/base.rb', line 577 def action_for(action_name) api_class.ensure_contract_built!(self) action_name = action_name.to_sym actions[action_name] end |
.actions ⇒ Object
504 505 506 |
# File 'lib/apiwork/contract/base.rb', line 504 def actions @actions ||= {} end |
.api_class ⇒ Object
584 585 586 587 588 589 590 591 592 |
# File 'lib/apiwork/contract/base.rb', line 584 def api_class return @api_class if @api_class return nil unless name namespace = name.deconstantize return nil if namespace.blank? API.find("/#{namespace.underscore.tr('::', '/')}") end |
.build_synthetic_contract(representation_class, api_class) ⇒ Object
535 536 537 538 539 540 541 |
# File 'lib/apiwork/contract/base.rb', line 535 def build_synthetic_contract(representation_class, api_class) Class.new(Contract::Base) do @synthetic = true @representation_class = representation_class @api_class = api_class end end |
.building? ⇒ Boolean
512 513 514 |
# File 'lib/apiwork/contract/base.rb', line 512 def building? @building end |
.contract_for(representation_class) ⇒ Object
524 525 526 527 528 529 530 531 532 533 |
# File 'lib/apiwork/contract/base.rb', line 524 def contract_for(representation_class) return nil unless representation_class&.name contract_name = representation_class.name.sub(/Representation\z/, 'Contract') contract_class = contract_name.safe_constantize return contract_class if contract_class.is_a?(Class) && contract_class < Contract::Base synthetic_contracts[representation_class] ||= build_synthetic_contract(representation_class, api_class) end |
.enum(name, deprecated: false, description: nil, example: nil, values: nil) ⇒ void
This method returns an undefined value.
Defines or extends an enum for this contract.
Subclasses inherit parent enums. In introspection, enums are prefixed with the contract’s identifier (e.g., ‘:status` in `InvoiceContract` becomes `:invoice_status`).
Multiple calls with the same name merge values (declaration merging).
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 |
# File 'lib/apiwork/contract/base.rb', line 295 def enum( name, deprecated: false, description: nil, example: nil, values: nil ) api_class.register_enum( name, deprecated:, description:, example:, values:, scope: self, ) end |
.enum?(name) ⇒ Boolean
602 603 604 |
# File 'lib/apiwork/contract/base.rb', line 602 def enum?(name) enum_values(name).present? end |
.enum_values(enum_name, visited: Set.new) ⇒ Object
606 607 608 609 610 611 612 613 614 615 616 617 618 |
# File 'lib/apiwork/contract/base.rb', line 606 def enum_values(enum_name, visited: Set.new) return nil if visited.include?(self) if api_class result = api_class.enum_values(enum_name, scope: self) return result if result end result = resolve_imported_enum_values(enum_name, visited: visited.dup.add(self)) return result if result resolve_parent_enum_values(enum_name, visited: visited.dup.add(self)) end |
.fragment(name) {|object| ... } ⇒ void
This method returns an undefined value.
Defines a fragment type for this contract.
Fragments are only available for merging into other types and never appear as standalone types. Use fragments to define reusable field groups.
252 253 254 |
# File 'lib/apiwork/contract/base.rb', line 252 def fragment(name, &block) api_class.register_fragment(name, scope: self, &block) end |
.identifier(value = nil) ⇒ String?
Prefixes types, enums, and unions in introspection output.
Must be unique within the API. Derived from the contract class name when not set (e.g., ‘RecurringInvoiceContract` becomes `recurring_invoice`).
119 120 121 122 123 |
# File 'lib/apiwork/contract/base.rb', line 119 def identifier(value = nil) return @identifier if value.nil? @identifier = value.to_s end |
.import(klass, as:) ⇒ void
This method returns an undefined value.
Imports types from another contract for reuse.
Imported types are accessed with a prefix matching the alias.
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 |
# File 'lib/apiwork/contract/base.rb', line 390 def import(klass, as:) unless klass.is_a?(Class) raise ConfigurationError, "import must be a Class constant, got #{klass.class}. " \ "Use: import UserContract, as: :user (not 'UserContract' or :user_contract)" end unless klass < Contract::Base raise ConfigurationError, 'import must be a Contract class (subclass of Apiwork::Contract::Base), ' \ "got #{klass}" end unless as.is_a?(Symbol) raise ConfigurationError, "import alias must be a Symbol, got #{as.class}. " \ 'Use: import UserContract, as: :user' end imports[as] = klass return if klass.building? return unless klass.representation? && klass.api_class klass.building = true begin klass.api_class.ensure_contract_built!(klass) ensure klass.building = false end end |
.imports ⇒ Object
508 509 510 |
# File 'lib/apiwork/contract/base.rb', line 508 def imports @imports ||= {} end |
.introspect(expand: false, locale: nil) ⇒ Introspection::Contract
Returns introspection data for this contract.
498 499 500 |
# File 'lib/apiwork/contract/base.rb', line 498 def introspect(expand: false, locale: nil) api_class.introspect_contract(self, expand:, locale:) end |
.object(name, deprecated: false, description: nil, example: nil) {|object| ... } ⇒ void
This method returns an undefined value.
Defines or extends an object type for this contract.
Subclasses inherit parent types. In introspection, types are prefixed with the contract’s identifier (e.g., ‘:item` in `InvoiceContract` becomes `:invoice_item`).
Multiple calls with the same name merge fields (declaration merging).
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 |
# File 'lib/apiwork/contract/base.rb', line 214 def object( name, deprecated: false, description: nil, example: nil, &block ) api_class.register_object( name, deprecated:, description:, example:, scope: self, &block ) end |
.parse_response(response, action) ⇒ Object
594 595 596 |
# File 'lib/apiwork/contract/base.rb', line 594 def parse_response(response, action) ResponseParser.parse(self, action, response) end |
.representation(klass) ⇒ void
This method returns an undefined value.
Configures the representation class for this contract.
Adapters use the representation to auto-generate request/response types. Use representation_class to retrieve.
140 141 142 143 144 145 146 147 148 149 150 151 152 153 |
# File 'lib/apiwork/contract/base.rb', line 140 def representation(klass) unless klass.is_a?(Class) raise ConfigurationError, "representation must be a Representation class, got #{klass.class}. " \ "Use: representation InvoiceRepresentation (not 'InvoiceRepresentation' or :invoice)" end unless klass < Representation::Base raise ConfigurationError, 'representation must be a Representation class (subclass of Apiwork::Representation::Base), ' \ "got #{klass}" end @representation_class = klass end |
.representation? ⇒ Boolean
543 544 545 |
# File 'lib/apiwork/contract/base.rb', line 543 def representation? representation_class.present? end |
.resolve_custom_type(type_name, visited: Set.new) ⇒ Object
563 564 565 566 567 568 569 570 571 572 573 574 575 |
# File 'lib/apiwork/contract/base.rb', line 563 def resolve_custom_type(type_name, visited: Set.new) raise ConfigurationError, "Circular import detected while resolving :#{type_name}" if visited.include?(self) if api_class result = api_class.type_definition(type_name, scope: self) return result if result end result = resolve_imported_type(type_name, visited: visited.dup.add(self)) return result if result resolve_parent_type(type_name, visited: visited.dup.add(self)) end |
.scope_prefix ⇒ Object
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 |
# File 'lib/apiwork/contract/base.rb', line 547 def scope_prefix return @identifier if @identifier if name name .demodulize .delete_suffix('Contract') .underscore elsif representation_class representation_class.name .demodulize .delete_suffix('Representation') .underscore end end |
.scoped_enum_name(name) ⇒ Object
624 625 626 |
# File 'lib/apiwork/contract/base.rb', line 624 def scoped_enum_name(name) api_class.scoped_enum_name(self, name) end |
.scoped_type_name(name) ⇒ Object
620 621 622 |
# File 'lib/apiwork/contract/base.rb', line 620 def scoped_type_name(name) api_class.scoped_type_name(self, name) end |
.synthetic? ⇒ Boolean
520 521 522 |
# File 'lib/apiwork/contract/base.rb', line 520 def synthetic? @synthetic == true end |
.synthetic_contracts ⇒ Object
516 517 518 |
# File 'lib/apiwork/contract/base.rb', line 516 def synthetic_contracts @synthetic_contracts ||= {} end |
.type?(name) ⇒ Boolean
598 599 600 |
# File 'lib/apiwork/contract/base.rb', line 598 def type?(name) resolve_custom_type(name).present? end |
.union(name, deprecated: false, description: nil, discriminator: nil, example: nil) {|union| ... } ⇒ void
This method returns an undefined value.
Defines or extends a discriminated union for this contract.
Subclasses inherit parent unions. In introspection, unions are prefixed with the contract’s identifier (e.g., ‘:payment_method` in `InvoiceContract` becomes `:invoice_payment_method`).
Multiple calls with the same name merge variants (declaration merging).
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 |
# File 'lib/apiwork/contract/base.rb', line 355 def union( name, deprecated: false, description: nil, discriminator: nil, example: nil, &block ) api_class.register_union( name, deprecated:, description:, discriminator:, example:, scope: self, &block ) end |
Instance Method Details
#body ⇒ Hash
The body for this contract.
Use this in controller actions to access validated request data. Contains type-coerced values matching your contract definition. Invalid requests are rejected before the action runs.
87 88 89 |
# File 'lib/apiwork/contract/base.rb', line 87 delegate :body, :query, to: :request |
#invalid? ⇒ Boolean
Whether this contract is invalid.
695 696 697 |
# File 'lib/apiwork/contract/base.rb', line 695 def invalid? issues.any? end |
#query ⇒ Hash
The query for this contract.
Use this in controller actions to access validated request data. Contains type-coerced values matching your contract definition. Invalid requests are rejected before the action runs.
87 88 89 |
# File 'lib/apiwork/contract/base.rb', line 87 delegate :body, :query, to: :request |
#valid? ⇒ Boolean
Whether this contract is valid.
687 688 689 |
# File 'lib/apiwork/contract/base.rb', line 687 def valid? issues.empty? end |