This repository the Lenra server application.
Report Bug
·
Request Feature
You will first need to start two databases, postgres and mongo. Postgres will be used by the server to store general data and Mongo will store the data of the applications that you run.
You can do this by using the docker compose up -d command at the root of this project.
Init git submodules : git submodule update --init --recursive
You will then need to install and setup elixir prerequisites for the server to run properly :
- Install erlang in version 24.2 and elixir in version 1.14.3 otp-24
- Create the database and start migration
mix setup. This is equivalent to running the following commands :mix deps.getto install the dependenciesmix ecto.createto create databasemix ecto.migrateto start all migration and have an up-to-date databasemix run apps/lenra/priv/repo/seeds.exsto fill database with default values
Now you can start the server with this command mix phx.server
The server is started at localhost:4000
Code quality check :
- Code formatting with
mix format - Syntax verification/Code rules
mix credo --strict - security check
mix sobelow - run tests
mix test - test + code coverage
mix coveralls [--umbrella] - test + code coverage + html report
mix coveralls.html [--umbrella]
- An error occurs when you have elixir or erlang in the wrong version and you can't launch the server. To install the correct version of erlang and elixir you can use the package asdf to install and manage all the versions of the packages you want. Documentation to use asdf : https://asdf-vm.com/guide/getting-started.html
- Official website: https://www.phoenixframework.org/
- Guides: https://hexdocs.pm/phoenix/overview.html
- Docs: https://hexdocs.pm/phoenix
- Forum: https://elixirforum.com/c/phoenix-forum
- Source: https://github.com/phoenixframework/phoenix
Use 3 layers :
- The Controller to manage the conn object, call the service and handle errors. He’s the only one who resolves the transactions.
- The Entity Model to manage changes on the object such as add/modify and database associations.
- The Service to manage business logic. He’s the only one with direct access to the database.
For the naming, we use a singular name then we derive it (User, UserController, UserServices)
- Entry point for the request.
- It can call several services only if their combination does not involve business logic.
- Execute the "final" transaction and handle potential errors.
- Assign data/error as required.
- Ends by "reply" to terminate the request and send the result to the client.
Simplified example of a "basic" controller: :
defmoduleLenraWeb.PostControllerdouseLenraWeb,:controlleraliasLenraWeb.Guardian.PlugaliasLenra.{PostServices}aliasLenra.{Repo}defindex(conn,_params)doposts=PostServices.all()conn|>assign_data(posts)|>replyenddefshow(conn,params)dopost=PostServices.get(params.id)conn|>assign_data(post)|>replyenddefcreate(conn,params)doPlug.current_resource(conn)|>PostServices.add_post(params)|>Repo.transaction()|>casedo{:ok,%{inserted_post: post}}->conn|>assign_data(post)|>reply{:error,{_,reason,_}}->conn|>assign_error(reason)|>replyendenddefupdate(conn,params)doPostServices.get(params.id)|>PostServices.update(params)|>Repo.transaction()|>casedo{:ok,%{updated_post: post}}->conn|>assign_data(post)|>reply{:error,{_,reason,_}}->conn|>assign_error(reason)|>replyendendendIt allows the creation/update of a data structure with help functions.
- A UNIQUE changeset function allow integrity verification of entity during creation/update.
- A 'new' function that allows the creation of the structure that deals with creating possible associations (foreign key)
- This function takes as parameters "params" and if necessary the other entities to be linked to.
- This function itself calls the "changeset" function to validate the integrity of the parameters.
- This function can define default values.
- An 'update' function that allow object update (and eventually these associations)
- This function take as parameter one entity of same type, "params" and if needed the others entities to modify the association.
- This function itself calls the "changeset" function to validate the integrity of the parameters.
Simplified example of "basic" model :
defmodulePostdouseEcto.SchemaimportEcto.ChangesetaliasLenra.Userschema"posts"dofield(:title,:string)field(:body,:string)belongs_to(:user,User)timestamps()enddefchangeset(post,params\\%{})dopost|>cast(params,[:title,:body])|>validate_required([:title,:body])|>validate_length(:title,min: 3,max: 120)|>validate_length(:title,min: 10)enddefnew(user,params)doEcto.build_assoc(user,:posts)# Création de l'association avec le user dans le new|>changeset(params)# création de l'objet + vérif des contraintesenddefupdate(post,params)dopost# Ici, pas d'association à mettre à jour|>changeset(params)# update de l'objet + vérif des contraintesendendIt contains the business logic. It assumes that its entries have been verified. There are 2 main types of basic operation, reading and writing.
A reading does not require Ecto.Multi
A writing is ALWAYS done with an Ecto.Multi
We always implement the CRUD database which will be the database called by other service functions.
This means that we never insert/delete from other services but we call these services there.
To create an entity, use the new function of the model (ex : User.new(params)) then we insert it in the database (with Ecto.Multi).
To combine multiple calls to Ecto.Multi services, use Ecto.Multi.merge
If needed, create "high level" services to preload the data and combine it with multiple simple operations.
- Example, when validating a user with their code :
defvalidate_user(id,code)douser=UserService.get(id)|>Repo.preload(:registration_code)# Chargement de l'utilisateur + preloadEcto.Multi.new()|>Ecto.Multi.run(:check_valid,fn_,_->RegistrationCodeServices.check_valid(user.registration_code,code)end)# Check si le code est valide ou non|>Ecto.Multi.merge(fn_->RegistrationCodeServices.delete(user.registration_code)end)# Delete le code (ne sera fait que si le code est valide.)|>Ecto.Multi.merge(fn_->UserServices.update(user,%{role: User.const_user_role()})end)# Update l'utilisateurendSimplified example of a "basic" service :
defmoduleLenra.PostServicesdoaliasLenra.{Repo,Post}aliasLenra.{UserServices,PostServices}defget(id)doRepo.get(Post,id)enddefget_by(clauses)doRepo.get_by(Post,clauses)enddefalldoRepo.all(Post)end# crée un post associé à un utilisateur# Opération "simple"defcreate(user,params)dopost=Post.new(user,params)Ecto.Multi.new()|>Ecto.Multi.insert(:inserted_post,post)end# Update un post (opération simple)defupdate(post,params)doEcto.Multi.new()|>Ecto.Multi.update(:updated_post,Post.update(post,params))end# Crée un post et notifie l'utilisateur (service de "haut niveau")defadd_post(user_id,params)douser=UserServices.get(user_id)Ecto.Multi.new()|>Ecto.Multi.merge(fn_->PostServices.create(user,params)end)|>Ecto.Multi.run(fn_,%{inserted_post: post}->NotifWorker.send_post_notif(user,post)end)endendContributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated.
If you have a suggestion that would make this better, please open an issue with the tag "enhancement" or "bug". Don't forget to give the project a star! Thanks again!
Distributed under the AGPL License. See LICENSE for more information.