jaeyson / ex_typesense

Typesense client for Elixir with support for importing your Ecto schemas.
https://hexdocs.pm/ex_typesense
MIT License
25 stars 7 forks source link

Configuring a connection string dynamically #18

Closed jaeyson closed 1 month ago

jaeyson commented 1 month ago

See context #17. Tldr; configure the connection parameters dynamically (ie. creds from db records).

The gist here is that, the connection can be pipe-able to functions. By default, you don't need to pass connections every time you use a function.

# This is the typical use case for searching
ExTypesense.search(collection_name, query)

You may have a Connection Ecto schema in your app and want to pass your own creds dynamically.

defmodule MyApp.Credential do
  schema "credentials" do
    field :node, :string
    field :secret_key, :string
    field :port, :integer
  end
end
credential = MyApp.Credential |> where(id: ^8888) |> Repo.one()

# using Connection struct
conn = %ExTypesense.Connection{
  host: credential.node,
  api_key: credential.secret_key,
  port: credential.port,
  scheme: "https"
}

# or maps, as long as the keys matches in ExTypesense.Connection.t()
conn = %{
  host: credential.node,
  api_key: credential.secret_key,
  port: credential.port,
  scheme: "https"
}

# or convert your struct to map, as long as the keys matches in ExTypesense.Connection.t()
conn = Map.from_struct(MyApp.Credential)

# or you don't want to change the fields in your schema, thus you convert it to map
conn = %Credential{
  node: "localhost",
  secret_key: "xyz",
  port: 8108,
  scheme: "http"
}

conn =
  conn
  |> Map.from_struct()
  |> Map.drop([:node, :secret_key])
  |> Map.put(:host, conn.node)
  |> Map.put(:api_key, conn.secret_key)

ExTypesense.search(conn, collection_name, query)