Type Inference
Attributes
An attribute's type is inferable if:
- the underlying ActiveRecord model of the resource has a type definition for the attribute
- the method for the attribute is not overridden in the model
- the method for the attribute is not overridden in the resource
Example
class UserResource < ApplicationResource
attribute :name # => Anchor::Types::String
attribute :bio # => Anchor::Types::Maybe.new(Anchor::Types::String)
attribute :role # => Anchor::Types::String if Anchor.config.use_active_record_validations is true (true is default)
attribute :model_override # => Anchor::Types::Unknown
attribute :resource_override # => Anchor::Types::Unknown
def resource_override
nil
end
end
class User < ApplicationRecord
validates :role, presence: true
def model_override
nil
end
end
# db/schema.rb snippet
create_table "users", force: :cascade do |t|
t.string "name", null: false
t.string "bio"
t.string "role"
t.string "model_override"
t.string "resource_override"
end
JSONAPI::Resource
attributes are inferred via introspection of the resource's
underlying ActiveRecord model.
ActiveRecord::Base.columns_hash[attribute]
is used to get the SQL type and is
then mapped to an Anchor::Type
in
Anchor::Types::Inference::ActiveRecord::SQL.from
.
Relevant Configs
use_active_record_validations
- use ActiveModel validations on the ActiveRecord model to determine nullability
ar_column_to_type
- custom type mapping
Relationships
Example
class User < ApplicationRecord
has_many :posts
has_one :posts
end
class UserResource < ApplicationResource
relationship :posts, to: :many # => Anchor::Types::Array.new(Anchor::Types::Reference.new("Post"))
end
class Post < ApplicationRecord
belongs_to :user
belongs_to :deleted_by, class_name: "User", optional: true
end
class PostResource < ApplicationResource
relationship :user, to: :one # => Anchor::Types::Reference.new("User")
relationship :deleted_by, to: :one, class_name: "User" # => Anchor::Types::Maybe.new(Anchor::Types::Reference.new("User"))
end
The .anchor_schema_name
of the related resource is used as the type identifier in the TypeScript serializer.
The nullability and cardinality are determined by the underlying ActiveRecord model's reflections, ActiveRecord::Base.reflections[name]
.
ActiveRecord Association | Inferred Anchor::Type (TypeScript expression) |
---|---|
belongs_to :relation | Relation |
belongs_to :relation, optional: true | Maybe<Relation> |
has_one :relation | Maybe<Relation> |
has_many :relations | Array<Relation> |
has_and_belogs_to_many :relations | Array<Relation> |
Relevant Configs
infer_nullable_relationships_as_optional
- whether to use e.g.
{ relation?: Relation }
or{ relation: Maybe<Relation> }
- whether to use e.g.