This two-part series has taken you on a journey to build a multi-tenant Elixir app using the Phoenix web framework. That's it! Now, when we visit a link like this should redirect to the original long URL and increment the link's view counter. t def hash_id_format (value) do case validate_hash_id (value) do true -> = link) do from (s in Link, where: s.id = ^link.hash, update: ]) |> Repo. t def autogenerate, do: generate () # The Ecto type that is being converted def type, do: :string hash_id_format (any) :: Map. t def load (value), do: hash_id_format (value) # A callback invoked by autogenerate fields autogenerate () :: String. t def dump (value), do: hash_id_format (value) # Changes a value from the default type into the HashId type load (any) :: Map. t def cast (value), do: hash_id_format (value) # Accepts a value that has been directly placed into the ecto struct after a changeset dump (any) :: Map. Type 8 # Called when creating an Ecto.Changeset cast (any) :: Map. Ecto will manage the process whenever a new link model is created.įirst, create a new file to represent this new type: Automatically generate unique string hashes to form the short URL field for links.Learn how to create and use Elixir custom types.Let's substitute the id primary key in the Link model with a custom Ecto type called HashId. We could write a custom function to generate such strings, but since we are on a quest to learn Elixir, let's use a more creative approach. In either case, when present in a model, this field is automatically incremented for every additional model created in an app.Ī core function of our app is generating short, unique strings to represent long URLs. Usually, it's in the form of an integer or, in some cases, a binary ID. Creating Short URLs Using the Ecto Custom Type in Phoenixīy default, Ecto models have an id field used as a model's primary key. You may notice that we haven't included a field for the short random string referencing the long URL. This should generate most of the boilerplate code we need to work with the Link resource. Mix Links Link links url:string visits:integer account_id:references:accounts
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |