• Stars
    star
    92
  • Rank 362,966 (Top 8 %)
  • Language
    Ruby
  • License
    MIT License
  • Created over 2 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

โœ… Generate TypeScript interfaces from your JSON serializers

Types From Serializers

Build Status Maintainability Gem Version License

Automatically generate TypeScript interfaces from your JSON serializers.

Currently, this library targets oj_serializers and ActiveRecord in Rails applications.

Demo ๐ŸŽฌ

For a schema such as this one:

DB Schema
  create_table "composers", force: :cascade do |t|
    t.text "first_name"
    t.text "last_name"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
  end

  create_table "songs", force: :cascade do |t|
    t.text "title"
    t.integer "composer_id"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
  end

  create_table "video_clips", force: :cascade do |t|
    t.text "title"
    t.text "youtube_id"
    t.integer "song_id"
    t.integer "composer_id"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
  end

and a serializer like the following:

class VideoSerializer < BaseSerializer
  object_as :video, model: :VideoClip

  attributes :id, :created_at, :title, :youtube_id

  type :string, optional: true
  def youtube_url
    "https://www.youtube.com/watch?v=#{video.youtube_id}" if video.youtube_id
  end

  has_one :song, serializer: SongSerializer
end

it would generate a TypeScript interface like:

import type Song from './Song'

export default interface Video {
  id: number
  createdAt: string | Date
  title?: string
  youtubeId?: string
  youtubeUrl?: string
  song: Song
}

Note

This is the default configuration, but you have full control over generation.

Why? ๐Ÿค”

It's easy for the backend and the frontend to become out of sync. Traditionally, preventing bugs requires writing extensive integration tests.

TypeScript is a great tool to catch this kind of bugs and mistakes, as it can detect incorrect usages and missing fields, but writing types manually is cumbersome, and they can become stale over time, giving a false sense of confidence.

This library takes advantage of the declarative nature of serializer libraries such as active_model_serializers and oj_serializers, extending them to allow embedding type information, as well as inferring types from the SQL schema when available.

As a result, it's posible to easily detect mismatches between the backend and the frontend, as well as make the fields more discoverable and provide great autocompletion in the frontend, without having to manually write the types.

Features โšก๏ธ

  • Start simple, no additional syntax required
  • Infers types from a related ActiveRecord model, using the SQL schema
  • Understands JS native types and how to map SQL columns: string, boolean, etc
  • Automatically types associations, importing the generated types for the referenced serializers
  • Detects conditional attributes and marks them as optional: name?: string
  • Fallback to a custom interface using type_from
  • Supports custom types and automatically adds the necessary imports

Installation ๐Ÿ’ฟ

Add this line to your application's Gemfile:

gem 'types_from_serializers'

And then run:

$ bundle install

Usage ๐Ÿš€

To get started, create a BaseSerializer that extends Oj::Serializer, and include the TypesFromSerializers::DSL module.

# app/serializers/base_serializer.rb

class BaseSerializer < Oj::Serializer
  include TypesFromSerializers::DSL
end

Note

You can customize this behavior using base_serializers.

Warning

All serializers should extend one of the base_serializers, or they won't be detected.

SQL Attributes

In most cases, you'll want to let TypesFromSerializers infer the types from the SQL schema.

If you are using ActiveRecord, the model related to the serializer will be inferred can be inferred from the serializer name:

UserSerializer => User

It can also be inferred from an object alias if provided:

class PersonSerializer < BaseSerializer
  object_as :user

In cases where we want to use a different alias, you can provide the model name explicitly:

class PersonSerializer < BaseSerializer
  object_as :person, model: :User

Model Attributes

When you want to be more strict than the SQL schema, or for attributes that are methods in the model, you can use:

  attributes(
    name: {type: :string},
    status: {type: :Status}, # a custom type in ~/types/Status.ts
  )

Serializer Attributes

For attributes defined in the serializer, use the type helper:

  type :boolean
  def suspended
    user.status.suspended?
  end

