Hi, I’m just starting out with Elixir/Phoenix and was wondering if someone could give me some feedback on the following code? (I’m working alone so want to avoid picking up bad habits!)
The code handles a user uploading a CSV file to update multiple entries in the db at once, and only if they provide the correct admin password.
def create(conn, _params, user) do
admin_password = Application.get_env(:datamo, :admin_password)
if (conn.params["upload_data"]["admin_password"] == admin_password) do
datasets = conn.params["upload_data"]["datasets"]
datasets.path
|> File.stream!()
|> CSV.decode(headers: [:name, :description, :file_url, :image_url])
|> Enum.map(fn dataset_params ->
user
|> build_assoc(:datasets)
|> Dataset.changeset(dataset_params)
end)
|> Enum.map(fn changeset ->
Repo.insert!(changeset)
end)
conn
|> put_flash(:info, "Datasets uploaded successfully.")
|> redirect(to: dataset_path(conn, :index))
else
conn
|> put_flash(:error, "Admin password incorrect.")
|> redirect(to: upload_path(conn, :new))
end
end
Any feedback on general style/usage would be fantastic!
A few concerns I have myself:
- No validation on the CSV
- Should I be using environment variables for the admin password rather than config vars?
- I should probably have different user permissions for admins rather than a password (authorization)
- Should I be handling possible errors on the Repo.insert (i.e. not using the ! version)?
- And similarly, should I be handling possible errors on the File.stream?
Thanks.