Serializers
Serializers convert records and errors to response data. An adapter uses two serializer types:
- Resource serializer - converts records and collections
- Error serializer - converts errors (contract, domain, HTTP)
Resource Serializers
Resource serializers inherit from Adapter::Serializer::Resource::Base:
class MyResourceSerializer < Adapter::Serializer::Resource::Base
data_type { |representation_class| representation_class.root_key.singular.to_sym }
contract_builder ContractBuilder
def serialize(resource, context:, serialize_options:)
representation_class.serialize(resource, context:)
end
endDSL Methods
data_type
A block that receives the representation class and returns the type name used in responses. This type name is referenced by wrappers when building response shapes.
data_type { |representation_class| representation_class.root_key.singular.to_sym }contract_builder
The class that registers contract-level types for this serializer. Called during introspection for each contract-representation pair.
contract_builder ContractBuilderInstance Methods
serialize
The serialize method implements serialization logic:
def serialize(resource, context:, serialize_options:)
# resource: single record or collection
# context: passed from controller
# serialize_options: from capabilities (e.g., includes)
representation_class.serialize(resource, context:)
endThe representation_class attribute provides access to the representation class.
Error Serializers
Error serializers inherit from Adapter::Serializer::Error::Base:
class MyErrorSerializer < Adapter::Serializer::Error::Base
data_type :error
api_builder APIBuilder
def serialize(error, context:)
{ errors: error.issues.map(&:to_h) }
end
endDSL Methods
data_type
A symbol naming the error type. Referenced by error wrappers.
data_type :errorapi_builder
The class that registers API-level error types. Called once per API during introspection.
api_builder APIBuilderInstance Methods
serialize
The serialize method implements error serialization:
def serialize(error, context:)
# error: the error object with issues
# context: passed from controller
{ errors: error.issues.map(&:to_h) }
endContract Builder Example
Resource serializers typically register the resource type via a contract builder:
class ContractBuilder < Adapter::Builder::Contract::Base
def build
object(representation_class.root_key.singular.to_sym) do |object|
representation_class.attributes.each_value do |attribute|
object.public_send(attribute.type, attribute.name)
end
end
end
endAPI Builder Example
Error serializers typically register error types via an API builder:
class APIBuilder < Adapter::Builder::API::Base
def build
object(:error) do |object|
object.string(:code)
object.string(:message)
object.string?(:field)
end
end
endUsing Custom Serializers
Custom serializers are registered in the adapter:
class MyAdapter < Apiwork::Adapter::Base
adapter_name :my
resource_serializer MyResourceSerializer
error_serializer MyErrorSerializer
end