Note

When specifying a type, attribute will be called automatically.

Fallback Attributes

You can also specify types_from to provide a TypeScript interface that should be used to obtain the field types:

class LocationSerializer < BaseSerializer
  object_as :location, types_from: :GoogleMapsLocation

  attributes(
    :lat,
    :lng,
  )
end
import GoogleMapsLocation from '~/types/GoogleMapsLocation'

export default interface Location {
  lat: GoogleMapsLocation['lat']
  lng: GoogleMapsLocation['lng']
}

Generation ๐Ÿ“œ

To get started, run bin/rails s to start the Rails development server.

TypesFromSerializers will automatically register a Rails reloader, which detects changes to serializer files, and will generate code on-demand only for the modified files.

It can also detect when new serializer files are added, or removed, and update the generated code accordingly.

Manually

To generate types manually, use the rake task:

bundle exec rake types_from_serializers:generate

or if you prefer to do it manually from the console:

require "types_from_serializers/generator"

TypesFromSerializers.generate(force: true)

With vite-plugin-full-reload โšก๏ธ

When using Vite Ruby, you can add vite-plugin-full-reload to automatically reload the page when modifying serializers, causing the Rails reload process to be triggered, which is when generation occurs.

// vite.config.ts
import { defineConfig } from 'vite'
import ruby from 'vite-plugin-ruby'
import reloadOnChange from 'vite-plugin-full-reload'

defineConfig({
  plugins: [
    ruby(),
    reloadOnChange(['app/serializers/**/*.rb'], { delay: 200 }),
  ],
})

As a result, when modifying a serializer and hitting save, the type for that serializer will be updated instantly!

Configuration โš™๏ธ

You can configure generation in a Rails initializer:

# config/initializers/types_from_serializers.rb

if Rails.env.development?
  TypesFromSerializers.config do |config|
    config.name_from_serializer = ->(name) { name }
  end
end

base_serializers

Default: ["BaseSerializer"]

Allows you to specify the base serializers, that are used to detect other serializers in the app that you would like to generate interfaces for.

serializers_dirs

Default: ["app/serializers"]

The dirs where the serializer files are located.

output_dir

Default: "app/frontend/types/serializers"

The dir where the generated TypeScript interface files are placed.

custom_types_dir

Default: "app/frontend/types"

The dir where the custom types are placed.

name_from_serializer

Default: ->(name) { name.delete_suffix("Serializer") }

A Proc that specifies how to convert the name of the serializer into the name of the generated TypeScript interface.

global_types

Default: ["Array", "Record", "Date"]

Types that don't need to be imported in TypeScript.

You can extend this list as needed if you are using global definitions.

skip_serializer_if

Default: ->(serializer) { false }

You can provide a proc to avoid generating serializers.

Along with base_serializers, this provides more fine-grained control in cases where a single backend supports several frontends, allowing to generate types separately.

sql_to_typescript_type_mapping

Specifies how to map SQL column types to TypeScript native and custom types.

# Example: You have response middleware that automatically converts date strings
# into Date objects, and you want TypeScript to treat those fields as `Date`.
config.sql_to_typescript_type_mapping.update(
  date: :Date,
  datetime: :Date,
)

# Example: You won't transform fields when receiving data in the frontend
# (date fields are serialized to JSON as strings).
config.sql_to_typescript_type_mapping.update(
  date: :string,
  datetime: :string,
)

# Example: You plan to introduce types slowly, and don't want to be strict with
# untyped fields, so treat them as `any` instead of `unknown`.
config.sql_to_typescript_type_mapping.default = :any

transform_keys

Default: ->(key) { key.camelize(:lower).chomp("?") }

You can provide a proc to transform property names.

This library assumes that you will transform the casing client-side, but you can generate types preserving case by using config.transform_keys = ->(key) { key }.

Contact โœ‰๏ธ

Please use Issues to report bugs you find, and Discussions to make feature requests or get help.

