Skip to content

Commit

Permalink
feat: Allow recursive type definition
Browse files Browse the repository at this point in the history
Let's say we have the following type:

```typescript
type Chapter = {
  title: string
  next: Chapter | null
}
```

Here, `Chapter` type is recursive, referencing itself.
Typelizer can generate this kind of type, but currently it tries
to import itself and causes an error.
This commit fixes this issue by ignoring itself from import target.
Note that I added spec for Alba only since that was my case,
but please tell me if I should add more specs for other serializers.
  • Loading branch information
okuramasafumi authored Nov 26, 2024
1 parent 6ac726e commit 5cd2dab
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 3 deletions.
6 changes: 5 additions & 1 deletion lib/typelizer/interface.rb
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ def imports
.uniq
.reject { |type| global_type?(type) }

(custom_type_imports + serializer_types).uniq
(custom_type_imports + serializer_types).uniq - Array(self_type_name)
end

def inspect
Expand All @@ -75,6 +75,10 @@ def inspect

private

def self_type_name
serializer.name.match(/(\w+::)?(\w+)(Serializer|Resource)/)[2]
end

def extract_typescript_types(type)
type.split(/[<>\[\],\s|]+/)
end
Expand Down
3 changes: 2 additions & 1 deletion spec/__snapshots__/AlbaPost.ts.snap
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Typelizer digest a9453a41deef37fc65276aad80c95e46
// Typelizer digest c272bbef7d366eb5882788757480509d
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {AlbaUser} from '@/types'
Expand All @@ -10,6 +10,7 @@ type AlbaPost = {
body?: string | null;
published_at?: string | null;
user: AlbaUser;
next_post: Post;
}

export default AlbaPost;
4 changes: 4 additions & 0 deletions spec/app/app/models/post.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,8 @@ class Post < ApplicationRecord
belongs_to :user

enum category: {news: 1, article: 2, blog: 3}

def next_post
# Returns Post
end
end
7 changes: 6 additions & 1 deletion spec/app/app/serializers/alba/post_serializer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,16 @@ class PostSerializer

typelizer_config do |c|
c.null_strategy = :nullable_and_optional
c.serializer_model_mapper = ->(serializer) { Object.const_get(serializer.name.gsub("Serializer", "").gsub("Alba::", "")) }
c.serializer_model_mapper = lambda { |serializer|
Object.const_get(serializer.name.gsub("Serializer", "").gsub("Alba::", ""))
}
end

attributes :id, :title, :category, :body, :published_at

has_one :user, serializer: UserSerializer

attributes :next_post
typelize next_post: "Post"
end
end

0 comments on commit 5cd2dab

Please sign in to comment.