diff --git a/README.md b/README.md index a2631ddc..665e7317 100644 --- a/README.md +++ b/README.md @@ -1,28 +1,27 @@ -# Bloom by Chayn +# Welcome to Bloom [![Bloom Backend CI Pipeline](https://github.com/chaynHQ/bloom-backend/actions/workflows/.ci.yml/badge.svg)](https://github.com/chaynHQ/bloom-backend/actions/workflows/.ci.yml) -Bloom is a remote trauma support service from [Chayn](https://www.chayn.co/about), a global, award-winning charity designing open-source tools to support the healing of survivors across the world. Since 2013, Chayn has reached over 500,000 survivors worldwide with our trauma-informed, survivor-centred, and intersectional approaches in utilizing tech for social impact. Bloom is our flagship product; a free, web-based, secure support service designed to aid in the healing of survivors. Through a combination of online video-based courses, anonymous interaction, and 1:1 chat, Bloom provides tailored information, self-help guidance, everyday tools, and comfort to cope with traumatic events. +[Bloom](https://bloom.chayn.co/) is a free, secure, and web-based trauma healing support service from [Chayn](https://www.chayn.co/about). Since 2013, Chayn has reached over 500,000 survivors worldwide with our trauma-informed, survivor-centred, and intersectional approaches in utilizing open-source tech for positive social impact. Bloom is our flagship product — providing tailored video-based courses, anonymous interaction, 1:1 chat, self-led healing guidance, everyday tools, and comfort to cope with traumatic events. Explore Chayn's [website](https://www.chayn.co/about), [research](https://org.chayn.co/research), [resources](https://www.chayn.co/resources), [projects](https://org.chayn.co/projects), [impact](https://org.chayn.co/impact), and [support services directory](https://www.chayn.co/global-directory). 💖 -## Support Our Work +## Key Features: -Chayn is proudly open-source and built with volunteer contributions. We are grateful for the generosity of the open-source community and aim to provide a fulfilling experience for open-source developers. +Chayn's Bloom service offers several key features designed to support individuals on their healing journey: -**Please give this repository a star ⭐ and follow our GitHub profile 🙏 to help us grow our open-source community and find more contributors like you!** +- **Free and Anonymous:** Bloom is a free service that ensures anonymity for its users. +- **Self-Paced Activities and Exploration:** Users can explore all resources and activities at their own pace. +- **Multi-lingual Support:** All features are available in multiple languages including Spanish, Hindi, French, English, Portuguese, and German. +- **Online Video Courses:** Provides healing educational video courses. +- **1-to-1 Messaging:** Secure messaging service to share reflections, feelings, and questions with Chayn therapists. +- **Supportive Messaging:** Receive tailored supportive messaging from Chayn through Whatsapp. -Support our mission further by [sponsoring us on GitHub](https://github.com/sponsors/chaynHQ), exploring our [volunteer programs](https://www.chayn.co/get-involved), and following Chayn on social media: - Linktree: [https://linktr.ee/chayn](https://linktr.ee/chayn) - Twitter: [@chaynhq](https://twitter.com/ChaynHQ) - Instagram: [@chaynhq](https://www.instagram.com/chaynhq/) - Youtube: [@chaynhq](https://www.youtube.com/@chaynhq) - Facebook: [@chayn](https://www.facebook.com/chayn) - LinkedIn: [@chayn](https://www.linkedin.com/company/chayn). +## Bloom Backend Technical Documentation -# Bloom Backend Contribution Docs: +Read our [Bloom Backend Technical Wiki Docs](https://github.com/chaynHQ/bloom-backend/wiki/Key-Concepts-and-Architecture) for overviews of key concepts and data & database architecture. -By making an open-source contribution to Chayn, you have agreed to our [Code of Conduct](/CODE_OF_CONDUCT.md). - -Happy coding! ⭐ - -## Technologies Used: - -Visit the [/docs directory](https://github.com/chaynHQ/bloom-backend/tree/develop/docs) for an overview of Bloom's backend architecture and key concepts. +Technologies Used: - [NestJS](https://nestjs.com/) - NodeJs framework for building scalable and reliable server-side applications - [PostgreSQL](https://www.postgresql.org/about/) - Object-relational SQL database system @@ -41,238 +40,22 @@ Visit the [/docs directory](https://github.com/chaynHQ/bloom-backend/tree/develo ## Local development -### Summary - -To run Bloom's backend: install prerequisites, configure environment variables, install dependencies, then run in a Dev Container, with Docker, or manually. - -Most contributions (and running Cypress integration tests from the frontend) require [populating your local database](#populate-database) with test data. - -### Prerequisites - -- NodeJS v20.x -- Yarn v1.x -- Docker -- PostgreSQL 16 -- Read [Contribution Guidelines](/CONTRIBUTING.md) - -### Configure Environment Variables - -Create a new `.env` file and fill it with the **required** environment variables: - -``` -# Variables for building and running tests. -# Provided variables are read-only and subject to change. -#=============================================================== -# REQUIRED VARIABLES FOR LOCAL DEVELOPMENT -#--------------------------------------------------------------- -# CORE ENVIRONMENT VARIABLES -PORT=35001 -DATABASE_URL=postgres://:@:/ -NODE_ENV=development - -# FIREBASE AUTH AND ANALYTICS -FIREBASE_TYPE=service_account -FIREBASE_PROJECT_ID= -FIREBASE_PRIVATE_KEY_ID= -FIREBASE_PRIVATE_KEY= -FIREBASE_CLIENT_EMAIL= -FIREBASE_CLIENT_ID= -FIREBASE_AUTH_URI=https://accounts.google.com/o/oauth2/auth -FIREBASE_TOKEN_URI=https://oauth2.googleapis.com/token -FIREBASE_CERT_URL=https://www.googleapis.com/oauth2/v1/certs -FIREBASE_CLIENT_CERT= -FIREBASE_API_KEY= -FIREBASE_AUTH_DOMAIN= -FIREBASE_PROJECT_ID= -FIREBASE_STORAGE_BUCKET= -FIREBASE_MESSAGING_SENDER_ID= -FIREBASE_API_ID= -FIREBASE_MEASUREMENT_ID= - -# REQUIRED VARIABLES FOR TESTING -#--------------------------------------------------------------- -# MOCK VALUES (can replace with real values or new mocks in same format) -SIMPLYBOOK_CREDENTIALS='{"login":"testlogin","password":"testpassword","company":"testcompany"}' -SIMPLYBOOK_COMPANY_NAME=testcompany - -# OPTIONAL VARIABLES -#--------------------------------------------------------------- -ROLLBAR_ENV=development # Rollbar logging -ROLLBAR_TOKEN= # Rollbar logging -ZAPIER_TOKEN= # Zapier automation -SLACK_WEBHOOK_URL= # Slack messaging bots -CRISP_TOKEN= # Crisp chat -MAILCHIMP_API_KEY= # Email messaging -RESPOND_IO_CREATE_CONTACT_WEBHOOK= # RESPOND.IO -RESPOND_IO_DELETE_CONTACT_WEBHOOK= # RESPOND.IO -``` - -#### How to Configure Firebase Variables: - -Bloom's required Firebase variables are obtained by creating a Firebase project, then generating a private key file in JSON format. First, create a Firebase project [in the Firebase console here](https://firebase.google.com/) (Google account required). Next, [follow these directions](https://firebase.google.com/docs/cloud-messaging/auth-server#provide-credentials-manually) to generate your private key file. - -### Install dependencies with yarn - -```bash -yarn -``` - -### Run in Docker - Recommended - -Bloom's backend is containerized and can be run solely in Docker - both the PostgreSQL database and NestJS app. To run the backend locally, make sure your system has Docker installed - you may need Docker Desktop if using a Mac or Windows. - -First, make sure the Docker app is running (just open the app). Then run - -```bash -docker-compose up -``` - -You should see this in the shell output: - -```shell -Listening on localhost:35001, CTRL+C to stop -``` - -_Note: you can use an application like Postman to test the apis locally_ - -### Run in Dev Container - Recommended for Visual Studio Users - -This method will automatically install all dependencies, IDE settings, and postgres container in a Dev Container (Docker container) within Visual Studio Code. - -Directions for running a dev container: - -1. Meet the [system requirements](https://code.visualstudio.com/docs/devcontainers/containers#_system-requirements) -2. Follow the [installation instructions](https://code.visualstudio.com/docs/devcontainers/containers#_installation) -3. [Check the installation](https://code.visualstudio.com/docs/devcontainers/tutorial#_check-installation) -4. After you've verified that the extension is installed and working, click on the "Remote Status" bar icon and select - "Reopen in Container". From here, the option to "Re-open in Container" should pop up in notifications whenever opening this project in VS. -5. [Configure your environment variables](#configure-environment-variables) and develop as you normally would. - -The dev Container is configured in the `.devcontainer` directory: - -- `docker-compose.yml` file in this directory extends the `docker-compose.yml` in the root directory. -- `devcontainer.json` configures the integrations with Visual Studio Code, such as the IDE extensions and settings in the `vscode` directory. - -See [Visual Studio Code Docs: Developing Inside a Dev Container](https://code.visualstudio.com/docs/devcontainers/containers) for more info. - -### Run Manually - -Manage postgres locally to [populate the database](#populate-database), then run: - -```bash -yarn start:dev -``` - -You should see this in the shell output: - -```shell -Listening on localhost:35001, CTRL+C to stop -``` +Making an open-source contribution you have agreed to our [Code of Conduct](/CODE_OF_CONDUCT.md). -### Unit Testing +- See [docs/local-development.md](docs/local-development.md) to get started. +- New contributors should start with our [Contribution Guidelines](CONTRIBUTING.md). -To run all unit tests - -```bash -yarn test -``` - -To have your unit tests running in the background as you change code: - -```bash -yarn test:watch -``` - -### Format and Linting - -Linting and formatting are provided by [ESLint](https://eslint.org/) and [Prettier](https://prettier.io/). We recommend VSCode users to utilize the workspace settings in [.vscode/settings.json](.vscode/settings.json) and install the extensions in [.vscode/extensions](.vscode/extensions.json) for automated consistency. - -**We strongly recommend maintaining consistent code style by linting and formatting before every commit:** - -To run linting - -```bash -yarn lint -``` - -To lint and fix - -```bash -yarn lint:fix -``` - -Run format and fix: - -```bash -yarn format -``` - -### Populate Database - -Most open-source contributions (like running Cypress integration tests from the frontend) require adding test data to your local database. To do this, navigate to our [Chayn Tech Wiki Guide](https://www.notion.so/chayn/Chayn-Tech-Contributor-Wiki-5356c7118c134863a2e092e9df6cbc34?pvs=4#eb2e24de94bd451f8683abe496656013) to obtain a backup file and follow directions there to populate your local database. - -Chayn staff with access to Heroku, you also have the option to seed the database via the following script. Before you start, make sure: - -1. bloom-local-db container is running in Docker -2. you are logged into the Heroku via your terminal. Read more about the Heroku Cli [here](https://devcenter.heroku.com/articles/heroku-cli) -3. Replace with the correct Heroku app name in the `seed-local-db.sh file` -4. Run `chmod +x ./seed-local-db.sh` in your terminal to make the file executable - - After the above has been confirmed, run - - ```bash - bash seed-local-db.sh - ``` - -### Database Migrations - -A migration in TypeORM is a single file with SQL queries to update a database schema as updates/additions are made. Read more about migrations [here](https://github.com/typeorm/typeorm/blob/master/docs/migrations.md). - -Migrations are automatically run when the app is built docker (locally) or Heroku for staging and production apps. - -**You'll need to generate and run a migration each time you add or update a database field or table.** - -To generate a new migration - -```bash -yarn migration:generate -``` - -Add the new migration import into [typeorm.config.ts](./src/typeorm.config.ts) - -To run (apply) migrations - -```bash -yarn migration:run -``` - -To revert a migration - -```bash -yarn migration:revert -``` - -Note that when running the app in Docker, you may need to run migration commands from the docker terminal/Exec - -**New environment variables must be added to Heroku before release.** - -## Git Flow and Deployment - -**The develop branch is our source of truth, not main.** - -Create new branches from the `develop` base branch. There is no need to run the build command before pushing changes to GitHub, simply push and create a pull request for the new branch. GitHub Actions will run build and linting tasks automatically. Rebase and merge feature/bug branches into `develop`. - -This will trigger an automatic deployment to the staging app by Heroku. +Happy coding! ⭐ -When changes have been tested in staging, merge `develop` into `main`. This will trigger an automatic deployment to the production app by Heroku. +# Support Our Work -## Swagger +Chayn is proudly open-source and built with volunteer contributions. We are grateful for the generosity of the open-source community. -Swagger automatically reflects all of the endpoints in the app, showing their urls and example request and response objects. +**Please consider giving this repository a star ⭐ and follow our GitHub profile to help us grow our open-source community and find more contributors like you!** -To access Swagger simply run the project and visit http://localhost:35001/swagger +Support our mission further by [sponsoring us on GitHub](https://github.com/sponsors/chaynHQ), exploring [our volunteer programs](), and following us on [social media](https://linktr.ee/chayn). -## License +# Licence Bloom and all of Chayn's projects are open source. The core tech stack included here is open source however some external integrations used in the project require subscriptions. diff --git a/docs/configure-env.md b/docs/configure-env.md new file mode 100644 index 00000000..09b2fae5 --- /dev/null +++ b/docs/configure-env.md @@ -0,0 +1,63 @@ +## Configure Environment Variables + +Create a new `.env` file and fill it with the **required** environment variables: + +``` +# Variables for building and running tests. +# Provided variables are read-only and subject to change. +#=============================================================== +# REQUIRED VARIABLES FOR LOCAL DEVELOPMENT +#--------------------------------------------------------------- +# CORE ENVIRONMENT VARIABLES +PORT=35001 +DATABASE_URL=postgres://:@:/ +NODE_ENV=development + +# FIREBASE AUTH AND ANALYTICS +FIREBASE_TYPE=service_account +FIREBASE_PROJECT_ID= +FIREBASE_PRIVATE_KEY_ID= +FIREBASE_PRIVATE_KEY= +FIREBASE_CLIENT_EMAIL= +FIREBASE_CLIENT_ID= +FIREBASE_AUTH_URI=https://accounts.google.com/o/oauth2/auth +FIREBASE_TOKEN_URI=https://oauth2.googleapis.com/token +FIREBASE_CERT_URL=https://www.googleapis.com/oauth2/v1/certs +FIREBASE_CLIENT_CERT= +FIREBASE_API_KEY= +FIREBASE_AUTH_DOMAIN= +FIREBASE_PROJECT_ID= +FIREBASE_STORAGE_BUCKET= +FIREBASE_MESSAGING_SENDER_ID= +FIREBASE_API_ID= +FIREBASE_MEASUREMENT_ID= + +# REQUIRED VARIABLES FOR TESTING +#--------------------------------------------------------------- +# MOCK VALUES (can replace with real values or new mocks in same format) +SIMPLYBOOK_CREDENTIALS='{"login":"testlogin","password":"testpassword","company":"testcompany"}' +SIMPLYBOOK_COMPANY_NAME=testcompany + +# OPTIONAL VARIABLES +#--------------------------------------------------------------- +ROLLBAR_ENV=development # Rollbar logging +ROLLBAR_TOKEN= # Rollbar logging +ZAPIER_TOKEN= # Zapier automation +SLACK_WEBHOOK_URL= # Slack messaging bots +CRISP_TOKEN= # Crisp chat +MAILCHIMP_API_KEY= # Email messaging +RESPOND_IO_CREATE_CONTACT_WEBHOOK= # RESPOND.IO +RESPOND_IO_DELETE_CONTACT_WEBHOOK= # RESPOND.IO +``` + +## How to Configure Variables: + +The Firebase environment variables for Bloom’s frontend and backend are configured by [creating a project in the Firebase console](https://firebase.google.com/) (Google account is required). Ensure the toggle is turned on to enable Google Analytics as it is required for the `NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID` + +For `FIREBASE_PRIVATE_KEY_ID`, follow [these directions](https://firebase.google.com/docs/cloud-messaging/auth-server#provide-credentials-manually) to generate a private key file in JSON format. + +The frontend and backend each have _required_ and _optional_ environment variables. Required variables are necessary for local development, and optional variables are for specific features. + +Note: Variables provided by Chayn are public, not linked to production, and subject to change at any time. Check for updates if you are experiencing problems. The absence of some optional environment variables may result in test failures. If you require an optional environment variable and cannot acquire it yourself (some must be connected to Chayn in some way), please reach out to the team in GitHub’s issue discussions. + +**Please notify us if creating new environment variables in your PR so we can add it to Heroku before release deployment.** diff --git a/docs/data-architecture.md b/docs/data-architecture.md deleted file mode 100644 index f83fefb7..00000000 --- a/docs/data-architecture.md +++ /dev/null @@ -1,33 +0,0 @@ -## Database models - -![Database models](database_models.jpg 'Database models') - -**User** -Stores basic profile data for a user and relationships. - -**Partner** -Stores basic profile data for a partner and relationships. - -**Partner Admin** -Stores relationship between a partner and a user, and the partner access records created by the partner admin. - -**Partner Access** -Stores the features assigned for a user by a partner. When a partner access record is created by a partner admin user, it is initially unassigned but the unique code generated will be shared with the user. When the user registers using this code, the partner access will be assigned/related to the user, granting them access to extra features. See `assignPartnerAccess`. Currently there are "tiers" of access determined by the frontend, however if future partners want different features for their users, settings for their features/tiers should be added to the `Partner` model. - -**Therapy Session** -Stores data related to therapy sessions booked via Simplybook, copying the session time and details about the therapist etc. The duplication of data here (vs leaving it in Simplybook) was made to allow therapy reporting to be included in Data Studio. This model also allows for displaying therapy session data on the frontend. Populated by Simplybook -> Zapier webhooks. - -**Course** -Stores data related to courses in Storyblok, copying the story id's. The `Course` records allow us to relate users to courses (via `CourseUser`) and a `Course` to `Session` records, which is required e.g. to check if a user completed a course. The slug and name etc are also stored for convenience, e.g. to be used in reporting. Populated and updated by Storyblok webhooks when course stories are published. - -**Session** -Stores data related to courses in Storyblok, copying the story id's. The `Session` records allow us to relate users to sessions (via `SessionUser`). The slug and name etc are also stored for convenience, e.g. to be used in reporting. Populated and updated by Storyblok webhooks when course stories are published. - -**CourseUser** -Stores relationship between a `User` and `Course` records, once a user has started a course. A users progress (`completed`) for the course is updated (`true`) when all related `SessionUser` records are `completed` for the related `Course`. - -**SessionUser** -Stores relationship between a `User` and `Session` records, once a user has started a session. A users session progress (`completed`) for the session is updated (true) when the `/complete` endpoint is called. - -## Database Schema -![Database schema](database_schema.png) diff --git a/docs/database-guide.md b/docs/database-guide.md new file mode 100644 index 00000000..d0b073bd --- /dev/null +++ b/docs/database-guide.md @@ -0,0 +1,106 @@ +# Bloom Backend Database Guide + +## How to Populate the Database + +### Summary + +Most open-source contributions (like running Cypress integration tests from the frontend) require adding test data to your local database. To do this, download Bloom's test data dump file, connect to the database server, then populate the database with the backup data. + +### Download Test Data Dump File + +Download the test data dump file [linked here from our Google Drive](https://drive.google.com/file/d/1y6KJpAlpozEg3GqhK8JRdmK-s7uzJXtB/view?usp=drive_link). + +### Connect to Server and Add Data + +There are multiple methods you can use here. For simplicity, these directions assume you are using Docker. + +Run the following command to restore the database from the dump file using pg_restore: + +``` +docker exec -i pg_restore -U -d --clean --if-exists < +``` + +`container_name`, `username`, and `database_name` are defined in the `docker-compose.yml` file under ‘db’. + +Start the bloom psql database server: + +``` +docker exec -it psql -U -d +``` + +This will open the psql server for bloom, where you can run queries to verify the restore. + +You can verify the restore by running a SQL query to test if one of our test user's data has been properly populated into the database: + +``` +SELECT * FROM public."user" users WHERE users."email" = 'tech+cypresspublic@chayn.co'; +``` + +If the user exists, the database has successfully been seeded! + +### Troubleshooting + +- If you remove **`--clean`** from the restore command but encounter duplicate object errors, the existing schema may conflict with the restore. In that case, clean the specific objects manually or use **`DROP SCHEMA public CASCADE`** before restoring. +- Verify that the dump file is valid by running: `pg_restore --list yourfile.dump` If it fails to list contents, the dump file may be corrupted or incomplete. +- In the psql server, verify the tables and columns exist with `\dt` , `\dt public.*` , and `\d public."user";` +- Run a **`DROP SCHEMA`** or truncate tables before running **`pg_restore`:** + ``` + DROP SCHEMA public CASCADE; + CREATE SCHEMA public; + ``` +- Try the following: delete the existing db, create a new db with the same name, and try the restore on this new db. The db drop may throw an error, if so run the following command first. + + `SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = 'bloom';` + + Then drop the database using: + + `DROP DATABASE bloom;` + +- If the sql dump file is outdated, you can update it by running `docker compose down` then `docker compose up` again as this is configured to run migrations. + +### Chayn Staff - Heroku Directions + +Chayn staff with access to Heroku, you also have the option to seed the database via the following script. Before you start, make sure: + +1. bloom-local-db container is running in Docker +2. you are logged into the Heroku via your terminal. Read more about the Heroku Cli [here](https://devcenter.heroku.com/articles/heroku-cli) +3. Replace with the correct Heroku app name in the `seed-local-db.sh file` +4. Run `chmod +x ./seed-local-db.sh` in your terminal to make the file executable + + After the above has been confirmed, run + + ```bash + bash seed-local-db.sh + ``` + +## Database Migrations + +A migration in TypeORM is a single file with SQL queries to update a database schema as updates/additions are made. Read more about migrations [here](https://github.com/typeorm/typeorm/blob/master/docs/migrations.md). + +Migrations are automatically run when the app is built docker (locally) or Heroku for staging and production apps. + +**You'll need to generate and run a migration each time you add or update a database field or table.** + +To generate a new migration + +```bash +yarn migration:generate +``` + +Add the new migration import into [typeorm.config.ts](./src/typeorm.config.ts) + +To run (apply) migrations + +```bash +yarn migration:run +``` + +To revert a migration + +```bash +yarn migration:revert +``` + +Note that when running the app in Docker, you may need to run migration commands from the docker terminal/Exec + +https://drive.google.com/file/d/1y6KJpAlpozEg3GqhK8JRdmK-s7uzJXtB/view?usp=sharing diff --git a/docs/database_models.jpg b/docs/database_models.jpg deleted file mode 100644 index f19b5249..00000000 Binary files a/docs/database_models.jpg and /dev/null differ diff --git a/docs/database_schema.png b/docs/database_schema.png deleted file mode 100644 index fa404e10..00000000 Binary files a/docs/database_schema.png and /dev/null differ diff --git a/docs/key-concepts.md b/docs/key-concepts.md deleted file mode 100644 index c425934d..00000000 --- a/docs/key-concepts.md +++ /dev/null @@ -1,28 +0,0 @@ -## Key concepts - -### User types - -There are several user types with different features enabled. - -**Public user** - joins Bloom without a partner, with access to self guided and live courses. - -**Partner user** - joins Bloom via a partner (and access code) with access to extra features and courses enabled by the partner(s). - -**Partner admin user** - a partner team member who uses the app to complete Bloom admin tasks such as creating new partner access codes. - -### Authentication - -User authentication is handled by [Firebase Auth](https://firebase.google.com/docs/auth). Bearer tokens are sent in api request headers and verified in [auth.service.ts](src/auth/auth.service.ts). The user record is fetched using the retrieved user email of the token. - -### Crisp profiles - -Crisp is the messaging platform used to message the Chayn team in relation to bloom course content or other queries and support. For public users, this 1-1 chat feature is available on _live_ courses only. For partner users, This 1-1 chat feature is available to users with a `PartnerAccess` that has 1-1 chat enabled. - -Users who have access to 1-1 chat also have a profile on Crisp that reflects data from our database regarding their partners, access and course progress. See [crisp.service.ts](src/crisp/crisp.service.ts) - -### Reporting - -Google Data Studio is an online tool for converting data into customizable informative reports and dashboards. - -The reports are generated by writing custom sql queries that return actionable data to Data Studio. Filters are applied in Data Studio allowing -data to be segregated into different time periods based on the data createdAt date diff --git a/docs/local-development.md b/docs/local-development.md new file mode 100644 index 00000000..7c2c3cb8 --- /dev/null +++ b/docs/local-development.md @@ -0,0 +1,160 @@ +# Local Development Guide + +## Summary + +**The develop branch is our source of truth.** Fork from develop, create new feature branch, then when your PR is merged, develop will automatically merge into the main branch for deployment to production. + +To run Bloom's backend: + +1. Install prerequisites +2. Configure environment variables +3. Install dependencies +4. Run in a Dev Container, with Docker, or manually. +5. Populate the database (required for most fullstack contributions and running integration tests from the frontend) + +To test the backend: + +- Run unit tests +- Run e2e integration tests from the frontend for fullstack contributions \*requires populating the database with data first + +## Prerequisites + +- NodeJS v20.x +- Yarn v1.x +- Docker +- PostgreSQL 16 + +## Configure Environment Variables + +See [configure-env.md](configure-env.md) for instructions on configuring environment variables. + +## Install dependencies with yarn + +```bash +yarn +``` + +## Run the App Locally + +There are 3 methods you can use to run Bloom’s backend locally: + +1. **Using Docker (recommended)** - runs postgres in a container. +2. **Visual Studio Code Dev Container (recommended for Visual Studio users)** - installs all dependencies and the postgres database container automatically. +3. **Manually** - manage postgres locally. + +### With Docker - Recommended + +Bloom's backend is containerized and can be run solely in Docker - both the PostgreSQL database and NestJS app. This uses the least resources on your computer. To run the backend locally, make sure your system has Docker installed - you may need Docker Desktop if using a Mac or Windows. + +First, make sure the Docker app is running (just open the app). Then run + +```bash +docker-compose up +``` + +You should see this in the shell output: + +```shell +Listening on localhost:35001, CTRL+C to stop +``` + +_Note: you can use an application like Postman to test the apis locally_ + +### Run in Dev Container - Recommended for Visual Studio Users + +This method will automatically install all dependencies, IDE settings, and postgres container in a Dev Container (Docker container) within Visual Studio Code. + +Directions for running a dev container: + +1. Meet the [system requirements](https://code.visualstudio.com/docs/devcontainers/containers#_system-requirements) +2. Follow the [installation instructions](https://code.visualstudio.com/docs/devcontainers/containers#_installation) +3. [Check the installation](https://code.visualstudio.com/docs/devcontainers/tutorial#_check-installation) +4. After you've verified that the extension is installed and working, click on the "Remote Status" bar icon and select + "Reopen in Container". From here, the option to "Re-open in Container" should pop up in notifications whenever opening this project in VS. +5. [Configure your environment variables](#configure-environment-variables) and develop as you normally would. + +The dev Container is configured in the `.devcontainer` directory: + +- `docker-compose.yml` file in this directory extends the `docker-compose.yml` in the root directory. +- `devcontainer.json` configures the integrations with Visual Studio Code, such as the IDE extensions and settings in the `vscode` directory. + +See [Visual Studio Code Docs: Developing Inside a Dev Container](https://code.visualstudio.com/docs/devcontainers/containers) for more info. + +### Run Manually + +Manage postgres locally to [populate the database](#populate-database), then run: + +```bash +yarn start:dev +``` + +You should see this in the shell output: + +```shell +Listening on localhost:35001, CTRL+C to stop +``` + +## Unit Testing + +To run all unit tests + +```bash +yarn test +``` + +To have your unit tests running in the background as you change code: + +```bash +yarn test:watch +``` + +## Format and Linting + +Linting and formatting are provided by [ESLint](https://eslint.org/) and [Prettier](https://prettier.io/). We recommend VSCode users to utilize the workspace settings in [.vscode/settings.json](.vscode/settings.json) and install the extensions in [.vscode/extensions](.vscode/extensions.json) for automated consistency. + +**We strongly recommend maintaining consistent code style by linting and formatting before every commit:** + +To run linting + +```bash +yarn lint +``` + +To lint and fix + +```bash +yarn lint:fix +``` + +Run format and fix: + +```bash +yarn format +``` + +# Populate the Database and Database Migrations + +Populating your local database with test data is required for running Cypress integration tests and testing Bloom’s full-stack functionality. + +See the [database-guide.md](database-guide.md) for instructions. + +**Prerequisites:** + +- [Postgres 16](https://www.postgresql.org/download/) \*_technically not required if using the Docker method, but recommended._ +- Running Bloom’s backend + +# Git Flow and Deployment + +**The develop branch is our source of truth, not main.** + +Create new branches from the `develop` base branch. There is no need to run the build command before pushing changes to GitHub, simply push and create a pull request for the new branch. GitHub Actions will run build and linting tasks automatically. Rebase and merge feature/bug branches into `develop`. + +This will trigger an automatic deployment to the staging app by Heroku. + +When changes have been tested in staging, merge `develop` into `main`. This will trigger an automatic deployment to the production app by Heroku. + +# Swagger + +Swagger automatically reflects all of the endpoints in the app, showing their urls and example request and response objects. + +To access Swagger simply run the project and visit http://localhost:35001/swagger