Don't hesitate to โญ๏ธ star the project if you find it useful!

Using it in production? Always love to hear about it! ๐Ÿ˜ƒ

License

The gem is available as open source under the terms of the MIT License.

More Repositories

1

vite_ruby

โšก๏ธ Vite.js in Ruby, bringing joy to your JavaScript experience
Ruby
1,270
star
2

iles

๐Ÿ The joyful site generator
TypeScript
1,074
star
3

vite-plugin-image-presets

๐Ÿ–ผ Image Presets for Vite.js apps
TypeScript
246
star
4

vite-plugin-environment

Easily expose environment variables in Vite.js
TypeScript
144
star
5

vite-plugin-full-reload

โ™ป๏ธ Automatically reload the page when files are modified
JavaScript
134
star
6

oj_serializers

โšก๏ธ Faster JSON serialization for Ruby on Rails. Easily migrate away from Active Model Serializers.
Ruby
113
star
7

js_from_routes

๐Ÿ›ฃ๏ธ Generate path helpers and API methods from your Rails routes
Ruby
98
star
8

request_store_rails

๐Ÿ“ฆ Per-request global storage for Rails prepared for multi-threaded apps
Ruby
85
star
9

vuex-stores

๐Ÿ—„ Store objects for Vuex, a simple and more fluid API for state-management.
JavaScript
62
star
10

vue-custom-element-example

An example on how to define custom elements using Vue 3
TypeScript
59
star
11

jekyll-vite

โšก๏ธ๐Ÿฉธ Use Vite.js in Jekyll as your assets pipeline
Ruby
50
star
12

vite-plugin-stimulus-hmr

โšก๏ธ HMR for Stimulus controllers in Vite.js
TypeScript
50
star
13

mongoid_includes

๐ŸŒฟ Improves eager loading support for Mongoid
Ruby
46
star
14

stimulus-vite-helpers

Helpers to easily load all your Stimulus controllers when using Vite.js
TypeScript
43
star
15

queryable

โ” Gives your queries a home and avoid tucking scopes inside your models
Ruby
42
star
16

capybara-compose

โœ… Easily write fluent integration tests with Capybara in Ruby
Ruby
32
star
17

better_settings

โš™ Settings for Ruby apps โ€“ fast, immutable, better.
Ruby
20
star
18

vite-plugin-bugsnag

Report builds and upload source maps to Bugsnag
TypeScript
18
star
19

i18n_multitenant

๐ŸŒŽ Provides a convenient way to use tenant-specific translations
Ruby
18
star
20

vite-plugin-manifest-sri

Subresource Integrity for Vite.js manifest files
JavaScript
15
star
21

resourcerer

โœจ Works like magic to dry up your controllers
Ruby
10
star
22

sublime-toggle-dark-mode

๐ŸŒš๐ŸŒž Toggle between dark and light mode in Sublime Text 4
JavaScript
10
star
23

pakiderm

๐Ÿ˜ Pakiderm will never forget the return value
Ruby
7
star
24

presenter_rails

๐Ÿ”ญ Expose your view models in a convenient way
Ruby
6
star
25

vite-plugin-erb

Use ERB files in Vite.js projects with a Ruby backend
TypeScript
5
star
26

journeyman

Let your factories use your business logic, making them flexible and easier to update.
Ruby
5
star
27

jekyll-vite-minima

โšก๏ธ๐Ÿฉธ Use Vite.js in Jekyll minima theme as your assets pipeline
Ruby
3
star
28

automatic-music-transcription

Automatically exported from code.google.com
C
2
star
29

vite-plugin-xdm

Use XDM in VIte.js
JavaScript
2
star
30

fast-food-mvc

Automatically exported from code.google.com
C#
1
star
31

ElMassimo

1
star
32

vite-vue-router-hmr-repro

Vue
1
star
33

crouton

๐Ÿž Context sensitive notifications for Rails
Ruby
1
star