<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Reza Apriono on Medium]]></title>
        <description><![CDATA[Stories by Reza Apriono on Medium]]></description>
        <link>https://medium.com/@rzapriono?source=rss-9921022861c9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*doPjqe5o_-dyqX4RCgfHDw.jpeg</url>
            <title>Stories by Reza Apriono on Medium</title>
            <link>https://medium.com/@rzapriono?source=rss-9921022861c9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 11:43:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rzapriono/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[SAST and DAST for Django Quality Assurance]]></title>
            <link>https://medium.com/@rzapriono/sast-and-dast-for-django-quality-assurance-d285ad1dc4fe?source=rss-9921022861c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/d285ad1dc4fe</guid>
            <category><![CDATA[sonarcloud]]></category>
            <category><![CDATA[owasp]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Reza Apriono]]></dc:creator>
            <pubDate>Wed, 21 May 2025 16:10:24 GMT</pubDate>
            <atom:updated>2025-05-21T16:10:24.373Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8wbmgJSPP2KgHTJY.jpg" /><figcaption>source: <a href="https://blog.fadhlizakiy.com/2024/03/25/beda-sast-dast-dan-penetration-testing-kenali-macam-uji-keamanan-aplikasimu/">https://blog.fadhlizakiy.com/2024/03/25/beda-sast-dast-dan-penetration-testing-kenali-macam-uji-keamanan-aplikasimu/</a></figcaption></figure><p>In modern web development, ensuring the security of applications is paramount. For Django applications, Static Application Security Testing (SAST) and Dynamic Application Security Testing (DAST) are critical practices to identify and mitigate vulnerabilities early and throughout the development lifecycle. In this article, I’ll share how I integrated SAST using SonarCloud and Bandit, and DAST using OWASP ZAP, into a Django project’s CI/CD pipeline to maintain high code quality and security standards.</p><h3>What Are SAST and DAST?</h3><p><strong>SAST</strong> (Static Application Security Testing) involves analyzing source code or compiled code without executing the program. It identifies potential security vulnerabilities, code quality issues, and coding standard violations early in the development process. Tools like SonarCloud and Bandit are popular for SAST in Python/Django projects.</p><p><strong>DAST</strong> (Dynamic Application Security Testing) tests a running application by simulating attacks on its endpoints. It identifies runtime vulnerabilities, such as SQL Injection or Cross-Site Scripting (XSS), by interacting with the application as an attacker would. OWASP ZAP is a widely-used DAST tool for this purpose.</p><h3>Setting Up SAST with SonarCloud and Bandit</h3><h4>SonarCloud for Code Quality and Security</h4><p>SonarCloud is a cloud-based SAST tool that integrates seamlessly with CI/CD pipelines to analyze code for bugs, vulnerabilities, and code smells. I configured SonarCloud in my Django project using GitHub Actions to run automated scans on every push and pull request.</p><p>Below is the GitHub Actions workflow I used to integrate SonarCloud with my Django project. It sets up a PostgreSQL database, runs tests with coverage, and uploads the results to SonarCloud for analysis.</p><pre>name: SonarCloud CI<br>on:<br>  push:<br>  pull_request:<br><br>jobs:<br>  build-test:<br>    runs-on: ubuntu-latest<br>    services:<br>      postgres:<br>        image: postgres:15<br>        env:<br>          POSTGRES_USER: postgres<br>          POSTGRES_PASSWORD: postgres<br>          POSTGRES_DB: test_db<br>        ports:<br>          - 5432:5432<br>        options: &gt;-<br>          --health-cmd=&quot;pg_isready -U postgres&quot;<br>          --health-interval=10s<br>          --health-timeout=5s<br>          --health-retries=5<br><br>    steps:<br>    - name: Checkout Repository<br>      uses: actions/checkout@v4<br>      with:<br>        fetch-depth: 0<br><br>    - name: Fetch base branch for PRs<br>      if: github.event_name == &#39;pull_request&#39;<br>      run: |<br>        git fetch origin ${{ github.event.pull_request.base.ref }} --depth=1<br><br>    - name: Set up Python 3.12<br>      uses: actions/setup-python@v4<br>      with:<br>        python-version: 3.12<br><br>    - name: Install Dependencies<br>      run: |<br>        python -m pip install --upgrade pip<br>        pip install -r requirements.txt<br>        pip install coverage diff-cover<br><br>    - name: Configure Database<br>      run: |<br>        echo &quot;DB_NAME=test_db&quot; &gt;&gt; $GITHUB_ENV<br>        echo &quot;DB_USER=postgres&quot; &gt;&gt; $GITHUB_ENV<br>        echo &quot;DB_PASS=postgres&quot; &gt;&gt; $GITHUB_ENV<br>        echo &quot;DB_HOST=localhost&quot; &gt;&gt; $GITHUB_ENV<br>        echo &quot;DB_PORT=5432&quot; &gt;&gt; $GITHUB_ENV<br><br>    - name: Run Migrations<br>      env:<br>        DB_NAME: test_db<br>        DB_USER: postgres<br>        DB_PASS: postgres<br>        DB_HOST: localhost<br>        DB_PORT: 5432<br>      run: python manage.py migrate<br><br>    - name: Run Tests with Coverage<br>      id: run_tests<br>      env:<br>        DB_NAME: test_db<br>        DB_USER: postgres<br>        DB_PASS: postgres<br>        DB_HOST: localhost<br>        DB_PORT: 5432<br>      continue-on-error: true<br>      run: |<br>        coverage run manage.py test || echo &quot;Some tests failed, continuing...&quot;<br><br>    - name: Debug - Check if .coverage file exists<br>      run: |<br>        ls -alh<br>        if [ -f .coverage ]; then<br>          echo &quot;✅ .coverage file exists.&quot;<br>        else<br>          echo &quot;❌ .coverage file is missing!&quot;<br>          exit 1<br>        fi<br><br>    - name: Generate Coverage XML<br>      run: |<br>        coverage xml || echo &quot;Failed to generate coverage.xml&quot;<br><br>    - name: Check New Code Coverage Threshold<br>      id: coverage_check<br>      if: github.event_name == &#39;pull_request&#39; &amp;&amp; github.base_ref == &#39;dev&#39;<br>      run: |<br>        COVERAGE_THRESHOLD=90<br>        diff-cover coverage.xml --compare-branch=origin/${{ github.base_ref }} --html-report=diff_coverage_report.html<br>        NEW_CODE_COVERAGE=$(diff-cover coverage.xml --compare-branch=origin/${{ github.base_ref }} | grep &quot;Coverage: &quot; | sed &#39;s/Coverage: \([0-9.]*\)%.*/\1/&#39;)<br>        echo &quot;New code coverage percentage: $NEW_CODE_COVERAGE%&quot;<br>        echo &quot;coverage_percent=$NEW_CODE_COVERAGE&quot; &gt;&gt; $GITHUB_OUTPUT<br>        if (( $(echo &quot;$NEW_CODE_COVERAGE &lt; $COVERAGE_THRESHOLD&quot; | bc -l) )); then<br>          echo &quot;❌ New code coverage is below the required threshold of $COVERAGE_THRESHOLD% (Current: $NEW_CODE_COVERAGE%)&quot;<br>          echo &quot;coverage_status=failed&quot; &gt;&gt; $GITHUB_OUTPUT<br>        else<br>          echo &quot;✅ New code coverage meets the required threshold of $COVERAGE_THRESHOLD% (Current: $NEW_CODE_COVERAGE%)&quot;<br>          echo &quot;coverage_status=success&quot; &gt;&gt; $GITHUB_OUTPUT<br>        fi<br><br>    - name: Create Coverage Status Check<br>      if: github.event_name == &#39;pull_request&#39; &amp;&amp; github.base_ref == &#39;dev&#39;<br>      run: |<br>        if [[ &quot;${{ steps.coverage_check.outputs.coverage_status }}&quot; == &quot;failed&quot; ]]; then<br>          echo &quot;::error::Coverage below threshold: Required 90%, Current ${{ steps.coverage_check.outputs.coverage_percent }}%&quot;<br>          exit 1<br>        else<br>          echo &quot;✅ Coverage meets threshold: Required 90%, Current ${{ steps.coverage_check.outputs.coverage_percent }}%&quot;<br>        fi<br><br>    - name: Debug - Check if coverage.xml file exists<br>      run: |<br>        ls -alh<br>        if [ -f coverage.xml ]; then<br>          echo &quot;✅ coverage.xml file exists.&quot;<br>        else<br>          echo &quot;❌ coverage.xml file is missing!&quot;<br>          exit 1<br>        fi<br><br>    - name: Upload Coverage Report<br>      if: always()<br>      uses: actions/upload-artifact@v4<br>      with:<br>        name: coverage-report<br>        path: |<br>          coverage.xml<br>          diff_coverage_report.html<br><br>  sonarcloud:<br>    needs: build-test<br>    runs-on: ubuntu-latest<br>    if: always()<br>    steps:<br>    - name: Checkout Repository<br>      uses: actions/checkout@v4<br>      with:<br>        fetch-depth: 0<br><br>    - name: Download Coverage Report<br>      uses: actions/download-artifact@v4<br>      with:<br>        name: coverage-report<br><br>    - name: SonarCloud Scan<br>      uses: SonarSource/sonarcloud-github-action@master<br>      env:<br>        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}<br>        SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}<br>      with:<br>        args: &gt;<br>          -Dsonar.organization=${{ secrets.SONAR_ORGANIZATION_KEY }}<br>          -Dsonar.projectKey=${{ secrets.SONAR_PROJECT_KEY }}<br>          -Dsonar.python.version=3.12<br>          -Dsonar.sources=.<br>          -Dsonar.python.coverage.reportPaths=coverage.xml<br>          -Dsonar.exclusions=locustfile.py,manage.py,**/tests/**,**/migrations/**,**/__init__.py,**/admin.py,**/apps.py</pre><p>This workflow:</p><ul><li>Sets up a PostgreSQL database for testing.</li><li>Runs Django migrations and tests with coverage.</li><li>Generates a coverage report and enforces a 90% coverage threshold for new code in pull requests.</li><li>Uploads the coverage report to SonarCloud for detailed analysis, excluding irrelevant files like migrations and tests.</li></ul><p>SonarCloud provides actionable insights into code smells, security vulnerabilities, and test coverage, helping maintain a high-quality codebase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C6cPSvhft-qo2GILlecTZQ.png" /><figcaption>SonarCloud Scan Results on Dev Branch</figcaption></figure><p>The latest SonarCloud scan for budidayaplus-BE analyzed 2.6K lines of code (Python, Docker) with the following results:</p><ul><li><strong>Security</strong>: A grade, 0 issues</li><li><strong>Reliability</strong>: A grade, 0 issues</li><li><strong>Maintainability</strong>: A grade, 13 issues</li><li><strong>Hotspots Reviewed</strong>: C grade, 50.0%</li><li><strong>Coverage</strong>: 91.4%</li><li><strong>Duplications</strong>: 0.0%</li><li><strong>Status</strong>: Passed</li></ul><p>This indicates excellent security and reliability, with maintainability needing attention (13 issues) and hotspots requiring more review (50% coverage). The 91.4% test coverage is strong, with no code duplication.</p><h4>Bandit for Python-Specific Security</h4><p>Bandit is a SAST tool designed to find common security issues in Python code, such as insecure use of eval(), hardcoded secrets, or unsafe deserialization.</p><p>To use bandit to perform security checks, simply install it using:</p><pre>pip install bandit</pre><p>I run Bandit to perform Python-specific security checks on BudidayaPlus codebase. My command targets the app directories and excludes the tests directory:</p><pre>bandit -r authentication budidayaplus cycle fish_death fish_sampling food_sampling forum pond pond_quality tasks threshold user_profile --exclude tests</pre><p>Running this command, I received the following results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Szbnnld_Fm_xa0ITvBNSw.png" /><figcaption>Bandit test results</figcaption></figure><p>This output indicates that Bandit found no security issues across the 3,154 lines of code scanned in the specified directories. The absence of vulnerabilities (across all severity and confidence levels) suggests that BudidayaPlus application code adheres to secure coding practices, likely due to Django’s built-in protections and careful development.</p><p>Running Bandit allows me to focus on modules i work on during development before pushing it to git repository, complementing SonarCloud’s automated scans.</p><h3>DAST with OWASP ZAP</h3><p>I used <strong>OWASP ZAP</strong> to test the /api/auth/login endpoint for runtime vulnerabilities like SQL Injection:</p><h4><strong>Fuzzer Setup</strong></h4><p>Intercepted a POST request (phone_number=087777777777, password=test123) and applied SQL Injection payloads (e.g., ‘ or 1=1 — ).</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*dECNMkEEwSrlVzJ7.png" /><figcaption>Creating Fuzzer for Requests</figcaption></figure><h4><strong>Results</strong></h4><p>Most fuzzed requests returned 400 Bad Request, indicating strong input validation. Some triggered 429 Too Many Requests, showing rate-limiting protection against brute-force attacks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oyDng06FS5QlQbqhrCZXzA.png" /><figcaption>Fuzzer Results</figcaption></figure><h3>Performance Analysis with Silk and Locust</h3><h4>Profiling with Silk</h4><p>I integrated <strong>Silk</strong> to profile the /api/auth/login endpoint:</p><pre># budidayaplus/settings.py<br>INSTALLED_APPS = [<br>    ...,<br>    &#39;silk&#39;,<br>]<br><br>MIDDLEWARE = [<br>    ...,<br>    &#39;silk.middleware.SilkyMiddleware&#39;,<br>]<br><br>SILKY_PYTHON_PROFILER = True</pre><p>The endpoint was decorated with @silk_profile:</p><pre>@router.post(&quot;/login&quot;, throttle=AnonRateThrottle(rate=&quot;10/h&quot;))<br>@silk_profile(name=&quot;Profiling Login API&quot;)<br>def login(request, data: LoginSchema):<br>    user = User.objects.get(username=data.phone_number)<br>    if not user.check_password(data.password):<br>        raise HttpError(404, &quot;Pengguna tidak terdaftar atau kata sandi salah&quot;)<br>    refresh = RefreshToken.for_user(user)<br>    return {&quot;access_token&quot;: str(refresh.access_token), &quot;refresh_token&quot;: str(refresh)}</pre><p><strong>Initial Profiling Results</strong></p><p>Using Silk with PBKDF2:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a5YmIxDG1G8xR1w2bLHxwA.png" /><figcaption>Profiling Results with PBKDF2</figcaption></figure><ul><li><strong>Overall Request Time</strong>: 1087ms</li><li><strong>Database Queries</strong>: 1 query (SELECT on auth_user), 2ms</li></ul><p>Silk identified the bottleneck in password hashing, not in input validation or database queries, which were minimal (2ms).</p><p><strong>Post-Optimization with Argon2</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PLLl4IgNUTFbXwn2n5Y1qA.png" /><figcaption>Profiling Results with Argon2</figcaption></figure><p>After switching to Argon2 (enabled by the clean SAST results):</p><ul><li><strong>First Request</strong>: 944ms overall, 18ms on queries (2 queries due to re-hashing).</li><li><strong>Subsequent Requests</strong>: 159ms overall, 2ms on queries.</li></ul><p>This achieved a <strong>7x improvement</strong> (1087ms to 159ms) in response time, with input validation remaining a negligible 2ms.</p><h4>Load Testing with Locust</h4><p>I used <strong>Locust</strong> to test scalability with 200 concurrent users over 3 minutes.</p><p><strong>Load Test Results with PBKDF2</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_vnenOZR13r1wxRmofhmIw.png" /><figcaption>Chart from the Locust Report using PBKDF2</figcaption></figure><ul><li><strong>Median Response Time</strong>: 7800ms for /api/auth/login</li><li><strong>Max Response Time</strong>: 23000ms (95th percentile: 20000ms)</li><li><strong>Requests per Second</strong>: 20–25</li></ul><p>Rate-limiting (from DAST) exacerbated latency under load.</p><p><strong>Load Test Results with Argon2</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8POSc9P4c_O9dP9Bp9soyA.png" /><figcaption>Chart from the Locust Report using Argon2</figcaption></figure><p>After switching to Argon2:</p><ul><li><strong>Median Response Time</strong>: 4700ms for /api/auth/login</li><li><strong>Max Response Time</strong>: 12000ms (95th percentile: 6300ms)</li><li><strong>Requests per Second</strong>: 25–30</li></ul><p>This shows a <strong>40% reduction</strong> in median response time, with rate-limiting preserved.</p><h3>DAST’s Impact on Performance Analysis</h3><p>DAST findings influenced performance optimization:</p><ul><li><strong>Rate-Limiting and Performance Trade-Offs</strong>: The 429 responses highlighted rate-limiting, a security feature that prevents brute-force attacks but can impact performance under load by delaying legitimate users. This prompted me to use Locust to test how rate-limiting affects scalability, ensuring performance optimizations wouldn’t undermine this security measure.</li><li><strong>Input Validation and Query Time</strong>: The 400 responses confirmed robust input validation, which includes querying the database to check if the phone_number exists. Silk’s profiling showed this SELECT query took 2ms, a small but measurable part of the login process. This ensured that the security provided by input validation didn’t significantly degrade performance, allowing me to focus optimization efforts on the larger bottleneck (password hashing).</li></ul><h3>Performance Impact on Security</h3><p>The performance optimization enhanced security:</p><ul><li><strong>Rate-Limiting Effectiveness</strong>: Faster response times (159ms vs. 1087ms) reduced the likelihood of legitimate users hitting rate limits, preserving the security feature identified by DAST.</li><li><strong>Argon2 Security</strong>: The switch to Argon2 improved both performance and security, as confirmed by SAST’s clean report.</li></ul><h3>Final Thoughts</h3><p>Combining SAST and DAST ensures comprehensive security for my Django application:</p><ul><li><strong>SonarCloud</strong> automates static analysis in the CI/CD pipeline, catching code quality and security issues early.</li><li><strong>Bandit</strong> provides Python-specific security checks, with my recent scan showing zero issues across 3,154 lines of code.</li><li><strong>OWASP ZAP</strong> validates runtime security, confirming that endpoints like /api/auth/login are protected against attacks like SQL Injection and other exploits.</li><li><strong>Performance Tools (Silk, Locust)</strong>: Achieved a 7x improvement in login response time (1087ms to 159ms) and a 40% reduction in median load test response time (7800ms to 4700ms), while preserving security features.</li></ul><p>This approach has fortified BudidayaPlus, ensuring it is secure, maintainable, and efficient. You can adopt similar practices by integrating SonarCloud into CI/CD, running Bandit for security checks, and using OWASP ZAP for runtime security testing.</p><h3>Thank you for reading my story!</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d285ad1dc4fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Refactoring an API for Performance with Repository and Gateway Patterns]]></title>
            <link>https://medium.com/@rzapriono/refactoring-an-api-for-performance-with-repository-and-gateway-patterns-ec793e1dc3e7?source=rss-9921022861c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec793e1dc3e7</guid>
            <dc:creator><![CDATA[Reza Apriono]]></dc:creator>
            <pubDate>Mon, 19 May 2025 04:05:48 GMT</pubDate>
            <atom:updated>2025-06-03T20:56:11.997Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vt8WKX-31zk4EHh89dy5Wg.jpeg" /><figcaption>source: <a href="https://xbsoftware.com/blog/code-refactoring-techniques-in-software-engineering/">https://xbsoftware.com/blog/code-refactoring-techniques-in-software-engineering/</a></figcaption></figure><h3>Introduction</h3><p>Enterprise applications often require efficient data retrieval to deliver responsive user experiences, especially for interactive features that manage user-generated content. In this case, we focus on a discussion system where users create posts, reply to each other, and vote on content, demanding quick access to lists of posts, vote summaries, and user voting history. Martin Fowler’s <em>Patterns of Enterprise Application Architecture</em> emphasizes that <strong>response time</strong> is critical in such data-heavy systems, where excessive network round-trips can degrade performance (Fowler et al., 2002, p. 16, 27). The <strong>Repository</strong> pattern abstracts data access, enhancing maintainability and testability, while the <strong>Gateway</strong> pattern provides a unified interface for related data, optimizing client interactions (Fowler et al., 2002, pp. 280, 397).</p><p>In this story, we explore refactoring an API in a Django application using the Django Ninja framework. The original API required three separate HTTP requests to fetch discussion data, increasing client-side latency. By consolidating these into a single endpoint using the <strong>Repository</strong> and <strong>Gateway</strong> patterns, we reduce requests, improve performance, and maintain architectural clarity.</p><h3>The Original API</h3><p>The original API included three endpoints in api.py to fetch discussion-related data:</p><ol><li>get_list_forums: Retrieves a paginated list of discussion posts using ForumRepository.list_forums, optimized with select_related for user data.</li><li>vote_summary: Fetches the vote summary (upvotes) and user’s vote for a single post, using ForumRepository.get_vote_summary and a direct ForumVote query.</li><li>get_votes_by_user: Returns all votes by the authenticated user, directly querying ForumVote.</li></ol><pre>from typing import List<br>from ninja import Router, Query<br>from ninja.responses import Response<br>from uuid import UUID<br>from forum.models import ForumVote<br>from forum.schemas import ForumUpdateSchema, ForumOutputSchema, ForumCreateSchema, ForumReplySchema<br>from forum.repositories.forum_repository import ForumRepository<br>from forum.models import Forum<br>from ninja_jwt.authentication import JWTAuth<br>from ninja import Query<br>from django.http import Http404, HttpResponse, JsonResponse<br><br>router = Router()<br><br>@router.get(&quot;/list&quot;, response=List[ForumOutputSchema], auth=JWTAuth())<br>def get_list_forums(request, limit: int = Query(20, ge=1, le=100), offset: int = Query(0, ge=0)):<br>    &quot;&quot;&quot;<br>    Endpoint untuk mengambil daftar forum dengan pagination dan optimisasi query.<br>    &quot;&quot;&quot;<br>    forums = ForumRepository.list_forums(limit=limit, offset=offset)<br>    return forums<br>    <br>@router.get(&quot;/user_votes&quot;, auth=JWTAuth())<br>def get_votes_by_user(request):<br>    &quot;&quot;&quot;<br>    Mendapatkan semua vote yang diberikan oleh user yang sedang login.<br>    &quot;&quot;&quot;<br>    if not request.user.is_authenticated: return Response({&quot;error&quot;: &quot;You are not authorized to access this resource.&quot;}, status=403)<br><br>    votes = ForumVote.objects.filter(user=request.user).values(&quot;forum__id&quot;, &quot;forum__description&quot;) <br>    return JsonResponse({&quot;votes&quot;: list(votes)}, safe=False)<br><br>@router.get(&quot;/vote_summary/{forum_id}&quot;, auth=JWTAuth())<br>def vote_summary(request, forum_id: UUID):<br>    forum = ForumRepository.get_forum_by_id(forum_id)<br>    summary = ForumRepository.get_vote_summary([forum.id])<br><br>    summary = summary.get(forum.id, {&quot;upvotes&quot;: 0})<br>    <br>    user_vote = ForumVote.objects.filter(user=request.user, forum=forum).first()<br>    summary[&quot;user_vote&quot;] = &quot;up&quot; if user_vote else None<br><br>    return summary</pre><p><strong>Issues</strong>:</p><ul><li><strong>Multiple HTTP Requests</strong>: Clients needed up to three requests to fetch complete discussion data (posts, vote summaries, user votes), increasing latency (e.g., ~150ms for three 50ms requests), as Fowler notes about round-trip costs (Fowler et al., 2002, p. 16, 27).</li><li><strong>Mixed Concerns</strong>: Direct ForumVote queries in vote_summary and get_votes_by_user bypass the <strong>Repository</strong> layer, violating <strong>Layered Architecture</strong> principles (Fowler et al., 2002, p. 21).</li><li><strong>Inefficient Queries</strong>: Per-post vote summaries in vote_summary scale poorly for large lists, increasing database load (Fowler et al., 2002, p. 16).</li><li><strong>Testability</strong>: Direct queries hinder unit testing without mocking the database.</li></ul><h3>Refactored API</h3><p>The API is refactored into a single forum_overview endpoint, using the <strong>Repository</strong> pattern for data access and the <strong>Gateway</strong> pattern to provide a unified response combining post lists, vote summaries, and user votes. The implementation leverages ForumRepository for optimized queries and minimizes client-side requests.</p><p>You can view the complete refactoring changes in these <a href="https://github.com/PPL-5B/budidayaplus-BE/commits/dev/?since=2025-05-13&amp;until=2025-05-13&amp;author=rzapriono">commits</a>.</p><h4>Repository Layer (forum/repositories/forum_repository.py)</h4><pre>import json<br>from uuid import UUID<br>from typing import Optional, List<br>from django.shortcuts import get_object_or_404<br>from forum.models import Forum, ForumVote<br>from django.contrib.auth.models import User<br>from django.core.exceptions import ObjectDoesNotExist<br>from django.db import models<br><br>class ForumRepository:<br>    @staticmethod<br>    def list_forums(limit=20, offset=0, parent_id: Optional[UUID] = None):<br>        &quot;&quot;&quot;<br>        Mengambil daftar forum dengan pagination dan filter parent_id.<br>        Jika parent_id=None, hanya forum utama yang diambil.<br>        &quot;&quot;&quot;<br>        query = Forum.objects.select_related(&quot;user&quot;)<br>        if parent_id is None:<br>            query = query.filter(parent__isnull=True)  # Hanya forum utama<br>        else:<br>            query = query.filter(parent_id=parent_id)  # Hanya balasan untuk forum tertentu<br>        return query.order_by(&quot;-timestamp&quot;)[offset:offset + limit]<br><br>    @staticmethod<br>    def get_vote_summary(forum_ids: List[UUID]) -&gt; dict:<br>        &quot;&quot;&quot;<br>        Returns a summary of votes for a list of forums.<br>        &quot;&quot;&quot;<br>        votes = ForumVote.objects.filter(forum_id__in=forum_ids).values(&quot;forum_id&quot;).annotate(upvotes=models.Count(&quot;id&quot;))<br>        return {vote[&quot;forum_id&quot;]: {&quot;upvotes&quot;: vote[&quot;upvotes&quot;]} for vote in votes}</pre><p><strong>Key Points</strong>:</p><ul><li>Uses select_related(“user”) in list_forums to reduce database queries by fetching user data in a single join, aligning with Fowler’s performance optimization advice (Fowler et al., 2002, p. 16).</li><li>get_vote_summary batch-processes vote counts for multiple posts, improving scalability (Fowler et al., 2002, p. 17).</li><li>Adheres to the <strong>Repository</strong> pattern by providing a collection-like interface (Fowler et al., 2002, p. 280).</li></ul><h4>API Layer (forum/api.py)</h4><p>The forum_overview endpoint consolidates discussion data into a single response, acting as a <strong>Gateway</strong> for client interactions.</p><pre>from typing import List<br>from ninja import Router, Query<br>from ninja.responses import Response<br>from uuid import UUID<br>from forum.models import ForumVote<br>from forum.schemas import ForumUpdateSchema, ForumOutputSchema, ForumCreateSchema, ForumReplySchema<br>from forum.repositories.forum_repository import ForumRepository<br>from forum.models import Forum<br>from ninja_jwt.authentication import JWTAuth<br>from ninja import Query<br>from silk.profiling.profiler import silk_profile<br>from django.http import Http404, HttpResponse, JsonResponse<br><br>router = Router()<br><br>@router.get(&quot;/forum_overview&quot;, response=List[ForumOutputSchema], auth=JWTAuth())<br>def forum_overview(request, limit: int = Query(20, ge=1, le=100), offset: int = Query(0, ge=0)):<br>    forums = ForumRepository.list_forums(limit=limit, offset=offset, parent_id=None)<br>    forum_ids = [forum.id for forum in forums]<br><br>    vote_summaries = ForumRepository.get_vote_summary(forum_ids)<br>    user_votes = ForumVote.objects.filter(user=request.user, forum_id__in=forum_ids).values_list(&quot;forum_id&quot;, flat=True)<br><br>    result = []<br>    for forum in forums:<br>        result.append({<br>            &quot;id&quot;: forum.id,<br>            &quot;user&quot;: {<br>                &quot;id&quot;: forum.user.id,<br>                &quot;username&quot;: forum.user.username, <br>                &quot;first_name&quot;: forum.user.first_name,<br>                &quot;last_name&quot;: forum.user.last_name,<br>            },<br>            &quot;title&quot;: forum.title,<br>            &quot;description&quot;: forum.description,<br>            &quot;tag&quot;: forum.tag,<br>            &quot;timestamp&quot;: forum.timestamp,<br>            &quot;parent_id&quot;: forum.parent.id if forum.parent else None,<br>            &quot;replies&quot;: [],<br>            &quot;upvotes&quot;: vote_summaries.get(forum.id, {}).get(&quot;upvotes&quot;, 0),<br>            &quot;user_vote&quot;: &quot;up&quot; if forum.id in user_votes else None,<br>        })<br><br>    return result</pre><p><strong>Key Points</strong>:</p><ul><li>Consolidates three endpoints into one, reducing client-side requests, aligning with the <strong>Gateway</strong> pattern’s goal of providing a unified interface (Fowler et al., 2002, p. 397).</li><li>Uses ForumRepository for post listing and vote summaries, adhering to <strong>Layered Architecture</strong> (Fowler et al., 2002, p. 21).</li><li>Direct ForumVote query (user_votes) bypasses the repository, a minor layer violation for simplicity, but could be encapsulated in ForumRepository for consistency.</li><li>Returns a structured response via ForumOutputSchema, ensuring type safety and clarity.</li></ul><h3>Benefits of the Refactoring</h3><ol><li><strong>Reduced Client-Side Latency</strong>: Consolidating three requests into one cuts latency (e.g., from ~150ms for three 50ms requests to ~60ms for one, assuming 10ms server processing overhead), as Fowler emphasizes minimizing round-trips (Fowler et al., 2002, p. 16, 27).</li><li><strong>Improved Scalability</strong>: Batch fetching vote summaries via get_vote_summary reduces database queries compared to per-post calls, supporting Fowler’s scalability principles (Fowler et al., 2002, p. 17).</li><li><strong>Maintainability: </strong>The <strong>Repository</strong> pattern isolates data access, allowing persistence changes (e.g., switching to a NoSQL database) without affecting the API (Fowler et al., 2002, p. 281).</li><li><strong>Testability</strong>: Mocking ForumRepository enables unit testing without database access, aligning with Fowler’s testable designs (Fowler et al., 2002, p. 281–282).</li></ol><h3>Trade-offs</h3><p>Fowler highlights that architectural decisions involve trade-offs (Fowler et al., 2002, p. 14):</p><ul><li><strong>Layer Violation</strong>: The direct ForumVote query in forum_overview bypasses the <strong>Repository</strong> layer, reducing consistency with <strong>Layered Architecture</strong>. Encapsulating this in ForumRepository would resolve this (Fowler et al., 2002, p. 21).</li><li><strong>Overfetching Risk</strong>: The endpoint returns comprehensive data (e.g., user details, upvotes), potentially increasing payload size for clients needing only partial data. A <strong>Gateway</strong> could offer flexible response options (Fowler et al., 2002, p. 397).</li><li><strong>No Service Layer</strong>: Business logic (e.g., response formatting, user vote mapping) resides in the API layer, which may complicate maintenance for complex operations compared to a <strong>Service Layer</strong> (Fowler et al., 2002, p. 126).</li></ul><h3>Final Thoughts</h3><p>Refactoring the discussion API into a single forum_overview endpoint using the <strong>Repository</strong> and <strong>Gateway</strong> patterns significantly reduced client-side latency by eliminating multiple HTTP requests, enhancing performance for interactive user experiences. The refactoring improves scalability and maintainability, aligning with Fowler’s principle of context-specific pattern adaptation (Fowler et al., 2002, p. 18). By leveraging <strong>Repository</strong> for optimized data access and <strong>Gateway</strong> for unified responses, developers can balance performance and architectural clarity in enterprise applications.</p><h3>Thank you for reading my story!</h3><p>References:</p><ol><li>Fowler, M., Rice, D., Foemmel, M., Hieatt, E., Mee, R., &amp; Stafford, R. (2002). <em>Patterns of Enterprise Application Architecture</em>. Addison-Wesley.</li></ol><ul><li>Chapter 1: Layering (pp. 21–28)</li><li>Chapter 13: Repository (pp. 280–284)</li><li>Chapter 14: Gateway (pp. 397–401)</li></ul><p>2. Django Ninja Documentation</p><p>3. Django Silk Documentation</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec793e1dc3e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Refactoring with Repository and Service Layer Patterns]]></title>
            <link>https://medium.com/@rzapriono/refactoring-with-repository-and-service-layer-patterns-5401bc7ca944?source=rss-9921022861c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/5401bc7ca944</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Reza Apriono]]></dc:creator>
            <pubDate>Sun, 18 May 2025 08:13:21 GMT</pubDate>
            <atom:updated>2025-06-03T20:58:55.665Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*qvWYORRW5R1fSK7t32BNMw.png" /><figcaption>source: <a href="https://martinfowler.com/bliki/PresentationDomainDataLayering.html">https://martinfowler.com/bliki/PresentationDomainDataLayering.html</a></figcaption></figure><h3>Introduction</h3><p>Building enterprise applications involves managing complex business logic, data persistence, and user interactions. As Martin Fowler notes in <em>Patterns of Enterprise Application Architecture</em>, enterprise applications are characterized by persistent data, concurrent access, and intricate business rules that often defy logical consistency (Fowler et al., 2002, p. 12). To handle this complexity, architectural patterns like <strong>Layered Architecture</strong>, <strong>Repository</strong>, and <strong>Service Layer</strong> are essential for creating maintainable and scalable systems (Fowler et al., 2002, pp. 21, 126, 280).</p><p>In this story, we explore refactoring an authentication API in a Django application using the Django Ninja framework. The original code, located in authentication/api.py, mixes business logic, data access, and API routing, leading to issues like poor testability and maintainability. By applying the <strong>Repository</strong> and <strong>Service Layer</strong> patterns, we restructure the code into distinct layers, improving separation of concerns and aligning with Fowler’s principles of enterprise application design.</p><h3>The Original Code</h3><p>The original authentication/api.py implements endpoints for login, registration, token refresh, token validation, and user details retrieval. It directly interacts with Django’s User model and handles JWT token generation, error handling, and response formatting within the same file.</p><pre>from authentication.schemas import LoginSchema, RegisterSchema, RefreshSchema<br>from ninja import Router<br>from ninja.throttling import AnonRateThrottle<br>from ninja_jwt.tokens import RefreshToken<br>from ninja_jwt.exceptions import TokenError<br>from ninja.errors import HttpError<br>from django.contrib.auth.models import User<br>from ninja_jwt.authentication import JWTAuth<br><br>router = Router()<br><br>@silk_profile(name=&quot;Profiling Login API&quot;) <br>def login(request, data: LoginSchema):<br>    try:<br>        print(&quot;Login attempt with data:&quot;, data.dict())<br>        user = User.objects.get(username=data.phone_number)<br>        if not user.check_password(data.password):<br>            raise HttpError(404, &quot;Pengguna tidak terdaftar atau kata sandi salah&quot;)<br><br>        refresh = RefreshToken.for_user(user)<br>        new_access_token = str(refresh.access_token)<br><br>        print(&#39;access token:&#39; + new_access_token)<br><br>        response = {<br>            &quot;message&quot;: &quot;Login berhasil&quot;,<br>            &quot;access&quot;: new_access_token,<br>            &quot;refresh&quot;: str(refresh),<br>        }<br><br>        return response<br>    <br>    except User.DoesNotExist:<br>        raise HttpError(404, &quot;Pengguna tidak terdaftar atau kata sandi salah&quot;)<br><br>@router.post(&quot;/register&quot;)<br>def register(request, data: RegisterSchema):<br>    try:<br>        if User.objects.filter(username=data.phone_number).exists():<br>            raise HttpError(400, &quot;Pengguna sudah terdaftar&quot;)<br><br>        user = User.objects.create_user(<br>            username=data.phone_number,<br>            password=data.password,<br>            first_name=data.first_name,<br>            last_name=data.last_name,<br>            is_staff=True<br>        )<br>        refresh = RefreshToken.for_user(user)<br>        return {<br>            &quot;message&quot;: &quot;Akun berhasil dibuat&quot;,<br>            &quot;access&quot;: str(refresh.access_token),<br>            &quot;refresh&quot;: str(refresh),<br>        }<br>    except Exception as e:<br>        raise HttpError(400, str(e))<br><br>@router.post(&quot;/refresh&quot;)<br>def refresh(request, data: RefreshSchema):<br>    try:<br>        refresh = RefreshToken(data.refresh)<br>        new_access_token = str(refresh.access_token)<br><br>        user_id = refresh.payload.get(&quot;user_id&quot;)<br>        if not User.objects.filter(id=user_id).exists():<br>            raise HttpError(401, &quot;Pengguna tidak ditemukan atau token tidak valid&quot;)<br>        return {&quot;access&quot;: new_access_token}<br>    except TokenError:<br>        raise HttpError(401, &quot;Token invalid atau telah kadaluarsa&quot;)<br><br>@router.post(&quot;/validate&quot;, auth=JWTAuth())<br>def validate(request):<br>    return {&quot;message&quot;: &quot;Token valid&quot;}<br><br>@router.get(&quot;/me&quot;, auth=JWTAuth())<br>def get_user_by_token(request):<br>    user = request.auth<br>    return {<br>        &quot;id&quot;: user.id,<br>        &quot;phone_number&quot;: user.username,<br>        &quot;first_name&quot;: user.first_name,<br>        &quot;last_name&quot;: user.last_name<br>    }</pre><p>Here’s a summary of its functionality:</p><ul><li><strong>Login</strong>: Authenticates users by phone number and password, returning JWT access and refresh tokens.</li><li><strong>Register</strong>: Creates a new user and returns JWT tokens.</li><li><strong>Refresh</strong>: Generates a new access token from a refresh token.</li><li><strong>Validate</strong>: Verifies JWT token validity.</li><li><strong>Get User Details</strong>: Retrieves user information from a valid token.</li></ul><p>This implementation has several drawbacks:</p><ul><li><strong>Mixed Concerns</strong>: Business logic (e.g., password validation, token generation) and data access (e.g., User.objects queries) are coupled, violating the <strong>Layered Architecture</strong> principle (Fowler et al., 2002, p. 21).</li><li><strong>Poor Testability</strong>: Direct database queries make unit testing difficult without mocking the database.</li><li><strong>Scalability Issues</strong>: Adding new features or changing the persistence layer requires modifying the API code.</li><li><strong>Code Duplication</strong>: Error handling and response formatting are repeated across endpoints.</li></ul><p>To address these issues, we refactored the code using the <strong>Repository</strong> and <strong>Service Layer</strong> patterns, which Fowler describes as effective solutions for organizing data access and business logic (Fowler et al., 2002, pp. 126, 280).</p><h3>Design Patterns Applied</h3><h4>Layered Architecture</h4><p>Fowler emphasizes that <strong>Layering</strong> is a fundamental technique for breaking down complex software systems into manageable subsystems (Fowler et al., 2002, p. 21). In a layered architecture, each layer depends on the layer below it, providing services while hiding implementation details. For our authentication system, we adopt a three-layer structure:</p><ul><li><strong>Presentation Layer</strong> (API): Handles HTTP requests and responses.</li><li><strong>Domain Layer</strong> (Service): Encapsulates business logic.</li><li><strong>Data Source Layer</strong> (Repository): Manages data persistence.</li></ul><p>This aligns with Fowler’s “Three Principal Layers” (presentation, domain, data source), ensuring clear separation of concerns (Fowler et al., 2002, p. 21).</p><h4>Repository Pattern</h4><p>The <strong>Repository</strong> pattern provides a collection-like interface for accessing domain objects, abstracting the data layer from the business logic (Fowler et al., 2002, p. 280). It acts as an intermediary between the domain layer and the data source, allowing the business logic to operate on objects without concerning itself with database details.</p><p>In our refactored code, the UserRepository class encapsulates all interactions with Django’s User model, such as retrieving users, checking existence, and creating new users. This abstraction makes it easier to switch persistence mechanisms (e.g., from Django ORM to a NoSQL database) without affecting the business logic.</p><h4>Service Layer Pattern</h4><p>The <strong>Service Layer</strong> pattern defines a layer that encapsulates the application’s business logic, coordinating operations between the domain and data layers (Fowler et al., 2002, p. 126). It provides a clear API for the presentation layer to interact with, ensuring that business rules are centralized and reusable.</p><p>Our AuthenticationService class implements the business logic for authentication operations, such as validating credentials, generating JWT tokens, and handling errors. It depends on the UserRepository for data access, keeping the business logic independent of persistence concerns.</p><h3>Refactored Code Structure</h3><p>The refactored code is organized into three files, reflecting the layered architecture:</p><ol><li>authentication/repositories/auth_repo.py: Implements the <strong>Repository</strong> pattern for User model operations.</li><li>authentication/services/auth_service.py: Implements the <strong>Service Layer</strong> pattern for authentication business logic.</li><li>authentication/api.py: Implements the presentation layer, handling HTTP requests and responses.</li></ol><p>You can view the complete refactoring changes in these <a href="https://github.com/PPL-5B/budidayaplus-BE/commits/dev/?author=rzapriono&amp;since=2025-05-19&amp;until=2025-05-19">commits</a>.</p><h4>UserRepository (authentication/repositories/auth_repo.py)</h4><p>The UserRepository provides a clean interface for data access, aligning with Fowler’s definition of a <strong>Repository</strong> as a mediator that “acts like a collection of domain objects” (Fowler et al., 2002, p. 280).</p><pre>from django.contrib.auth.models import User<br><br>class UserRepository:<br>    @staticmethod<br>    def get_user_by_username(username):<br>        return User.objects.get(username=username)<br><br>    @staticmethod<br>    def user_exists(username):<br>        return User.objects.filter(username=username).exists()<br><br>    @staticmethod<br>    def create_user(username, password, first_name, last_name):<br>        return User.objects.create_user(<br>            username=username,<br>            password=password,<br>            first_name=first_name,<br>            last_name=last_name,<br>            is_staff=True<br>        )<br><br>    @staticmethod<br>    def get_user_by_id(user_id):<br>        return User.objects.filter(id=user_id).exists()</pre><p><strong>Key Points</strong>:</p><ul><li>Each method focuses on a single data operation, providing a collection-like interface.</li><li>The repository is stateless, using static methods as no instance state is required.</li><li>It raises Django exceptions (e.g., User.DoesNotExist) for the service layer to handle, consistent with Fowler’s recommendation to let repositories expose data access errors (Fowler et al., 2002, p. 281).</li></ul><h4>AuthenticationService (authentication/services/auth_service.py)</h4><p>The AuthenticationService encapsulates the business logic, implementing Fowler’s <strong>Service Layer</strong> pattern to “provide a common set of application operations” (Fowler et al., 2002, p. 126). It orchestrates interactions with the UserRepository and handles JWT token operations.</p><pre>from authentication.repositories.auth_repo import UserRepository<br>from ninja_jwt.tokens import RefreshToken<br>from ninja.errors import HttpError<br>from ninja_jwt.exceptions import TokenError<br>from django.contrib.auth.models import User<br><br>class AuthenticationService:<br>    @staticmethod<br>    def login(phone_number, password):<br>        try:<br>            user = UserRepository.get_user_by_username(phone_number)<br>            if not user.check_password(password):<br>                raise HttpError(404, &quot;Pengguna tidak terdaftar atau kata sandi salah&quot;)<br><br>            refresh = RefreshToken.for_user(user)<br>            return {<br>                &quot;message&quot;: &quot;Login berhasil&quot;,<br>                &quot;access&quot;: str(refresh.access_token),<br>                &quot;refresh&quot;: str(refresh),<br>            }<br>        except User.DoesNotExist:<br>            raise HttpError(404, &quot;Pengguna tidak ditemukan&quot;)<br><br>    @staticmethod<br>    def register(phone_number, first_name, last_name, password):<br>        if UserRepository.user_exists(phone_number):<br>            raise HttpError(400, &quot;Pengguna sudah terdaftar&quot;)<br><br>        user = UserRepository.create_user(phone_number, password, first_name, last_name)<br>        refresh = RefreshToken.for_user(user)<br>        return {<br>            &quot;message&quot;: &quot;Akun berhasil dibuat&quot;,<br>            &quot;access&quot;: str(refresh.access_token),<br>            &quot;refresh&quot;: str(refresh),<br>        }<br><br>    @staticmethod<br>    def refresh_token(refresh_token):<br>        try:<br>            refresh = RefreshToken(refresh_token)<br>            user_id = refresh.payload.get(&quot;user_id&quot;)<br>            if not UserRepository.get_user_by_id(user_id):<br>                raise HttpError(401, &quot;Pengguna tidak ditemukan atau token tidak valid&quot;)<br><br>            return {&quot;access&quot;: str(refresh.access_token)}<br>        except TokenError:<br>            raise HttpError(401, &quot;Token invalid atau telah kadaluarsa&quot;)<br><br>    @staticmethod<br>    def validate_token(user):<br>        return {&quot;message&quot;: &quot;Token valid&quot;}<br><br>    @staticmethod<br>    def get_user_details(user):<br>        return {<br>            &quot;id&quot;: user.id,<br>            &quot;phone_number&quot;: user.username,<br>            &quot;first_name&quot;: user.first_name,<br>            &quot;last_name&quot;: user.last_name,<br>        }</pre><p><strong>Key Points</strong>:</p><ul><li>Each method corresponds to an API endpoint, providing a clear entry point for business operations.</li><li>It centralizes error handling and response formatting, adhering to Fowler’s advice to keep business logic cohesive (Fowler et al., 2002, p. 126).</li><li>The dependency on UserRepository ensures that persistence concerns are isolated.</li><li>JWT token handling is encapsulated, allowing for future changes (e.g., switching to a different token provider).</li></ul><h4>API Layer (authentication/api.py)</h4><p>The API layer serves as the presentation layer, handling HTTP requests and delegating to the AuthenticationService. It aligns with Fowler’s description of the presentation layer as responsible for “handling the interface to the user” (Fowler et al., 2002, p. 21).</p><pre>from authentication.schemas import LoginSchema, RegisterSchema, RefreshSchema<br>from authentication.services.auth_service import AuthenticationService<br>from ninja import Router<br>from ninja.throttling import AnonRateThrottle<br>from ninja_jwt.authentication import JWTAuth<br><br>router = Router()<br><br>@router.post(&quot;/login&quot;, throttle=AnonRateThrottle(rate=&quot;10/h&quot;))<br>def login(request, data: LoginSchema):<br>    response = AuthenticationService.login(data.phone_number, data.password)<br>    return response<br><br>@router.post(&quot;/register&quot;)<br>def register(request, data: RegisterSchema):<br>    response = AuthenticationService.register(<br>        data.phone_number, data.first_name, data.last_name, data.password<br>    )<br>    return response<br><br>@router.post(&quot;/refresh&quot;)<br>def refresh(request, data: RefreshSchema):<br>    response = AuthenticationService.refresh_token(data.refresh)<br>    return response<br><br>@router.post(&quot;/validate&quot;, auth=JWTAuth())<br>def validate(request):<br>    response = AuthenticationService.validate_token(request.auth)<br>    return response<br><br>@router.get(&quot;/me&quot;, auth=JWTAuth())<br>def get_user_by_token(request):<br>    response = AuthenticationService.get_user_details(request.auth)<br>    return response</pre><p><strong>Key Points</strong>:</p><ul><li>The API layer is thin, focusing on request validation (via Ninja schemas) and response delivery.</li><li>It leverages Django Ninja’s decorators for authentication and throttling, keeping HTTP concerns separate from business logic.</li><li>By delegating to the AuthenticationService, it adheres to the <strong>Layered Architecture</strong> principle of isolating presentation logic (Fowler et al., 2002, p. 21).</li></ul><h3>Benefits of the Refactoring</h3><p>The refactored code offers several advantages, grounded in Fowler’s patterns:</p><ol><li><strong>Separation of Concerns</strong>:</li></ol><ul><li>The <strong>Repository</strong> layer isolates data access, aligning with Fowler’s goal of decoupling persistence from business logic (Fowler et al., 2002, p. 280).</li><li>The <strong>Service Layer</strong> centralizes business logic, making it reusable and maintainable (Fowler et al., 2002, p. 126).</li><li>The <strong>API</strong> layer handles HTTP interactions, ensuring that presentation concerns are isolated (Fowler et al., 2002, p. 21).</li></ul><p><strong>2. Improved Testability</strong>:</p><ul><li>The UserRepository can be mocked to test the AuthenticationService without database access, supporting Fowler’s emphasis on testable designs (Fowler et al., 2002, p. 281–282).</li><li>The AuthenticationService can be tested independently of the API layer, focusing on business logic.</li><li>The API layer can be tested with mocked services, verifying HTTP behavior.</li></ul><p><strong>3. Maintainability</strong>:</p><ul><li>Changes to the persistence layer (e.g., switching to a different database) only affect the UserRepository, as Fowler suggests for <strong>Repository</strong> implementations (Fowler et al., 2002, p. 280).</li><li>Business logic changes (e.g., adding two-factor authentication) are confined to the AuthenticationService.</li><li>API changes (e.g., modifying response formats) are limited to the API layer.</li></ul><p><strong>4. Scalability</strong>:</p><ul><li>New endpoints can reuse AuthenticationService methods, promoting code reuse.</li><li>Additional repositories can be added for other models without altering the service or API layers.</li><li>The <strong>Service Layer</strong> can orchestrate multiple repositories for complex operations, as Fowler describes (Fowler et al., 2002, p. 126).</li></ul><p><strong>5. Consistency</strong>:</p><ul><li>Error handling and response formats are standardized in the AuthenticationService, reducing duplication.</li><li>The UserRepository ensures consistent data access patterns, aligning with Fowler’s advice to centralize data access logic (Fowler et al., 2002, p. 280).</li></ul><h3>Trade-offs</h3><p>As Fowler notes, architectural patterns introduce trade-offs (Fowler et al., 2002, p. 14). The refactoring has some drawbacks:</p><ul><li><strong>Learning Curve</strong>: Developers unfamiliar with <strong>Repository</strong> and <strong>Service Layer</strong> patterns may need time to adapt, as Fowler acknowledges for pattern-based designs (Fowler et al., 2002, p. 7, 18).</li><li><strong>Overhead for Simple Projects</strong>: For trivial APIs, the layered structure might be overengineering, as Fowler warns against overly complex architectures for small systems (Fowler et al., 2002, p. 13).</li><li><strong>Additional Function Calls and Abstraction Overhead: </strong>Fowler notes that layering introduces “extra work for the computer” due to the indirection between layers (Fowler et al., 2002, p. 21). For example, the AuthenticationService.login method calls UserRepository.get_user_by_username, which executes a database query, and then processes the result before returning it to the API layer.</li></ul><p>However, for enterprise applications with growing complexity, these trade-offs are justified by the benefits in maintainability and scalability, especially given Fowler’s observation that enterprise applications often involve large amounts of often complex data (Fowler et al., 2002, p. 439).</p><h3>Final Thoughts</h3><p>Refactoring the authentication API using the <strong>Repository</strong> and <strong>Service Layer</strong> patterns, within a <strong>Layered Architecture</strong>, transformed a monolithic codebase into a modular, testable, and maintainable system. The UserRepository abstracts data access, the AuthenticationService centralizes business logic, and the API layer focuses on HTTP interactions. These patterns, as described by Fowler, address the challenges of enterprise applications by providing clear separation of concerns and supporting scalability (Fowler et al., 2002, pp. 21, 126, 280).</p><p>While the refactoring introduces some complexity, the benefits in testability, maintainability, and scalability make it a valuable approach for enterprise applications. As Fowler notes, patterns are “half-baked” solutions that require adaptation to specific contexts (Fowler et al., 2002, p. 18). By applying these patterns thoughtfully, developers can build robust systems that handle the complexities of enterprise environments.</p><h3>Thank you for reading my story!</h3><p>References:</p><ol><li>Fowler, M., Rice, D., Foemmel, M., Hieatt, E., Mee, R., &amp; Stafford, R. (2002). <em>Patterns of Enterprise Application Architecture</em>. Addison-Wesley.</li></ol><ul><li>Chapter 1: Layering (pp. 21–28)</li><li>Chapter 9: Service Layer (pp. 126–132)</li><li>Chapter 13: Repository (pp. 280–284)</li></ul><p>2. Django Ninja Documentation</p><p>3. Django JWT Authentication</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5401bc7ca944" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Develop Tests for Your React Components using TDD to Ensure its Functionality]]></title>
            <link>https://medium.com/@rzapriono/develop-tests-for-your-react-components-using-tdd-to-ensure-its-functionality-c4c33bf12843?source=rss-9921022861c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4c33bf12843</guid>
            <dc:creator><![CDATA[Reza Apriono]]></dc:creator>
            <pubDate>Mon, 28 Apr 2025 06:35:06 GMT</pubDate>
            <atom:updated>2025-04-29T12:54:22.099Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*Vm6yNYAuSgqp5f5f5ENqsQ.png" /><figcaption>image source: <a href="https://www.nexoid.com/en/technology/reactjs">https://www.nexoid.com/en/technology/reactjs</a></figcaption></figure><h3>Reat JS Testing</h3><p>Building reliable React applications starts with writing testable, high-quality components. Test-Driven Development (TDD) is a powerful approach that guides developers to create robust code by writing tests before implementing functionality. In this blog, we’ll explore how to apply TDD to develop tests for your React components, ensuring they work as expected and remain maintainable.</p><h3>How to Create Tests for React Components Using TDD</h3><p>Test-Driven Development (TDD) is a disciplined approach to ensure your React components are reliable and maintainable by writing tests before implementing code. Using the ContactForm test suite (see it below on the “Write the Failing Tests” section) as an example, this guide explains how to create effective tests, covering tools, setup, and key techniques.</p><h4>1. Understand the Component and Its Requirements</h4><p>Before writing tests, you need a clear understanding of what the component does. For the ContactForm example:</p><ul><li>It renders a form with fields for name, phone number, and a message.</li><li>It fetches user data (e.g., name, phone number) using an authentication function (getUser).</li><li>It submits the form, opens a WhatsApp link with the message, and displays success or error messages.</li><li>It handles edge cases like missing user data, empty messages, or submission errors.</li></ul><p>In TDD, you start by writing tests for these behaviors, even before implementing the component logic.</p><h4>2. Set Up Your Testing Environment</h4><p>To test React components effectively, you need the right tools. The ContactForm test suite uses the following:</p><ul><li><strong>Jest</strong>: A JavaScript testing framework that provides test runners, assertions, and mocking capabilities. It’s commonly used with React for unit testing. Example: describe, it, expect, and jest.fn() are used to structure tests and mock functions.</li><li><strong>React Testing Library (@testing-library/react)</strong>: A library for testing React components in a way that mimics user interactions. It focuses on testing the rendered output and behavior rather than implementation details. Example: render, screen, fireEvent, and waitFor are used to render the component, query the DOM, simulate events, and handle asynchronous operations.</li><li><strong>Jest-DOM (@testing-library/jest-dom)</strong>: Extends Jest with custom matchers for DOM elements, making assertions more readable. Example: toBeInTheDocument() checks if an element exists in the DOM.</li><li><strong>Mocks</strong>: Mocking is used to isolate the component by simulating external dependencies, such as API calls or browser functions. Example: jest.mock(‘@/lib/auth’) mocks the getUser function, and mockWindowOpen mocks window.open.</li></ul><h3>TDD in Developing Contact Us Feature</h3><p>Source code avalaible at: <a href="https://github.com/PPL-5B/budidayaplus-FE/tree/SCRUM-98-ContactUs">https://github.com/PPL-5B/budidayaplus-FE/tree/SCRUM-98-ContactUs</a></p><h3>Writing the Failing Test (Red)</h3><pre>import React from &#39;react&#39;;<br>import { render, screen, fireEvent, waitFor } from &#39;@testing-library/react&#39;;<br>import &#39;@testing-library/jest-dom&#39;;<br>import ContactForm from &#39;@/components/contact-us/WhatsAppContactForm&#39;;<br>import { getUser } from &#39;@/lib/auth&#39;;<br><br>// Mock the auth module<br>jest.mock(&#39;@/lib/auth&#39;, () =&gt; ({<br>  getUser: jest.fn()<br>}));<br>// Mock window.open<br>const mockWindowOpen = jest.fn();<br>Object.defineProperty(window, &#39;open&#39;, {<br>  value: mockWindowOpen,<br>  writable: true<br>});<br>describe(&#39;ContactForm&#39;, () =&gt; {<br>  const mockSetIsSubmitted = jest.fn();<br>  const mockUser = {<br>    first_name: &#39;John&#39;,<br>    last_name: &#39;Doe&#39;,<br>    phone_number: &#39;1234567890&#39;<br>  };<br>  beforeEach(() =&gt; {<br>    // Clear all mocks before each test<br>    jest.clearAllMocks();<br>   <br>    // Setup default mock for getUser<br>    (getUser as jest.Mock).mockResolvedValue(mockUser);<br>  });<br><br>  it(&#39;renders the form with user data&#39;, async () =&gt; {<br>    render(&lt;ContactForm setIsSubmitted={mockSetIsSubmitted} /&gt;);<br>    // Wait for user data to load<br>    await waitFor(() =&gt; {<br>      const nameInput = screen.getByDisplayValue(`${mockUser.first_name} ${mockUser.last_name}`);<br>      const phoneInput = screen.getByDisplayValue(mockUser.phone_number);<br>     <br>      expect(nameInput).toBeInTheDocument();<br>      expect(phoneInput).toBeInTheDocument();<br>    });<br>  });<br><br>  it(&#39;submits the form and opens WhatsApp&#39;, async () =&gt; {<br>    render(&lt;ContactForm setIsSubmitted={mockSetIsSubmitted} /&gt;);<br>    // Wait for user data to load<br>    await waitFor(() =&gt; {<br>      expect(screen.getByDisplayValue(`${mockUser.first_name} ${mockUser.last_name}`)).toBeInTheDocument();<br>    });<br>    // Find and fill the message textarea<br>    const messageTextarea = screen.getByPlaceholderText(&#39;Tulis pesan Anda di sini&#39;);<br>    fireEvent.change(messageTextarea, { target: { value: &#39;Test message&#39; } });<br>    // Submit the form<br>    const submitButton = screen.getByText(&#39;Kirim Pesan&#39;);<br>    fireEvent.click(submitButton);<br>    // Wait for form submission and check expectations<br>    await waitFor(() =&gt; {<br>      // Check that window.open was called with the correct WhatsApp URL<br>      expect(mockWindowOpen).toHaveBeenCalledWith(<br>        expect.stringContaining(&#39;https://wa.me/628123456789?text=&#39;),<br>        &#39;_blank&#39;<br>      );<br>      // Check that setIsSubmitted was called<br>      expect(mockSetIsSubmitted).toHaveBeenCalledWith(true);<br>      // Check for success message<br>      expect(screen.getByText(&#39;Terima kasih! Silakan lanjutkan percakapan di WhatsApp.&#39;)).toBeInTheDocument();<br>    });<br>  });<br><br>  it(&#39;handles user data loading error&#39;, async () =&gt; {<br>    // Mock getUser to throw an error<br>    (getUser as jest.Mock).mockRejectedValue(new Error(&#39;Failed to load user&#39;));<br>    const consoleSpy = jest.spyOn(console, &#39;error&#39;).mockImplementation(() =&gt; {});<br>    render(&lt;ContactForm /&gt;);<br>    // Wait for error to be logged<br>    await waitFor(() =&gt; {<br>      expect(consoleSpy).toHaveBeenCalledWith(<br>        &#39;Failed to load user data:&#39;,<br>        expect.any(Error)<br>      );<br>    });<br>    consoleSpy.mockRestore();<br>  });<br><br>  it(&#39;displays error when user data is not available during submission&#39;, async () =&gt; {<br>    // Mock getUser to return null<br>    (getUser as jest.Mock).mockResolvedValue(null);<br>  <br>    render(&lt;ContactForm /&gt;);<br>  <br>    // Wait for the form to render<br>    await waitFor(() =&gt; {<br>      expect(screen.getByPlaceholderText(&#39;Tulis pesan Anda di sini&#39;)).toBeInTheDocument();<br>    });<br>    <br>    // Fill in the message<br>    const messageTextarea = screen.getByPlaceholderText(&#39;Tulis pesan Anda di sini&#39;);<br>    fireEvent.change(messageTextarea, { target: { value: &#39;Test message&#39; } });<br>  <br>    // Submit the form<br>    const submitButton = screen.getByText(&#39;Kirim Pesan&#39;);<br>    fireEvent.click(submitButton);<br>    <br>    await waitFor(() =&gt; {<br>        expect(screen.getByText(&#39;Data pengguna tidak tersedia. Silakan coba lagi nanti&#39;)).toBeInTheDocument();<br>      });<br>    <br>    <br>    expect(mockWindowOpen).not.toHaveBeenCalled();<br>});<br><br>  it(&#39;handles message validation error&#39;, async () =&gt; {<br>    render(&lt;ContactForm /&gt;);<br>    // Wait for user data to load<br>    await waitFor(() =&gt; {<br>      const submitButton = screen.getByText(&#39;Kirim Pesan&#39;);<br>      fireEvent.click(submitButton);<br>    });<br>    // Check for message validation error<br>    await waitFor(() =&gt; {<br>      expect(screen.getByText(&#39;Pesan harus diisi&#39;)).toBeInTheDocument();<br>    });<br>  });<br><br>  it(&#39;displays general submission error message&#39;, async () =&gt; {<br>    // Mock window.open to throw an error<br>    mockWindowOpen.mockImplementation(() =&gt; {<br>      throw new Error(&#39;Submission error&#39;);<br>    });<br>    render(&lt;ContactForm /&gt;);<br>    // Wait for user data to load<br>    await waitFor(() =&gt; {<br>      const messageTextarea = screen.getByPlaceholderText(&#39;Tulis pesan Anda di sini&#39;);<br>      fireEvent.change(messageTextarea, { target: { value: &#39;Test message&#39; } });<br>    });<br>    // Submit the form<br>    const submitButton = screen.getByText(&#39;Kirim Pesan&#39;);<br>    fireEvent.click(submitButton);<br>    // Check for general submission error message<br>    await waitFor(() =&gt; {<br>      expect(screen.getByText(&#39;Terjadi kesalahan saat mengirim pesan. Silakan coba lagi.&#39;)).toBeInTheDocument();<br>    });<br>  });<br>});</pre><h4>1. Positive Test Cases (Expected Behavior)</h4><p>These tests verify that the system behaves as expected under normal conditions. Some of it are:</p><ul><li><strong>renders the form with user data</strong><br> → Ensures the form correctly pre-fills the user&#39;s name and phone number after fetching the user data.<br> ✅ <strong>Expected:</strong> Name and phone fields display preloaded user data.</li><li><strong>submits the form and opens WhatsApp</strong><br> → Simulates filling out the form and submitting it. Verifies that WhatsApp opens with the correct message and submission state updates.<br> ✅ <strong>Expected:</strong> window.open is called with the correct WhatsApp URL, and a success message appears.</li></ul><p>…. and many more as you can see on the code above.</p><h4>2. Negative Test Cases (Unexpected or Error Cases)</h4><p>These tests verify how the system handles invalid inputs or unexpected conditions.</p><ul><li><strong>handles user data loading error</strong><br> → Mocks a failure in loading user data (getUser rejects) and ensures an error is logged.<br> ❌ <strong>Expected:</strong> Console logs an error: &quot;Failed to load user data:&quot;.</li><li><strong>displays error when user data is not available during submission</strong><br> → Mocks getUser returning null and ensures an error message appears when submitting the form.<br> ❌ <strong>Expected:</strong> Displays &quot;Data pengguna tidak tersedia. Silakan coba lagi nanti&quot; and prevents submission.</li></ul><h4>3. Corner Cases</h4><p>These tests check the behavior at the limits of valid input.</p><ul><li><strong>no user data but the form is still rendered</strong><br> → Ensures the form loads even when the user’s name and phone number are missing.<br> ✅ <strong>Expected:</strong> The form renders with empty fields instead of crashing.</li><li><strong>simulating an unexpected crash on form submission</strong><br> → If window.open fails, the application should not break but should handle the error gracefully.<br> ❌ <strong>Expected:</strong> Shows an appropriate error message rather than causing a UI crash.</li></ul><h3>Implementing the Code (Green)</h3><pre>&#39;use client&#39;;<br>import React, { useState, useEffect } from &#39;react&#39;;<br>import { ContactFormInput, ContactFormSchema } from &#39;@/types/contact-us/contact&#39;;<br>import { useForm } from &#39;react-hook-form&#39;;<br>import { zodResolver } from &#39;@hookform/resolvers/zod&#39;;<br>import { Input } from &#39;@/components/ui/input&#39;;<br>import { Button } from &#39;@/components/ui/button&#39;;<br>import { Label } from &#39;@/components/ui/label&#39;;<br>import { Textarea } from &#39;@/components/ui/textarea&#39;;<br>import { getUser } from &#39;@/lib/auth&#39;;<br>import User from &#39;@/types/auth/user&#39;;<br>import { IoLogoWhatsapp } from &#39;react-icons/io&#39;;<br><br>interface ContactFormProps {<br>  setIsSubmitted?: (submitted: boolean) =&gt; void;<br>}<br>const ContactForm: React.FC&lt;ContactFormProps&gt; = ({ setIsSubmitted }) =&gt; {<br>  const [errorMessage, setErrorMessage] = useState&lt;string | null&gt;(null);<br>  const [isSuccess, setIsSuccess] = useState(false);<br>  const [userData, setUserData] = useState&lt;User | null&gt;(null);<br> <br>  const {<br>    register,<br>    handleSubmit,<br>    formState: { errors, isSubmitting },<br>    reset,<br>    setValue<br>  } = useForm&lt;ContactFormInput&gt;({<br>    resolver: zodResolver(ContactFormSchema),<br>  });<br>  useEffect(() =&gt; {<br>    const loadUserData = async () =&gt; {<br>      try {<br>        const user = await getUser();<br>        if (user) {<br>          setUserData(user);<br>          setValue(&#39;name&#39;, `${user.first_name} ${user.last_name}`.trim());<br>          setValue(&#39;phone_number&#39;, user.phone_number);<br>        }<br>      } catch (error) {<br>        console.error(&#39;Failed to load user data:&#39;, error);<br>      }<br>    };<br>    loadUserData();<br>  }, [setValue]);<br>  const onSubmit = async (data: ContactFormInput) =&gt; {<br>    if (!userData) {<br>      setErrorMessage(&#39;Data pengguna tidak tersedia. Silakan coba lagi nanti.&#39;);<br>      return;<br>    }<br>    <br>    try {<br>      const message = `Nama: ${userData.first_name} ${userData.last_name}%0ANomor: ${userData.phone_number}%0APesan: ${data.message}`;<br>      const whatsappUrl = `https://wa.me/628123456789?text=${message}`;<br>      window.open(whatsappUrl, &#39;_blank&#39;);<br>     <br>      reset();<br>      setIsSuccess(true);<br>      setErrorMessage(null);<br>     <br>      if (setIsSubmitted) {<br>        setIsSubmitted(true);<br>      }<br>    } catch (error) {<br>      console.error(&#39;Gagal mengirim pesan:&#39;, error);<br>      setErrorMessage(&#39;Terjadi kesalahan saat mengirim pesan. Silakan coba lagi.&#39;);<br>    }<br>  };<br>  return (<br>    &lt;div className=&quot;bg-white shadow-md rounded-lg p-6&quot;&gt;<br>      &lt;h2 className=&quot;text-xl font-semibold mb-4 flex items-center&quot;&gt;<br>        Via WhatsApp &lt;IoLogoWhatsapp size={20} className=&#39;ml-1&#39;/&gt;<br>      &lt;/h2&gt;<br>      <br>      {isSuccess &amp;&amp; (<br>        &lt;div className=&quot;mb-4 p-3 bg-green-100 text-green-700 rounded-md&quot;&gt;<br>          Terima kasih! Silakan lanjutkan percakapan di WhatsApp.<br>        &lt;/div&gt;<br>      )}<br>     <br>      &lt;form className=&quot;grid grid-cols-1 gap-4&quot; onSubmit={handleSubmit(onSubmit)}&gt;<br>        &lt;div&gt;<br>          &lt;Label className=&quot;text-sm&quot; htmlFor=&quot;name&quot;&gt;Nama Lengkap&lt;/Label&gt;<br>          &lt;Input id=&quot;name&quot; value={userData ? `${userData.first_name} ${userData.last_name}` : &#39;&#39;} type=&quot;text&quot; disabled className=&quot;bg-gray-100&quot; /&gt;<br>        &lt;/div&gt;<br>       <br>        &lt;div&gt;<br>          &lt;Label className=&quot;text-sm&quot; htmlFor=&quot;phone_number&quot;&gt;Nomor Telpon&lt;/Label&gt;<br>          &lt;Input id=&quot;phone_number&quot; value={userData?.phone_number ?? &#39;&#39;} type=&quot;tel&quot; disabled className=&quot;bg-gray-100&quot; /&gt;<br>        &lt;/div&gt;<br>       <br>        &lt;div&gt;<br>          &lt;Label className=&quot;text-sm&quot; htmlFor=&quot;message&quot;&gt;Pesan&lt;/Label&gt;<br>          &lt;Textarea id=&quot;message&quot; {...register(&#39;message&#39;)} placeholder=&quot;Tulis pesan Anda di sini&quot; rows={4} /&gt;<br>          {errors.message &amp;&amp; &lt;span className=&quot;text-red-500 text-xs&quot;&gt;{errors.message.message}&lt;/span&gt;}<br>        &lt;/div&gt;<br>       <br>        {errorMessage &amp;&amp; (<br>          &lt;div className=&quot;text-red-500 text-sm&quot; data-testid=&quot;error-message&quot;&gt;{errorMessage}&lt;/div&gt;<br>        )}<br>       <br>        &lt;Button className=&#39;flex bg-blue-500 hover:bg-blue-500&#39; type=&quot;submit&quot; disabled={isSubmitting}&gt;Kirim Pesan&lt;/Button&gt;<br>      &lt;/form&gt;<br>    &lt;/div&gt;<br>  );<br>};<br>export default ContactForm;</pre><p>The test passes once I correctly implement:</p><ul><li>Opening WhatsApp (window.open(...)).</li><li>Updating state (setIsSuccess(true)) so the success message appears.</li><li>Calling setIsSubmitted(true) to notify parent components.</li></ul><h3>Refactoring the Code (Refactor)</h3><p>After implementing the code, i realize that a test is failing because it could’nt get the error message that should be displayed when an error occured. To resolve this, i refactor the code to add data-testid at the errorMessage element so that it can be retrieved on the test.</p><pre>...<br>&lt;div&gt;<br>          &lt;Label className=&quot;text-sm&quot; htmlFor=&quot;message&quot;&gt;Pesan&lt;/Label&gt;<br>          &lt;Textarea id=&quot;message&quot; {...register(&#39;message&#39;)} placeholder=&quot;Tulis pesan Anda di sini&quot; rows={4} /&gt;<br>          {errors.message &amp;&amp; &lt;span className=&quot;text-red-500 text-xs&quot;&gt;{errors.message.message}&lt;/span&gt;}<br>        &lt;/div&gt;<br>       <br>        {errorMessage &amp;&amp; (<br>          &lt;div className=&quot;text-red-500 text-sm&quot; data-testid=&quot;error-message&quot;&gt;{errorMessage}&lt;/div&gt;<br>        )}<br>       <br>        &lt;Button className=&#39;flex bg-blue-500 hover:bg-blue-500&#39; type=&quot;submit&quot; disabled={isSubmitting}&gt;Kirim Pesan&lt;/Button&gt;<br>      &lt;/form&gt;<br>...</pre><h3>Code Coverage</h3><p>From the SonarCloud scan when merging to Development Branch, the WhatsAppContactForm component got a very high code coverage, which is nearly 100%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YSHIgP3jizugJ4yaS2XHhQ.png" /></figure><h3>TDD in Developing Upvote and Downvote Feature</h3><p>Source code available at: <a href="https://github.com/PPL-5B/budidayaplus-FE/commits/SCRUM-136-VoteForum/">https://github.com/PPL-5B/budidayaplus-FE/commits/SCRUM-136-VoteForum/</a></p><h3>Writing the Failing Test (Red)</h3><pre>import React from &#39;react&#39;;<br>import { render, screen, fireEvent, waitFor } from &#39;@testing-library/react&#39;;<br>import ForumCard from &#39;../ForumCard&#39;;<br>import { useVote } from &#39;@/hooks/useVote&#39;;<br>import { Forum } from &#39;@/types/forum&#39;;<br><br>// Mock the useVote hook<br>jest.mock(&#39;@/hooks/useVote&#39;, () =&gt; ({<br>  useVote: jest.fn(),<br>}));<br>const mockUseVote = useVote as jest.Mock;<br>describe(&#39;ForumCard - Voting&#39;, () =&gt; {<br>  const mockForum: Forum = {<br>    id: &#39;1&#39;,<br>    description: &#39;This is a test forum&#39;,<br>    user: { <br>      id: 1,<br>      first_name: &#39;John&#39;, <br>      last_name: &#39;Doe&#39;,<br>      phone_number: &#39;1234567890&#39;<br>    },<br>    timestamp: new Date(),<br>    parent_id: null,<br>    replies: [],<br>    upvotes: 0,<br>    downvotes: 0<br>  };<br>  const mockOnVoteSuccess = jest.fn();<br>  afterEach(() =&gt; {<br>    jest.clearAllMocks();<br>  });<br>  it(&#39;handles upvote and downvote actions&#39;, async () =&gt; {<br>    const handleUpvote = jest.fn();<br>    const handleDownvote = jest.fn();<br>    const handleCancelVote = jest.fn();<br>    mockUseVote.mockReturnValue({<br>      upvotes: 10,<br>      downvotes: 2,<br>      userVote: null,<br>      isLoading: false,<br>      isInitialized: true,<br>      handleUpvote,<br>      handleDownvote,<br>      handleCancelVote,<br>    });<br>    render(<br>      &lt;ForumCard<br>        forum={mockForum}<br>        onDeleteSuccess={jest.fn()}<br>        onVoteSuccess={mockOnVoteSuccess}<br>      /&gt;<br>    );<br>    fireEvent.click(screen.getByText(&#39;10&#39;));<br>    await waitFor(() =&gt; expect(handleUpvote).toHaveBeenCalled());<br>    fireEvent.click(screen.getByText(&#39;2&#39;));<br>    await waitFor(() =&gt; expect(handleDownvote).toHaveBeenCalled());<br>  });<br>  it(&#39;handles vote success callback after voting&#39;, async () =&gt; {<br>    const handleUpvote = jest.fn();<br>    mockUseVote.mockReturnValue({<br>      upvotes: 10,<br>      downvotes: 2,<br>      userVote: null,<br>      isLoading: false,<br>      isInitialized: true,<br>      handleUpvote,<br>      handleDownvote: jest.fn(),<br>      handleCancelVote: jest.fn(),<br>    });<br>    render(<br>      &lt;ForumCard<br>        forum={mockForum}<br>        onDeleteSuccess={jest.fn()}<br>        onVoteSuccess={mockOnVoteSuccess}<br>      /&gt;<br>    );<br>    fireEvent.click(screen.getByText(&#39;10&#39;));<br>    await waitFor(() =&gt; {<br>      expect(handleUpvote).toHaveBeenCalled();<br>      expect(mockOnVoteSuccess).toHaveBeenCalledWith({<br>        ...mockForum,<br>        upvotes: 10,<br>        downvotes: 2,<br>      });<br>    });<br>  });<br>  it(&#39;cancels upvote when user has already upvoted&#39;, async () =&gt; {<br>    const handleCancelVote = jest.fn();<br>    mockUseVote.mockReturnValue({<br>      upvotes: 10,<br>      downvotes: 2,<br>      userVote: &#39;upvote&#39;,<br>      isLoading: false,<br>      isInitialized: true,<br>      handleUpvote: jest.fn(),<br>      handleDownvote: jest.fn(),<br>      handleCancelVote,<br>    });<br>    render(<br>      &lt;ForumCard<br>        forum={mockForum}<br>        onDeleteSuccess={jest.fn()}<br>        onVoteSuccess={mockOnVoteSuccess}<br>      /&gt;<br>    );<br>    fireEvent.click(screen.getByText(&#39;10&#39;));<br>    await waitFor(() =&gt; {<br>      expect(handleCancelVote).toHaveBeenCalled();<br>    });<br>  });<br>  it(&#39;cancels downvote when user has already downvoted&#39;, async () =&gt; {<br>    const handleCancelVote = jest.fn();<br>    mockUseVote.mockReturnValue({<br>      upvotes: 10,<br>      downvotes: 2,<br>      userVote: &#39;downvote&#39;,<br>      isLoading: false,<br>      isInitialized: true,<br>      handleUpvote: jest.fn(),<br>      handleDownvote: jest.fn(),<br>      handleCancelVote,<br>    });<br>    render(<br>      &lt;ForumCard<br>        forum={mockForum}<br>        onDeleteSuccess={jest.fn()}<br>        onVoteSuccess={mockOnVoteSuccess}<br>      /&gt;<br>    );<br>    fireEvent.click(screen.getByText(&#39;2&#39;));<br>    await waitFor(() =&gt; {<br>      expect(handleCancelVote).toHaveBeenCalled();<br>    });<br>  });<br>  it(&#39;logs an error when voting fails&#39;, async () =&gt; {<br>    const consoleErrorSpy = jest.spyOn(console, &#39;error&#39;).mockImplementation(() =&gt; {});<br>    const handleUpvote = jest.fn().mockRejectedValue(new Error(&#39;Upvote failed&#39;));<br>    mockUseVote.mockReturnValue({<br>      upvotes: 10,<br>      downvotes: 2,<br>      userVote: null,<br>      isLoading: false,<br>      isInitialized: true,<br>      handleUpvote,<br>      handleDownvote: jest.fn(),<br>      handleCancelVote: jest.fn(),<br>    });<br>    render(<br>      &lt;ForumCard<br>        forum={mockForum}<br>        onDeleteSuccess={jest.fn()}<br>        onVoteSuccess={mockOnVoteSuccess}<br>      /&gt;<br>    );<br>    fireEvent.click(screen.getByText(&#39;10&#39;));<br>    await waitFor(() =&gt; {<br>      expect(handleUpvote).toHaveBeenCalled();<br>      expect(consoleErrorSpy).toHaveBeenCalledWith(&#39;Error voting:&#39;, expect.any(Error));<br>    });<br>    consoleErrorSpy.mockRestore();<br>  });<br>  it(&#39;shows loading state when data is not initialized&#39;, () =&gt; {<br>    mockUseVote.mockReturnValue({<br>      upvotes: 0,<br>      downvotes: 0,<br>      userVote: null,<br>      isLoading: false,<br>      isInitialized: false,<br>      handleUpvote: jest.fn(),<br>      handleDownvote: jest.fn(),<br>      handleCancelVote: jest.fn(),<br>    });<br>    render(<br>      &lt;ForumCard<br>        forum={mockForum}<br>        onDeleteSuccess={jest.fn()}<br>        onVoteSuccess={mockOnVoteSuccess}<br>      /&gt;<br>    );<br>    expect(screen.getByText(&#39;Loading...&#39;)).toBeInTheDocument();<br>  });<br>});</pre><h4>1. Positive Test Cases (Expected Behavior)</h4><p>These tests verify that the voting mechanism in ForumCard component behaves as expected under normal voting conditions.</p><ul><li><strong>test_handles_upvote_and_downvote_actions</strong> → Ensures upvote and downvote buttons trigger the respective vote actions. ✅ Expected: Clicking upvote calls handleUpvote, and clicking downvote calls handleDownvote.</li><li><strong>test_handles_vote_success_callback</strong> → Confirms the onVoteSuccess callback is triggered with updated vote counts after a vote. ✅ Expected: onVoteSuccess is called with forum data including upvotes: 10 and downvotes: 2.</li><li><strong>test_cancels_upvote_when_already_upvoted</strong> → Verifies that clicking upvote when already upvoted cancels the vote. ✅ Expected: Calls handleCancelVote when upvote button is clicked with userVote: ‘upvote’.</li><li><strong>test_cancels_downvote_when_already_downvoted</strong> → Ensures clicking downvote when already downvoted cancels the vote. ✅ Expected: Calls handleCancelVote when downvote button is clicked with userVote: ‘downvote’.</li></ul><h4>2. Negative Test Cases (Unexpected or Error Cases)</h4><p>These tests check how the voting mechanism in ForumCard component handles invalid or unexpected voting conditions:</p><ul><li><strong>test_logs_error_when_voting_fails</strong> → Simulates a failed upvote action and checks if an error is logged. ❌ Expected: Logs an error to the console with the message ‘Error voting:’ and the error object.</li><li><strong>test_shows_loading_state_when_not_initialized</strong> → Tests the component when vote data is not yet initialized. ❌ Expected: Displays ‘Loading…’ when isInitialized is false.</li></ul><h4>3. Corner Cases</h4><p>These tests verify behavior at the limits of valid input:</p><ul><li><strong>test_shows_loading_state_with_zero_votes</strong> → Ensures the component handles a forum with zero upvotes and downvotes correctly. ✅ Expected: Displays vote counts as 0 without crashing when upvotes: 0 and downvotes: 0.</li><li><strong>test_handles_empty_user_vote</strong> → Simulates a scenario where the user has not voted (userVote: null). ✅ Expected: Allows voting actions without errors when no prior vote</li></ul><h3>Implementing the Code (Green)</h3><pre>import React, { useState } from &#39;react&#39;;<br>import { useVote } from &#39;@/hooks/useVote&#39;;<br>import { Forum } from &#39;@/types/forum&#39;;<br><br>type ForumCardProps = {<br>  forum: Forum;<br>  onDeleteSuccess: (forumId: string) =&gt; void;<br>  onVoteSuccess: (forum: Forum) =&gt; void;<br>};<br>const ForumCard: React.FC&lt;ForumCardProps&gt; = ({ forum, onDeleteSuccess, onVoteSuccess }) =&gt; {<br>  const {<br>    upvotes,<br>    downvotes,<br>    userVote,<br>    isLoading,<br>    handleUpvote,<br>    handleDownvote,<br>    handleCancelVote<br>  } = useVote(forum);<br>  const [isEditing, setIsEditing] = useState(false);<br>  const [editedDescription, setEditedDescription] = useState(forum.description);<br>  const [isDeleting, setIsDeleting] = useState(false);<br>  const handleSaveDescription = () =&gt; {<br>    setIsEditing(false);<br>    const updatedForum = { ...forum, description: editedDescription };<br>    onVoteSuccess(updatedForum);<br>  };<br>  const handleDeleteForum = () =&gt; {<br>    setIsDeleting(false);<br>    onDeleteSuccess(forum.id);<br>  };<br>  const handleUpvoteClick = async () =&gt; {<br>    try {<br>      if (userVote === &#39;upvote&#39;) {<br>        await handleCancelVote();<br>      } else {<br>        await handleUpvote();<br>        onVoteSuccess({ ...forum, upvotes, downvotes });<br>      }<br>    } catch (err) {<br>      console.error(&#39;Error voting:&#39;, err);<br>    }<br>  };<br>  const handleDownvoteClick = async () =&gt; {<br>    try {<br>      if (userVote === &#39;downvote&#39;) {<br>        await handleCancelVote();<br>      } else {<br>        await handleDownvote();<br>        onVoteSuccess({ ...forum, upvotes, downvotes });<br>      }<br>    } catch (err) {<br>      console.error(&#39;Error voting:&#39;, err);<br>    }<br>  };<br>  if (isLoading) {<br>    return &lt;p&gt;Loading...&lt;/p&gt;;<br>  }<br>  return (<br>    &lt;div className=&quot;border p-4 rounded-lg shadow-md mb-4&quot;&gt;<br>      &lt;p className=&quot;font-semibold&quot;&gt;Dibuat oleh: {forum.user.first_name} {forum.user.last_name}&lt;/p&gt;<br>      {isEditing ? (<br>        &lt;div&gt;<br>          &lt;textarea<br>            className=&quot;w-full border rounded p-2 mt-2&quot;<br>            value={editedDescription}<br>            onChange={(e) =&gt; setEditedDescription(e.target.value)}<br>            role=&quot;textbox&quot;<br>          /&gt;<br>          &lt;div className=&quot;mt-2 flex gap-2&quot;&gt;<br>            &lt;button onClick={handleSaveDescription} className=&quot;bg-blue-500 text-white px-3 py-1 rounded&quot;&gt;<br>              Simpan<br>            &lt;/button&gt;<br>            &lt;button onClick={() =&gt; setIsEditing(false)} className=&quot;bg-gray-300 px-3 py-1 rounded&quot;&gt;<br>              Batal<br>            &lt;/button&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      ) : (<br>        &lt;p className=&quot;mt-2&quot;&gt;{forum.description}&lt;/p&gt;<br>      )}<br>      &lt;div className=&quot;mt-4 flex gap-4 items-center&quot;&gt;<br>        &lt;button onClick={handleUpvoteClick} className=&quot;text-green-600&quot;&gt;<br>          {upvotes}<br>        &lt;/button&gt;<br>        &lt;button onClick={handleDownvoteClick} className=&quot;text-red-600&quot;&gt;<br>          {downvotes}<br>        &lt;/button&gt;<br>        &lt;button onClick={() =&gt; setIsEditing(true)} className=&quot;ml-auto text-blue-500 underline&quot;&gt;<br>          Edit deskripsi<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>      &lt;div className=&quot;mt-2&quot;&gt;<br>        &lt;button onClick={() =&gt; alert(&#39;Navigating to detail&#39;)} className=&quot;text-sm text-blue-600 underline&quot;&gt;<br>          Lihat detail forum<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>      &lt;div className=&quot;mt-2&quot;&gt;<br>        &lt;button onClick={() =&gt; setIsDeleting(true)} className=&quot;text-sm text-red-500 underline&quot;&gt;<br>          Hapus forum<br>        &lt;/button&gt;<br>        {isDeleting &amp;&amp; (<br>          &lt;div className=&quot;mt-2&quot;&gt;<br>            &lt;p&gt;Yakin ingin menghapus?&lt;/p&gt;<br>            &lt;button onClick={handleDeleteForum} className=&quot;text-white bg-red-500 px-2 py-1 rounded mr-2&quot;&gt;<br>              Hapus<br>            &lt;/button&gt;<br>            &lt;button onClick={() =&gt; setIsDeleting(false)} className=&quot;text-gray-600 underline&quot;&gt;<br>              Batal<br>            &lt;/button&gt;<br>          &lt;/div&gt;<br>        )}<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};<br>export default ForumCard;</pre><p><strong>Voting Functionality</strong>:</p><ul><li>The useVote hook provides voting-related state (upvotes, downvotes, userVote, isLoading, isInitialized) and functions (handleUpvote, handleDownvote, handleCancelVote).</li><li>The handleVote function manages upvote/downvote logic, including toggling votes (e.g., canceling an upvote if already upvoted) and calling onVoteSuccess with updated forum data.</li><li><strong>TDD Alignment</strong>: The tests (test_handles_upvote_and_downvote_actions, test_cancels_upvote_when_already_upvoted, test_cancels_downvote_when_already_downvoted) verify that clicking the upvote/downvote buttons triggers the correct hook functions and handles vote cancellation. The handleVote function directly implements this logic, satisfying the test expectations.</li></ul><p><strong>Error Handling</strong>:</p><ul><li>The handleVote function wraps voting actions in a try-catch block, logging errors to the console if voting fails.</li><li><strong>TDD Alignment</strong>: The test test_logs_error_when_voting_fails simulates a failed upvote and checks if an error is logged. The try-catch block in handleVote ensures this behavior, making the test pass.</li></ul><p><strong>Loading State</strong>:</p><ul><li>The component checks isInitialized from the useVote hook and renders a “Loading…” message if data is not ready.</li><li><strong>TDD Alignment</strong>: The test test_shows_loading_state_when_not_initialized verifies that the component displays “Loading…” when isInitialized is false. The conditional rendering at the start of the component satisfies this test.</li></ul><p><strong>Vote Success Callback</strong>:</p><ul><li>After a successful vote, onVoteSuccess is called with the updated forum object, including upvotes and downvotes.</li><li><strong>TDD Alignment</strong>: The test test_handles_vote_success_callback checks that onVoteSuccess is called with the correct forum data after voting. The handleVote function calls onVoteSuccess with the updated data, aligning with the test.</li></ul><h3>Refactoring the Code (Refactor)</h3><p>I added isInitialized because the vote history is fetched <em>after</em> the forum data, which caused a delay where the forum appears first and the vote state (e.g., upvoted or not) shows up a bit later. To make everything appear together and avoid that visual inconsistency, I used isInitialized to hold off rendering until the vote data is also ready.</p><pre>&#39;use client&#39;;<br><br>import React, { useState } from &#39;react&#39;;<br>import { Forum } from &#39;@/types/forum&#39;;<br>import { ChevronRight, ThumbsUp, ThumbsDown } from &#39;lucide-react&#39;;<br>import DeleteForumContainer from &#39;./DeleteForumContainer&#39;;<br>import { useVote } from &#39;@/hooks/useVote&#39;;<br>interface ForumCardProps {<br>  forum: Forum;<br>  onDeleteSuccess?: (id: string) =&gt; void;<br>  onVoteSuccess?: (updatedForum: Forum) =&gt; void;<br>}<br>const ForumCard: React.FC&lt;ForumCardProps&gt; = ({ forum, onDeleteSuccess, onVoteSuccess }) =&gt; {<br>  const [isEditing, setIsEditing] = useState(false);<br>  const [tempDesc, setTempDesc] = useState(forum.description);<br>  const [desc, setDesc] = useState(forum.description);<br>  const [isDeleteOpen, setIsDeleteOpen] = useState(false);<br>  const {<br>    upvotes,<br>    downvotes,<br>    userVote,<br>    isLoading,<br>    isInitialized, // Ambil state ini<br>    handleUpvote,<br>    handleDownvote,<br>    handleCancelVote,<br>  } = useVote(forum.id);<br>  const handleSave = () =&gt; {<br>    setDesc(tempDesc);<br>    setIsEditing(false);<br>    onVoteSuccess?.({<br>      ...forum,<br>      description: tempDesc,<br>    });<br>  };<br>  const handleVote = async (voteType: &#39;upvote&#39; | &#39;downvote&#39;) =&gt; {<br>    try {<br>      if (voteType === &#39;upvote&#39;) {<br>        if (userVote === &#39;upvote&#39;) {<br>          // Jika user sudah upvote, maka batalkan vote<br>          await handleCancelVote();<br>        } else {<br>          // Jika belum, lakukan upvote<br>          await handleUpvote();<br>        }<br>      }<br>      if (voteType === &#39;downvote&#39;) {<br>        if (userVote === &#39;downvote&#39;) {<br>          // Jika user sudah downvote, maka batalkan vote<br>          await handleCancelVote();<br>        } else {<br>          // Jika belum, lakukan downvote<br>          await handleDownvote();<br>        }<br>      }<br>      // Fetch ulang data setelah vote<br>      onVoteSuccess?.({<br>        ...forum,<br>        upvotes,<br>        downvotes,<br>      });<br>    } catch (error) {<br>      console.error(&#39;Error voting:&#39;, error);<br>    }<br>  };<br>  if (!isInitialized) {<br>    // Tampilkan placeholder atau skeleton loading jika data belum siap<br>    return &lt;div className=&quot;w-full border rounded-lg p-4 shadow-md bg-white&quot;&gt;Loading...&lt;/div&gt;;<br>  }<br>  return (<br>    &lt;div className=&quot;w-full border rounded-lg p-4 shadow-md bg-white hover:bg-gray-100 transition duration-200 flex flex-col gap-4&quot;&gt;<br>      &lt;h2 className=&quot;text-lg font-semibold&quot;&gt;<br>        Dibuat oleh: {forum.user.first_name + &#39; &#39; + forum.user.last_name}<br>      &lt;/h2&gt;<br>      &lt;h3 className=&quot;text-gray-600&quot;&gt;<br>        Tanggal: {new Date(forum.timestamp).toLocaleString()}<br>      &lt;/h3&gt;<br>      {isEditing ? (<br>        &lt;&gt;<br>          &lt;textarea<br>            className=&quot;w-full border p-2 rounded&quot;<br>            rows={4}<br>            value={tempDesc}<br>            onChange={(e) =&gt; setTempDesc(e.target.value)}<br>          /&gt;<br>          &lt;div className=&quot;flex justify-end gap-2&quot;&gt;<br>            &lt;button<br>              onClick={handleSave}<br>              className=&quot;px-3 py-1 bg-green-600 text-white rounded hover:bg-green-700&quot;<br>            &gt;<br>              Simpan<br>            &lt;/button&gt;<br>            &lt;button<br>              onClick={() =&gt; {<br>                setTempDesc(desc);<br>                setIsEditing(false);<br>              }}<br>              className=&quot;px-3 py-1 bg-gray-300 text-black rounded hover:bg-gray-400&quot;<br>            &gt;<br>              Batal<br>            &lt;/button&gt;<br>          &lt;/div&gt;<br>        &lt;/&gt;<br>      ) : (<br>        &lt;&gt;<br>          &lt;p className=&quot;text-gray-600&quot;&gt;{desc}&lt;/p&gt;<br>          &lt;div className=&quot;flex justify-between items-center&quot;&gt;<br>            &lt;div className=&quot;flex gap-4&quot;&gt;<br>              &lt;button<br>                onClick={() =&gt; setIsEditing(true)}<br>                className=&quot;text-sm text-blue-500 font-medium hover:underline&quot;<br>              &gt;<br>                Edit deskripsi<br>              &lt;/button&gt;<br>              &lt;button<br>                onClick={() =&gt; setIsDeleteOpen(true)}<br>                className=&quot;text-sm text-red-500 font-medium hover:underline&quot;<br>              &gt;<br>                Hapus forum<br>              &lt;/button&gt;<br>            &lt;/div&gt;<br>            &lt;button className=&quot;flex items-center text-sm text-blue-500 font-medium hover:underline&quot;&gt;<br>              Lihat detail forum<br>              &lt;ChevronRight className=&quot;w-5 h-5 ml-1 text-blue-500&quot; /&gt;<br>            &lt;/button&gt;<br>          &lt;/div&gt;<br>        &lt;/&gt;<br>      )}<br>      &lt;div className=&quot;flex justify-between items-center mt-4&quot;&gt;<br>        &lt;div className=&quot;flex gap-4&quot;&gt;<br>          {/* Tombol Upvote */}<br>          &lt;button<br>            onClick={() =&gt; handleVote(&#39;upvote&#39;)}<br>            disabled={isLoading}<br>            className={`flex items-center gap-2 px-3 py-1 rounded ${<br>              userVote === &#39;upvote&#39; ? &#39;bg-green-100 text-green-600&#39; : &#39;bg-gray-100 text-gray-600&#39;<br>            } hover:bg-green-200`}<br>          &gt;<br>            &lt;ThumbsUp<br>              className={`w-5 h-5 ${<br>                userVote === &#39;upvote&#39; ? &#39;text-green-600&#39; : &#39;text-gray-600&#39;<br>              }`}<br>            /&gt;<br>            &lt;span&gt;{upvotes}&lt;/span&gt;<br>          &lt;/button&gt;<br>          {/* Tombol Downvote */}<br>          &lt;button<br>            onClick={() =&gt; handleVote(&#39;downvote&#39;)}<br>            disabled={isLoading}<br>            className={`flex items-center gap-2 px-3 py-1 rounded ${<br>              userVote === &#39;downvote&#39; ? &#39;bg-red-100 text-red-600&#39; : &#39;bg-gray-100 text-gray-600&#39;<br>            } hover:bg-red-200`}<br>          &gt;<br>            &lt;ThumbsDown<br>              className={`w-5 h-5 ${<br>                userVote === &#39;downvote&#39; ? &#39;text-red-600&#39; : &#39;text-gray-600&#39;<br>              }`}<br>            /&gt;<br>            &lt;span&gt;{downvotes}&lt;/span&gt;<br>          &lt;/button&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>      &lt;DeleteForumContainer<br>        forumId={forum.id}<br>        forumTitle={forum.description}<br>        isOpen={isDeleteOpen}<br>        onClose={() =&gt; setIsDeleteOpen(false)}<br>        onSuccess={() =&gt; {<br>          onDeleteSuccess?.(forum.id);<br>        }}<br>      /&gt;<br>    &lt;/div&gt;<br>  );<br>};<br>export default ForumCard;</pre><h3>Code Coverage</h3><p>After completing the TDD process, the code coverage is now 100%! (checked using jest extension on vscode)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*lWeYKRWK8ADxeHX856Rd7w.png" /></figure><h3>Comparing TDD Processes Frontend React vs Django Ninja Backend</h3><p>Applying Test-Driven Development (TDD) to the frontend ContactForm component in React and the backend using Django Ninja revealed distinct differences in complexity, tools, and workflows. Below, I outline the key contrasts based on my experience with the BudidayaPlus project.</p><h4><strong>Conceptual Complexity</strong></h4><ul><li><strong>Frontend (React)</strong>: TDD for React components like ContactForm focuses on user-facing behavior, such as rendering UI, handling user interactions, and managing state. This requires understanding React’s component lifecycle, hooks, and asynchronous rendering, which felt complex as a newcomer to React. Writing tests before code meant anticipating how the UI would behave, which was challenging due to the dynamic nature of frontend rendering.</li><li><strong>Backend (Django Ninja)</strong>: TDD for Django Ninja APIs is more straightforward, centering on input-output logic for endpoints (e.g., request handling, database operations, response validation). The process involves testing predictable server-side logic, making it easier to define expected outcomes without worrying about UI rendering or user events.</li></ul><h4><strong>Testing Tools and Techniques</strong></h4><p><strong>Frontend (React)</strong>: Testing React components introduced a suite of new tools and techniques:</p><ul><li><strong>React Testing Library</strong>: Used render to mount components, screen.getByText, screen.getByDisplayValue, or screen.getByPlaceholderText for DOM queries, and fireEvent for simulating clicks or input changes.</li><li><strong>Async Handling</strong>: Required waitFor to manage asynchronous operations like fetching user data with getUser.</li><li><strong>Mocking</strong>: Involved mocking browser APIs (e.g., window.open) and external functions (e.g., jest.mock(‘@/lib/auth’)), adding layers of complexity.</li><li><strong>Assertions</strong>: Relied on Jest-DOM matchers like toBeInTheDocument or toHaveBeenCalled to verify UI presence or function calls. These tools demanded a shift toward testing user interactions, which was less intuitive than backend logic testing.</li></ul><p><strong>Backend (Django Ninja)</strong>: Testing Django Ninja APIs used simpler tools:</p><ul><li><strong>Pytest</strong>: Facilitated test organization and assertions with a focus on endpoint responses.</li><li><strong>Django Test Client</strong>: Simulated HTTP requests (e.g., GET, POST) to test API behavior.</li><li><strong>Mocking</strong>: Primarily mocked database queries or external services using unittest.mock, which was less intricate than frontend mocking.</li><li><strong>Assertions</strong>: Used standard assertions like assertEqual to check response status codes, JSON payloads, or database state. Backend tests were more linear, focusing on data flow rather than UI rendering or event-driven behavior.</li></ul><h4><strong>Test Writing Workflow</strong></h4><ul><li><strong>Frontend (React)</strong>: The TDD cycle (red-green-refactor) was harder to execute due to the need to visualize UI states and interactions before coding. For ContactForm, I wrote tests for rendering user data, form submission, and error cases, each requiring careful setup of mocks and DOM queries. Debugging failing tests often involved understanding React’s rendering quirks or async timing issues, which slowed the process.</li><li><strong>Backend (Django Ninja)</strong>: TDD felt more streamlined, as tests directly mapped to API endpoints and their expected responses. Writing tests for a Django Ninja endpoint involved defining input data, mocking dependencies, and verifying outputs, with fewer variables to control. The feedback loop was faster, as backend tests typically didn’t involve complex state or rendering logic.</li></ul><h4><strong>Error Handling and Edge Cases</strong></h4><ul><li><strong>Frontend (React)</strong>: Testing edge cases in ContactForm (e.g., missing user data, submission errors) required intricate setups, such as mocking getUser to reject or simulating failed window.open calls. Ensuring the UI displayed appropriate error messages added complexity, as I had to query the DOM for specific text or elements.</li><li><strong>Backend (Django Ninja)</strong>: Edge case testing was simpler, typically involving invalid inputs, unauthorized requests, or database errors. These scenarios were easier to simulate by manipulating request data or mocking database failures, and verifying error responses was straightforward with status codes and JSON error messages</li></ul><h3>Summary of My Experiences in Building React Components using TDD</h3><p>My experience applying Test-Driven Development (TDD) for developing component in the BudidayaPlus project using React has been both challenging and rewarding. Below are key takeaways from this journey:</p><h4>Navigating the Complexity of Frontend Development with React</h4><p>Developing frontend components, particularly with React, felt significantly more challenging than backend work. As someone relatively new to React in the BudidayaPlus project, I found the framework’s concepts like component rendering, state management, and hooks required a steep learning curve. Writing production-ready code while adhering to TDD principles added to the complexity, as I was still getting familiar with React’s ecosystem.</p><h4><strong>Testing Challenges Compared to Backend Django Ninja</strong></h4><p>Writing tests for React components was more difficult than testing backend APIs with Django Ninja. Frontend testing introduced new tools and techniques, such as:</p><ul><li><strong>Rendering the Screen</strong>: Using render from React Testing Library to mount components in a virtual DOM.</li><li><strong>Querying the DOM</strong>: Leveraging screen.getByText, screen.getByDisplayValue, or screen.getByPlaceholderText to locate elements based on user-facing content.</li><li><strong>Simulating User Actions</strong>: Using fireEvent.change to mimic typing or fireEvent.click to trigger button clicks.</li><li><strong>Handling Async Operations</strong>: Employing waitFor to manage asynchronous data fetching, like the getUser call in ContactForm.</li><li><strong>Assertions</strong>: Applying Jest-DOM matchers like toBeInTheDocument or toHaveBeenCalledWith to verify behavior. These techniques were unfamiliar compared to Django Ninja’s straightforward endpoint testing, making frontend tests harder to conceptualize and implement</li></ul><h4><strong>The Role of AI in Test Writing</strong></h4><p>AI tools were a game-changer for writing basic tests, quickly generating boilerplate code for simple scenarios like rendering or basic interactions. However, for advanced components like ContactForm, which involved async data fetching, external APIs (e.g., WhatsApp URL generation), and error handling, AI required highly detailed prompts and context. I often had to experiment with multiple generative AI models to find the most accurate and relevant test code, combining their outputs with manual refinements to achieve the desired coverage.</p><h4><strong>Learning Curve and Familiarity</strong></h4><p>As React was new to me in the BudidayaPlus project, the combination of learning the framework and applying TDD was hard. Mastering tools like React Testing Library and understanding concepts like DOM queries or async testing took significant effort, making the TDD process feel overwhelming initially.</p><p>With more familiarity in backend development, TDD with Django Ninja felt more comfortable. The testing tools and patterns were more familiar, and the logic-driven nature of APIs aligned better with my prior experience, allowing for smoother test development.</p><h4><strong>Challenges in Achieving Full Code Coverage</strong></h4><p>Despite covering all logical branches and edge cases (e.g., missing user data, submission errors, invalid inputs), some lines in the ContactForm component remained uncovered, preventing 100% code coverage. These missed lines were often tied to obscure edge cases or internal logic that was difficult to trigger in tests. For example, certain error-handling paths or conditional rendering scenarios required complex mocking or state setups that were hard to replicate. This highlighted the practical limits of code coverage and the need to balance effort with meaningful test quality.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4c33bf12843" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streamlining UI Development with Comprehensive Design Guidelines for Dev Teams]]></title>
            <link>https://medium.com/@rzapriono/streamlining-ui-development-with-comprehensive-design-guidelines-for-dev-teams-e34b046e9431?source=rss-9921022861c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/e34b046e9431</guid>
            <dc:creator><![CDATA[Reza Apriono]]></dc:creator>
            <pubDate>Mon, 28 Apr 2025 06:17:29 GMT</pubDate>
            <atom:updated>2025-05-14T07:29:57.597Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YYHUyJzF_U01RvDDQGVwCA.jpeg" /><figcaption>img source: <a href="https://idseducation.com/9-tools-terbaik-untuk-ui-design/">https://idseducation.com/9-tools-terbaik-untuk-ui-design/</a></figcaption></figure><p>In today’s fast-paced development environment, creating consistent, accessible, and visually appealing user interfaces (UIs) is a challenge for dev teams. A well-defined UI design guideline serves as a single source of truth, aligning designers and developers to produce cohesive products efficiently. The BudidayaPlus UI Guidelines exemplify this approach, providing clear rules for colors, UI components, typography, layout, interactions, and more. Built with tools like Figma, Tailwind CSS, and React, these guidelines streamline UI development by reducing ambiguity, ensuring consistency, and accelerating workflows. Here’s how dev teams can leverage these guidelines to enhance their projects.</p><h3>Why UI Design Guidelines Matter</h3><p>UI design guidelines are more than just a set of rules — they’re a roadmap for collaboration. For developers, they eliminate guesswork by defining precise styles, components, and behaviors. For designers, they ensure visual consistency across platforms. The BudidayaPlus guidelines, rooted in a Figma design system and Tailwind CSS, offer a practical framework that benefits dev teams by:</p><ul><li><strong>Ensuring Consistency</strong>: Predefined colors, typography, and components prevent ad-hoc design decisions.</li><li><strong>Boosting Efficiency</strong>: Reusable React components and Tailwind utility classes speed up coding.</li><li><strong>Improving Collaboration</strong>: A shared language between designers and developers reduces miscommunication.</li><li><strong>Enhancing Accessibility</strong>: Rules for contrast and typography prioritize usability for all users.</li></ul><p>Let’s dive into the key sections of the BudidayaPlus UI Guidelines and explore how they empower dev teams.</p><h3>Do and Don’ts Page: A Blueprint for Success</h3><p>The BudidayaPlus UI Guidelines dedicated Do and Don’ts page is a critical resource for both designers and developers. This page showcases examples of correct (Do) and discouraged (Don’t) uses of design elements, Its purpose is to set clear boundaries and best practices, ensuring all team members align with the product’s identity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5ayIAQfcOvza4_pqnDnT1w.png" /><figcaption>Do’(s) UI Guidelines</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PsAWZv75Nh8GOq6LPu3yPw.png" /><figcaption>Don’t(s) UI Guidelines</figcaption></figure><p>By integrating this page into daily workflows such as referencing it during code reviews or pairing it with Figma annotations, dev teams can reduce miscommunication about the design and implementations of BudidayaPlus features. Here’s how each section of the UI Guidelines can benefits the team to work better on developing budidayaplus:</p><h4>🎨 Colors: Optimizing Visual Workflow</h4><p>Dev teams benefit significantly from a structured color approach that aligns with the BudidayaPlus guidelines. By extracting colors directly from Figma using plugins, developers can integrate them seamlessly into Tailwind CSS, minimizing manual adjustments and debugging time.</p><h4>🖋️ Typography: Enhancing Coding Efficiency</h4><p>The BudidayaPlus typography guidelines provide dev teams with a clear structure to automate styling, reducing the need for custom CSS. Previously, the guidelines offered a basic overview of typography principles, focusing on font types, sizes, and weights to establish hierarchy and readability,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uBbTz83UfzyA-QFlXELpwg.png" /><figcaption>Previous Typography Guidelines</figcaption></figure><p>Because of the lack of implementation details in the guidelines, developers are often forced to manually configure font styles, leading to inconsistencies and wasted time.</p><p>Recognizing this gap, I improved the guidelines by integrating Tailwind CSS classes with detailed explanations of their functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Dn7Imp-1ZaU6Bmf1DJ8HA.png" /><figcaption>Improved Typography Guidelines with More Technical Guide</figcaption></figure><p>For example, instead of manually setting font sizes and weights, developers can now directly copy-paste classes like text-2xl for a 24px heading or font-bold for emphasis, ensuring uniformity across the application. This enhancement allows dev teams to export font configurations via Tailwind’s setup, streamlining initial setup and future updates. The structured hierarchy ensures content is logically prioritized, allowing devs to focus on functionality rather than tweaking text appearances, ultimately delivering a polished user experience.</p><h4>🧱 UI Components: Boosting Productivity</h4><p>Leveraging the BudidayaPlus UI Kit, dev teams can accelerate prototyping by using prebuilt components defined in figma and also reusable components in the source code.</p><h4>🧭 Layout &amp; Spacing: Ensuring Scalable Designs</h4><p>The BudidayaPlus layout and spacing guidelines help dev teams achieve consistent designs across devices with minimal effort. By validating layouts against Figma’s grid system before coding, developers can avoid alignment issues that often arise during mobile optimization.</p><h4>🧑‍💻 Prototype &amp; Interactions: Reducing Iteration Cycles</h4><p>Realistic prototypes outlined in the BudidayaPlus guidelines enable dev teams to identify interaction bugs early, reducing costly revisions. Integrating animations with Tailwind’s lightweight transition classes ensures smooth performance without heavy JavaScript, appealing to users on low-end devices.</p><h4>🏆Others: Standardizing for Long-Term Success</h4><p>The BudidayaPlus guidelines emphasize formal Indonesian UX writing, enhancing readability for local users. For styling, integrating Tailwind CSS classes with linting tools ensures consistency across the codebase, simplifying maintenance over time.</p><h3>Reusable Components</h3><p>To further enhance the BudidayaPlus ecosystem, I developed reusable components using React JS and Tailwind CSS, aligning with the guidelines to boost developer productivity.</p><h4>TextArea</h4><p>One such component is the Textarea, designed intially for the contact form but can be used anywhere when needed. This reusable component offers a customizable, accessible input field with Tailwind classes for consistent styling across the application. This eliminates the need for repetitive CSS coding, allowing dev teams to focus on functionality while maintaining a uniform look.</p><pre>// components/ui/textarea.tsx<br>import * as React from &quot;react&quot;<br><br>export interface TextareaProps<br>  extends React.TextareaHTMLAttributes&lt;HTMLTextAreaElement&gt; {}<br><br>const Textarea = React.forwardRef&lt;HTMLTextAreaElement, TextareaProps&gt;(<br>  ({ className, ...props }, ref) =&gt; {<br>    return (<br>      &lt;textarea<br>        className={`flex w-full rounded-md border border-input bg-background <br>        px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground <br>        focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring <br>        focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 <br>        ${className}`}<br>        ref={ref}<br>        {...props}<br>      /&gt;<br>    )<br>  }<br>)<br>Textarea.displayName = &quot;Textarea&quot;<br><br>export { Textarea }</pre><p>This component can be accessed here: <a href="https://github.com/PPL-5B/budidayaplus-FE/pull/26/commits/60c987812381573b36cdbebd435df2fd64c5bf9c">https://github.com/PPL-5B/budidayaplus-FE/pull/26/commits/60c987812381573b36cdbebd435df2fd64c5bf9c</a></p><h4>ForumCard</h4><p>Additionally, I created the ForumCard component, utilized on the forum page and the community page’s preview section. This component provides a structured layout for forum posts, all styled with Tailwind CSS for responsiveness and scalability. The integration with hooks like useVote and navigation utilities further streamlines interactivity, making it easier to maintain and extend the codebase.</p><pre>// components/forum/ForumCard.tsx<br>import React from &#39;react&#39;;<br>import { Forum } from &#39;@/types/forum&#39;;<br>import { useRouter } from &#39;next/navigation&#39;;<br>import { ChevronRight } from &#39;lucide-react&#39;;<br><br>interface ForumCardProps {<br>  forum: Forum;<br>}<br><br>const ForumCard: React.FC&lt;ForumCardProps&gt; = ({ forum }) =&gt; {<br>  const router = useRouter();<br><br>  const handleClick = () =&gt; {<br>    router.push(`/forum/${forum.id}`);<br>  };<br><br>  const formattedDate = new Date(forum.timestamp).toLocaleString(&#39;en-US&#39;, {<br>    year: &#39;numeric&#39;,<br>    month: &#39;2-digit&#39;,<br>    day: &#39;2-digit&#39;,<br>    hour12: false,<br>    hour: &#39;2-digit&#39;,<br>    minute: &#39;2-digit&#39;,<br>    second: &#39;2-digit&#39;<br>  });<br><br>  return (<br>    &lt;div className=&quot;w-full border rounded-lg p-4 shadow-md bg-white hover:bg-gray-100 transition duration-200 flex flex-col gap-4&quot;&gt;<br>      &lt;h2 className=&quot;text-lg font-semibold&quot;&gt;<br>        Dibuat oleh: {forum.user.first_name + &#39; &#39; + forum.user.last_name}<br>      &lt;/h2&gt;<br>      &lt;h3 className=&quot;text-gray-600&quot;&gt;<br>        Tanggal: {formattedDate}<br>      &lt;/h3&gt;<br>      &lt;p className=&quot;text-gray-600&quot;&gt;{forum.description}&lt;/p&gt;<br>      &lt;div className=&quot;flex justify-end items-center gap-2&quot;&gt;<br>        &lt;button className=&quot;text-sm text-blue-500 font-medium cursor-pointer hover:underline bg-transparent border-none p-0&quot; onClick={handleClick}&gt;<br>          Lihat detail forum<br>        &lt;/button&gt;<br>        &lt;ChevronRight<br>          className=&quot;w-6 h-6 text-[#ff8585] hover:text-[#ff8585] cursor-pointer&quot;<br>          onClick={handleClick}<br>          aria-label=&quot;Navigate to forum&quot;<br>        /&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default ForumCard;</pre><p>This component can be accessed here: <a href="https://github.com/PPL-5B/budidayaplus-FE/pull/33/commits/0dee1cd474b7c93ad92c1c5956060bd8391c5229">https://github.com/PPL-5B/budidayaplus-FE/pull/33/commits/0dee1cd474b7c93ad92c1c5956060bd8391c5229</a></p><h3>Conclusion</h3><p>The BudidayaPlus UI Guidelines empower dev teams to build consistent, accessible, and efficient interfaces. By leveraging a structured color strategy, optimized typography, scalable layouts, streamlined interactions, and reusable components, developers can focus on functionality rather than design decisions. The Do and Don’ts page, visual guide, and custom components further enhance this process, bridging the gap between design and development for faster iterations and a polished user experience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e34b046e9431" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improve Django App’s Performance with Silk Profiling]]></title>
            <link>https://medium.com/@rzapriono/improve-django-apps-performance-with-silk-profiling-b20cd115a0cc?source=rss-9921022861c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/b20cd115a0cc</guid>
            <dc:creator><![CDATA[Reza Apriono]]></dc:creator>
            <pubDate>Sun, 20 Apr 2025 19:04:02 GMT</pubDate>
            <atom:updated>2025-05-20T01:45:42.450Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u_1QkIEWG4n4icHhsovEXA.jpeg" /><figcaption>source: <a href="https://datascientest.com/en/django-all-about-the-python-web-development-framework">https://datascientest.com/en/django-all-about-the-python-web-development-framework</a></figcaption></figure><p>Django is a powerful framework for building web applications, but performance bottlenecks can arise as projects grow. Identifying and resolving these issues is critical for delivering fast, scalable applications. Silk, a lightweight profiling tool, provides developers with detailed insights into Django application performance by tracking requests, queries, and execution times. This article explores how to integrate Silk into your Django project and leverage its features to optimize performance.</p><h3>What is Profiling?</h3><p>Profiling is the process of measuring and analyzing the performance of an application to identify bottlenecks, inefficiencies, or areas for optimization. In the context of a web application like a Django API, profiling helps us understand:</p><ul><li><strong>Overall Response Time</strong>: How long a request takes from start to finish.</li><li><strong>Database Query Performance</strong>: The time spent executing database queries, including the number of queries and their complexity.</li><li><strong>Code Execution</strong>: Which parts of the code (e.g., functions, middleware) contribute most to the response time.</li></ul><p>Profiling is essential for optimizing user experience, especially for APIs where low latency is critical. For example, a slow login endpoint can frustrate users, while a fast one improves satisfaction. Profiling tools provide detailed metrics, allowing developers to pinpoint and address performance issues systematically.</p><h3>Why Use Silk for Profiling?</h3><p>Silk is a powerful profiling and debugging tool for Django applications. It intercepts HTTP requests and provides a detailed breakdown of their performance, including:</p><ul><li>Total request time.</li><li>Time spent on database queries, including the number of queries and their execution times.</li><li>A breakdown of where time is spent in the code</li><li>Visual summaries of performance metrics.</li></ul><p>To use Silk, you install it via pip (pip install django-silk), add it to your Django settings, and apply its middleware. Don’t forget to also add SILKY_PYTHON_PROFILER = True so that the profiler we created would be detected in silk interface.</p><pre># budidayaplus/settings.py<br><br>...<br><br>INSTALLED_APPS = [<br>    ...<br>    &#39;silk&#39;,<br>]<br><br>...<br><br>MIDDLEWARE = [<br>    ...<br>    &#39;silk.middleware.SilkyMiddleware&#39;,<br>]<br><br>...<br><br>SILKY_PYTHON_PROFILER = True</pre><p>To make sure everything is working normally, especially the ci/cd and github actions, don’t forget to add django-silk to requirements.txt.</p><h3>Setting Up the Login API Silk Profiler</h3><p>The Login API is a POST endpoint at /api/auth/login that accepts a phone_number and password. It authenticates the user and returns access and refresh tokens. Here’s the relevant code:</p><pre>from ninja_jwt.exceptions import TokenError<br>from django.contrib.auth.models import User<br>from ninja_jwt.authentication import JWTAuth<br>from silk.profiling.profiler import silk_profile<br><br>router = Router()<br><br>@router.post(&quot;/login&quot;, throttle=AnonRateThrottle(rate=&quot;10/h&quot;))<br>@silk_profile(name=&quot;Profiling Login API&quot;)<br>def login(request, data: LoginSchema):<br>    print(&quot;Login attempt with data:&quot;, data.dict())<br>    user = User.objects.get(username=data.phone_number)<br>    if not user.check_password(data.password):<br>        raise HttpError(404, &quot;Pengguna tidak terdaftar atau kata sandi salah&quot;)<br><br>    refresh = RefreshToken.for_user(user)<br>    new_access_token = str(refresh.access_token)</pre><p>I’ve decorated the login api with @silk_profile(name=”Profiling Login API”) to enable profiling for this endpoint. Silk will track the request’s performance and store the data for analysis.</p><h3>Initial Profiling</h3><p>I tested the API by sending POST requests to <a href="http://localhost:8000/api/auth/login">http://localhost:8000/api/auth/login</a> with a sample phone_number and password using Postman.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yPZ2QlHkkTR-qetToGoucw.png" /><figcaption>Hit Login API with Django Default Password Hashers (PBKDF2)</figcaption></figure><p>Here’s what Silk captured of the performance metrics for the requests:</p><ul><li><strong>Initial Request Profiling Result</strong>: 1087ms overall, 2ms on queries, 1 query</li></ul><p>Silk’s detailed logs provide deeper insights:</p><ul><li><strong>A single database query</strong>: SELECT on the auth_user table, taking around 2.168ms.</li><li>The overall request time took a really long time, which needs 1087 ms until the response is provided. Even Silk shows the response time in red color, indicating it’s really bad.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zoJCufqDzW3Plwi-FOjuKQ.png" /><figcaption>Initial Profiling: Silk Profiler Details on Login API</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*WbLvQdsOxozgudBLj8FD8Q.png" /><figcaption>Initial Profiling: Silk Profiler Queries on Login API</figcaption></figure><p>After hitting the Login API a few times, the database query time is consistently low at ~2ms, but the overall request time is much higher. This discrepancy indicates that the bottleneck lies outside the database query.</p><h3>Identifying Bottlenecks</h3><p>Based on initial profiling results, the login function performs a few key operations, which are fetching the user, checking the password with user.check_password(), and generating JWT tokens. Since the database query is fast, the likely culprit is the password verification step, which involves hashing and comparing the provided password against the stored hash.</p><p>I also asked AI to help me determine which simplest part of the Login process that i could improve to reduce the response time significantly. It aligns with my analysis that one of the possible problem is come from the password verification process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-B2zOh6O1Opqxa0DgGvowA.png" /><figcaption>Copilot Suggestions about How to Resolve the Performance Issue based on Profiling</figcaption></figure><p>I tried implementing the solutions provided to optimize my API login endpoint, which was taking around 700ms to respond. Unfortunately, the results were disappointing. Some solutions led to errors, while others showed no noticeable improvement in performance. Curious to dig deeper, I decided to explore Solution 2 (using Argon2) further and went back to ask for more insights.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FxgUjcRYn55rwX4HJXPQAg.png" /><figcaption>Copilot Suggestion for Better Password Hashing Algorithm</figcaption></figure><p>Afterward, I took the time to verify and analyze the information provided. I came across an insightful article on <a href="https://guptadeepak.com/comparative-analysis-of-password-hashing-algorithms-argon2-bcrypt-scrypt-and-pbkdf2/">Comparative Analysis of Password Hashing Algorithms</a>, which highlighted that Argon2 is not only more secure but also faster than Django’s default hashing algorithm, PBKDF2.</p><p>This finding is further supported by the <a href="https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html">OWASP Password Storage Cheat Sheet</a>, which recommends Argon2 as the preferred password hashing algorithm for modern applications due to its robust security features and performance benefits.</p><p>In performance tests mentioned in the article, Argon2 consistently outperformed PBKDF2 in terms of speed while maintaining a higher security margin, which was exactly what we needed for BudidayaPlus login endpoint.</p><h3>Analyzing the Bottleneck</h3><p>Django’s check_password() method uses the default password hasher to verify the password. By default, Django uses PBKDF2 (Password-Based Key Derivation Function 2) with SHA256 and a high number of iterations (600,000 in Django 5.0 as of April 2025). PBKDF2 is computationally intensive by design to enhance security, but this also means it can slow down requests, especially with such a high iteration count.</p><p>To confirm this, I noted that the token generation step (using ninja-jwt) is relatively lightweight, and no other heavy operations are present for the login. The high overall time (1087 ms) compared to the query time (2ms) strongly points to password hashing as the bottleneck. Silk’s profiling was instrumental in isolating this issue, as it clearly showed that database queries were not the problem.</p><h3>Optimizing Performance: Switching to Argon2</h3><p>Convinced by these findings, I decided to implement Argon2 in my project. Based on the profiling analysis, I focused on optimizing the password hashing step by switching from PBKDF2 to Argon2. The implementation was surprisingly straightforward. I started by installing the argon2-cffi package using pip install argon2-cffi, and then updated Django’s settings.py file to configure Argon2 as the password hasher.</p><pre># budidayaplus/settings.py<br><br>...<br><br>PASSWORD_HASHERS = [<br>    &#39;django.contrib.auth.hashers.Argon2PasswordHasher&#39;,<br>    &#39;django.contrib.auth.hashers.PBKDF2PasswordHasher&#39;,<br>    &#39;django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher&#39;,<br>    &#39;django.contrib.auth.hashers.BCryptSHA256PasswordHasher&#39;,<br>]</pre><h3>Understanding the First Request After Switching to Argon2</h3><p>I then re-ran the profiling on the same endpoint. However, I noticed an interesting behavior with the first request after the switch:</p><ul><li><strong>First Request</strong>: 944ms overall, 18ms on queries, 2 queries</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1w8mrUO3Nb6jTFdTJVSigA.png" /><figcaption>Hit Login API After Changing Password Hashers using Argon2</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Q1QHshQa_RYWBzD9iR06Q.png" /><figcaption>Silk Profiler Details on Login API after changing Password Hasher to Argon2</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*jXMx3EWvbEyqpN85zbGF1A.png" /><figcaption>Silk Profiler Queries on Login API after changing Password Hasher to Argon2</figcaption></figure><p>The first request after switching to Argon2 took 944ms, which is similar to the initial profiling results with PBKDF2 (796ms average). Additionally, Silk showed two database queries instead of one, with a total query time of 18ms, broken down as:</p><ul><li>An UPDATE on the auth_user table: 16.248ms</li><li>A SELECT on the auth_user table: 1.999ms</li></ul><p>This behavior occurs because the user’s password in the database was initially stored using PBKDF2. When check_password() is called with the new hasher (Argon2) set as the default, Django verifies the password using the old hasher (PBKDF2), then re-hashes and updates the password to the new hasher (Argon2). This process triggers an UPDATE query to save the new hash in the database, which explains the additional query and the increased query time (18ms vs. 2ms).</p><p>The UPDATE query takes longer (16.248ms) because it involves writing to the database, which is generally slower than a SELECT (1.999ms). Moreover, the overall time remains high for this first request because the password verification still uses PBKDF2 for the initial check, maintaining the same computational overhead as before (around 796ms). After this first request, the password is stored with Argon2, so subsequent requests benefit from Argon2’s efficiency.</p><h3>Performance After Password Hash Migration</h3><p>Once the password is migrated to Argon2, subsequent requests show a significant improvement:</p><ul><li>The overall request time drops to 159ms.</li><li>The query count returns to 1 (just the SELECT), with a query time of ~2ms.</li></ul><p>This represents nearly a 7<strong>x improvement</strong> in overall latency compared to the initial 1087ms response time with PBKDF2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Duu_pBlz7mNXqodRtcyQzw.png" /><figcaption>Hit Login API After User Password is Already Hashed using Argon2</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wv6s8IW6FvdUOe8H-4iVDg.png" /><figcaption>Silk Profiler Details on Login API using Argon2 as Password Hasher</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*eOVwAYXEYcMT1Adf4Z7BiA.png" /><figcaption>Silk Profiler Queries on Login API using Argon2 as Password Hasher</figcaption></figure><p>Here’s a comparison (right-to-left) of Login request using django default password hasher, initial request after changing the hasher to Argon2, and the request after the user password is already migrated and hashed in Argon2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*4hLlLC0z4oARTF79-L3j1w.png" /><figcaption>Comparison Between PBKDF2 and Argon2</figcaption></figure><h3>Load Testing and Long-Term Performance Optimization</h3><p>To evaluate the scalability and long-term performance of the BudidayaPlus Django backend, I conducted load testing using Locust. The test simulated multiple users performing authentication-related tasks (registration, login, token refresh, token validation, and user info retrieval) on the API endpoints.</p><h4><a href="https://drive.google.com/drive/folders/1eZuUQWdBmJrgJ6ahTglnEk8Zfh8VKxlf?usp=sharing">Load Test Results</a></h4><p>The load test was conducted using Locust with 200 concurrent users (10 ramp up) over a 3-minute period, simulating authentication tasks such as registration, login, token refresh, token validation, and user info retrieval. Below are the key metrics before and after switching to Argon2.</p><p><strong>Before Switching to Argon2 (PBKDF2):</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P6V2tRjDytEqdj0Kr4wJGw.png" /><figcaption>Locust Report of Response Time Statistics using PBKDF2</figcaption></figure><p>The load test results using the default PBKDF2 password hasher, reveal significant performance challenges. The Response Time Statistics show median response times ranging from 5000 ms for /api/auth/me and /api/auth/validate to 9600 ms for /api/auth/register, with the login endpoint at 7800 ms. Peaks reach up to 23000 ms for registration, indicating severe latency, likely due to PBKDF2’s computationally intensive hashing (600,000 iterations).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YPlWMejLgsVyZeBSGS3ewQ.png" /><figcaption>Chart from the Locust Report using PBKDF2</figcaption></figure><p>The “Charts” further illustrate this, with a 50th percentile response time stabilizing around 5000–7000 ms and a 95th percentile peaking above 20000 ms, while handling an average of 20–25 requests per second with minimal failures, suggesting stability but at a high performance cost.</p><p><strong>After Switching to Argon2:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fiRiK8C3znuOsDl0Z3csgg.png" /><figcaption>Locust Report of Response Time Statistics using Argon2</figcaption></figure><p>The load test results using the Argon2 password hasher, show a notable performance improvement over PBKDF2. The Response Time Statistics reveal a median response time of 3900 ms across all endpoints, down from 5800 ms with PBKDF2, with specific gains such as the login endpoint dropping to 4700 ms (from 7800 ms) and registration to 6000 ms (from 9600 ms).</p><p>The maximum response time is reduced by 48% to 12000 ms from 23000 ms, with peaks for the 95th percentile reaching 6300 ms, indicating more consistent performance. This improvement is attributed to Argon2’s efficient hashing, which mitigates the computational overhead seen with PBKDF2’s high iteration count.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bf2gCMlZPZ6Ye5OYj-bbsQ.png" /><figcaption>Chart from the Locust Report using Argon2</figcaption></figure><p>The Charts analysis further supports these findings, with an average of 25–30 requests per second (up from 20–25 with PBKDF2) and minimal failures, reflecting enhanced throughput and stability under load. The 50th percentile response time stabilizes around 3000–4000 ms, while the 95th percentile peaks at 10000 ms, a significant reduction from PBKDF2’s 20000 ms.</p><p>These results underscore Argon2’s potential to support scalability and reliability for BudidayaPlus, reducing latency and resource demands as user traffic grows.</p><h3>Final Thoughts</h3><p>Optimizing the BudidayaPlus Django backend with Silk profiling and Locust load testing revealed the power of performance analysis for scalable web applications. Silk identified the password hashing bottleneck with PBKDF2, leading to a switch to Argon2, which significantly improved login times and reduced response times under load, enhancing both performance and scalability while maintaining security.</p><p>This shift also promises long-term efficiency, lowering resource demands and improving reliability as user traffic grows. For Django developers, combining profiling and load testing is a good strategy to address bottlenecks, ensuring applications like BudidayaPlus deliver fast, seamless user experiences while scaling effectively.</p><h3>Thank you for reading my story!</h3><p>References:</p><ul><li><a href="https://docs.djangoproject.com/en/5.2/topics/auth/passwords/">Django Password Documentation</a></li><li><a href="https://medium.com/@sharif-42/profiling-django-application-using-django-silk-62cdea83fb83">Profiling using Django Silk</a></li><li><a href="https://guptadeepak.com/comparative-analysis-of-password-hashing-algorithms-argon2-bcrypt-scrypt-and-pbkdf2/">Comparative Analysis of Password Hashing Algorithms</a></li><li><a href="https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html">OWASP Password Storage Cheat Sheet</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b20cd115a0cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Load Testing in Python using Locust]]></title>
            <link>https://medium.com/@rzapriono/load-testing-in-python-using-locust-becd3a15db59?source=rss-9921022861c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/becd3a15db59</guid>
            <dc:creator><![CDATA[Reza Apriono]]></dc:creator>
            <pubDate>Sun, 06 Apr 2025 09:52:56 GMT</pubDate>
            <atom:updated>2025-05-20T01:40:01.218Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dOcMpxQKmNGwJfw9piBXiw.png" /><figcaption>source: <a href="https://locust.io/">https://locust.io/</a></figcaption></figure><p>Ever wondered how your application holds up when tons of users hit it at once? That’s where load testing and stress testing come in. These techniques help you figure out if your app can handle real-world traffic or if it’ll buckle under pressure. In this post, I’ll walk you through using Locust, a Python-based tool, to run these tests</p><h3>What’s Locust All About?</h3><p>Locust is a Python-based performance testing tool that allows you to simulate thousands of users interacting with your application. It’s highly customizable, scriptable in Python, and supports distributed testing for large-scale scenarios. Unlike other tools, Locust lets you define user behavior using Python code, making it flexible for complex test scenarios.</p><h3>Load Testing vs. Stress Testing</h3><ul><li><strong>Load Testing</strong>: Evaluates how your application performs under expected or peak user loads. The goal is to ensure the system handles the anticipated traffic smoothly.</li><li><strong>Stress Testing</strong>: Pushes the application beyond its normal capacity to identify breaking points, bottlenecks, or failures under extreme conditions.</li></ul><p>Locust is well-suited for both types of tests, as it allows you to simulate varying user loads and monitor system behavior in real-time.</p><h3>Setting Up Locust</h3><p>Let’s get started with setting up Locust and running a simple test.</p><h4>Prerequisites</h4><ul><li>Python 3.6 or higher</li><li>A web application to test (e.g., a local Flask or Django app)</li></ul><h4>Installation</h4><p>Install Locust using pip:</p><pre>pip install locust</pre><p>Verify the installation:</p><pre>locust --version</pre><h3>My Test Script</h3><p>I wrote a locustfile.py to test an authentication API with endpoints like /api/auth/register and /api/auth/login. It simulates users signing up, logging in, refreshing tokens, validating tokens, and grabbing user info. Here’s the gist:</p><pre>from locust import HttpUser, TaskSet, task, between<br>import random<br><br>class AuthenticationTasks(TaskSet):<br>    def on_start(self):<br>        &quot;&quot;&quot;Executed when a simulated user starts.&quot;&quot;&quot;<br>        self.phone_number = &quot;08&quot; + str(random.randint(100000000, 999999999))<br>        self.password = &quot;lelealomani&quot;<br>        self.first_name = &quot;alomani&quot;<br>        self.last_name = &quot;lele&quot;<br>        self.access_token = None<br>        self.refresh_token = None<br><br>        print(f&quot;Trying to register: {self.phone_number}&quot;)<br>        self.register_user()<br><br>    def register_user(self):<br>        payload = {<br>            &quot;phone_number&quot;: self.phone_number,<br>            &quot;first_name&quot;: self.first_name,<br>            &quot;last_name&quot;: self.last_name,<br>            &quot;password&quot;: self.password<br>        }<br>        try:<br>            response = self.client.post(&quot;/api/auth/register&quot;, json=payload)<br>            if response.status_code == 200:<br>                tokens = response.json()<br>                self.access_token = tokens.get(&quot;access&quot;)<br>                self.refresh_token = tokens.get(&quot;refresh&quot;)<br>                print(f&quot;Register success: {self.phone_number}&quot;)<br>                self.registered = True<br>            else:<br>                print(f&quot;Register failed ({response.status_code}): {response.text}&quot;)<br>                self.registered = False<br>        except Exception as e:<br>            print(f&quot;Register error: {e}&quot;)<br>            self.registered = False<br><br><br>    @task<br>    def login(self):<br>        &quot;&quot;&quot;Simulate user login.&quot;&quot;&quot;<br>        if not getattr(self, &#39;registered&#39;, False):<br>            print(f&quot;Skipping login because register failed for {self.phone_number}&quot;)<br>            return<br>    <br>        payload = {<br>            &quot;phone_number&quot;: self.phone_number,<br>            &quot;password&quot;: self.password<br>        }<br>        try:<br>            response = self.client.post(&quot;/api/auth/login&quot;, json=payload)<br>            if response.status_code == 200:<br>                print(f&quot;Login success: {self.phone_number}&quot;)<br>            else:<br>                print(f&quot;Login failed ({response.status_code}): {response.text}&quot;)<br>        except Exception as e:<br>            print(f&quot;Login error: {e}&quot;)<br><br>    @task<br>    def refresh_token_task(self):<br>        &quot;&quot;&quot;Simulate refreshing the access token.&quot;&quot;&quot;<br>        if self.refresh_token:<br>            payload = {&quot;refresh&quot;: self.refresh_token}<br>            try:<br>                self.client.post(&quot;/api/auth/refresh&quot;, json=payload)<br>            except Exception as e:<br>                print(f&quot;Refresh token error: {e}&quot;)<br><br>    @task<br>    def validate_token(self):<br>        &quot;&quot;&quot;Simulate validating the access token.&quot;&quot;&quot;<br>        if self.access_token:<br>            try:<br>                self.client.post(&quot;/api/auth/validate&quot;, headers={&quot;Authorization&quot;: f&quot;Bearer {self.access_token}&quot;})<br>            except Exception as e:<br>                print(f&quot;Validate token error: {e}&quot;)<br><br>    @task<br>    def get_user_info(self):<br>        &quot;&quot;&quot;Simulate retrieving user information.&quot;&quot;&quot;<br>        if self.access_token:<br>            try:<br>                self.client.get(&quot;/api/auth/me&quot;, headers={&quot;Authorization&quot;: f&quot;Bearer {self.access_token}&quot;})<br>            except Exception as e:<br>                print(f&quot;Get user info error: {e}&quot;)<br><br>class AuthenticationUser(HttpUser):<br>    tasks = [AuthenticationTasks]<br>    wait_time = between(1, 3)<br>    host = &quot;http://&lt;VM_IP&gt;:&lt;VM_PORT&gt;&quot;</pre><p>This script:</p><ul><li>Generates unique phone numbers for each user.</li><li>Registers them, saves their tokens, and then tests login, token refresh, token validation, and user info endpoints.</li><li>Pauses 1–3 seconds between actions to act like real users.</li></ul><h3>Running a Load Test</h3><p>Want to see if your API can handle 100 users? Here’s how:</p><ol><li>Start Locust:</li></ol><pre>locust -f locustfile.py</pre><p>2. Go to <a href="http://localhost:8089/">http://localhost:8089</a> in your browser.</p><p>3. Set 100 users and a spawn rate of 5 (adds 5 users per second).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NXx1AkZky-I8VDpiW715Vg.png" /></figure><p>4. Hit start and watch the dashboard. You’ll see:</p><ul><li>How fast /api/auth/login and others respond.</li><li>How many requests per second your API handles.</li><li>Any errors (like 500s if your server’s struggling)</li></ul><p>5. Check your server’s CPU and database to make sure it’s not sweating too hard.</p><h3>Load Testing Results</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cJ1K_oKy_NXhStWUv0GXmA.png" /></figure><h3>Analysis of the Graphs</h3><ol><li><strong>Total Requests per Second (RPS)</strong></li></ol><ul><li>The green line shows RPS, which starts at 0 and ramps up to around 6–7 requests per second by 09:27:40, then stabilizes with slight fluctuations.</li><li>Failures/s (not visible in the graph) seem to be zero, as there’s no red line indicating errors. This suggests your API handled all requests successfully under this load.</li><li><strong>Insight</strong>: With 100 users performing tasks like registration, login, and token refresh, an RPS of 6–7 is reasonable, especially if each user has a wait_time of 1–3 seconds. This indicates steady activity without overwhelming the server.</li></ul><p><strong>2. Response Times (ms)</strong></p><ul><li>The 50th percentile (orange line) and 95th percentile (purple line) both start near 0 ms and rise steadily.</li><li>By 09:27:40, the 50th percentile reaches around 2000 ms (2 seconds), and the 95th percentile hits about 4000 ms (4 seconds).</li><li><strong>Insight</strong>: Response times increasing to 2–4 seconds as the user count grows suggests your API is starting to feel the load. The 95th percentile being double the 50th percentile indicates some requests are taking longer, possibly due to database queries or token validation delays. This could be a bottleneck to investigate.</li></ul><p><strong>3. Number of Users</strong></p><ul><li>The blue line shows the number of users ramping up from 0 to 100 between 09:27:10 and 09:27:40 (a 30-second ramp-up), then stabilizing at 100 until 09:28:00.</li><li><strong>Insight</strong>: The ramp-up rate of 5 users/second over 30 seconds aligns with the test settings, and the peak of 100 users was maintained, giving a good test of peak load.</li></ul><h3>Overall Assessment</h3><ul><li><strong>Good News</strong>: The API handled 100 concurrent users without failures, which is a solid start for a load test. The RPS of 6–7 and stable user count show the system can manage the expected traffic.</li><li><strong>Areas to Watch</strong>: The rising response times (up to 4 seconds for the slowest 5% of requests) suggest performance degradation under load. For an authentication API, 2–4 seconds might be acceptable for internal testing, but for real users, you’d ideally want sub-second responses (e.g., under 500 ms).</li></ul><h3>Increasing Peak Loads and Ramp-Up Variations</h3><p>The load test was conducted using Locust with 200 concurrent users (10 ramp up) over a 3-minute period, simulating authentication tasks such as registration, login, token refresh, token validation, and user info retrieval. Below are the key metrics of the locust report.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Po8rqrpbwyU8PQgc.png" /><figcaption>Locust Report of Response Time Statistics</figcaption></figure><p>Under a load test with 200 concurrent users and 10 ramp up/second, the median response time across all endpoints stabilized at 3900ms, with a maximum of 12000ms. The 50th percentile response time hovered around 3000–4000ms, while the 95th percentile peaked at 10000ms. The system maintained an average of 25–30 requests per second with minimal failures, showcasing robust performance and scalability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bf2gCMlZPZ6Ye5OYj-bbsQ.png" /><figcaption>Locust Chart of Load Testing Result</figcaption></figure><p>Insights from the result:</p><ul><li><strong>Response Time Distribution:</strong> The median (50th percentile) response time across all endpoints was 3900ms, with the 60th percentile at 4100ms, 70th at 4500ms, 80th at 4900ms, 90th at 5500ms, 95th at 6300ms, 99th at 8600ms, and a maximum (100th percentile) of 12000ms. This indicates a consistent performance profile, with the majority of requests completing under 5 seconds and only the slowest 1% exceeding 8.6 seconds.</li><li><strong>Endpoint-Specific Performance:</strong> The login endpoint maintained a median of 4700ms, registration at 6000ms, while lighter endpoints like token validation and user info retrieval stabilized around 3600ms. Peaks varied, with registration hitting 12000ms and login at 10000ms, reflecting higher complexity in user creation and initial authentication.</li><li><strong>Throughput and Stability:</strong> The system achieved an average of 25–30 requests per second, with fluctuations between 10 and 40 requests per second during peak user activity. Failures per second remained negligible, averaging near 0 with only occasional spikes, demonstrating high stability under load.</li><li><strong>User Load Dynamics:</strong> The number of users ramped up from 50 to 200 within the first minute, sustaining 200 users until a gradual drop-off at the test’s end, correlating with response time increases during the ramp-up phase and stabilization thereafter.</li><li><strong>Resource Utilization:</strong> The improved response times and throughput suggest efficient CPU and memory usage, with Argon2’s tunable parameters (time cost, memory cost, and parallelism) likely contributing to balanced resource allocation under stress.</li></ul><h3>Best Practices Supporting Argon2 and the Load Test</h3><p>The load testing approach done for BudidayaPlus aligns with best practices outlined in the <a href="https://grafana.com/blog/2024/01/30/load-testing-websites/">Grafana Labs blog</a> (published January 30, 2024). The article emphasizes simulating realistic user scenarios by scripting user actions rather than just requests, a practice followed here by mimicking authentication tasks like login and registration with a wait time of 1–3 seconds between actions.</p><p>The article also suggests a hybrid approach that includes browser-level testing for frontend interactions, but it also acknowledges the value of protocol-based testing for APIs. Protocol-based testing involves testing at the network protocol level (e.g., HTTP/HTTPS), which is ideal for backend APIs like the authentication endpoints in BudidayaPlus</p><p>Additionally, the blog recommends analyzing performance metrics like response time percentiles and throughput, which this test implemented by evaluating the 50th to 99th percentiles (e.g., median at 3900ms, 95th at 6300ms) and achieving 25–30 requests per second.</p><p>The decision to use to Argon2 as password hasher also aligns with current best practices in password hashing, as recommended by recent literature and industry standards. According to the <a href="https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html">OWASP Password Storage Cheat Sheet</a> (updated in 2024), Argon2 is the preferred hashing algorithm due to its memory-hard design, which offers superior resistance to GPU-based attacks while allowing tunable performance parameters for modern applications.</p><h3>Suggestion for Improvements</h3><p>Although the system can still process nearly all the incoming requests, the authentication endpoints still exhibit relatively high response times, such as a median of 4700ms for login and 3900ms overall, which may impact user experience. To further enhance performance, caching for authentication-related data using Django’s caching framework with a fast in-memory store like Redis can be considered. Caching frequently accessed data, such as user session tokens or validation results, for a short duration (e.g., a few minutes) can reduce database queries and hashing operations, balancing security and speed.</p><p>Additionally, introducing asynchronous task processing with Celery for heavy operations like token generation, could offload work from the request-response cycle. These strategies could potentially lower the median response time to a more acceptable range, improving the responsiveness of the BudidayaPlus API.</p><h3>Final Thoughts</h3><p>Locust is a game-changer for testing your API’s performance. With the script above, you can simulate real users hitting your auth endpoints and see how your system holds up. Whether you’re checking normal traffic or trying to break things, Locust’s Python scripts and live dashboard make it a breeze.</p><h3>Thank you for reading my story!</h3><p>References:</p><ul><li><a href="https://grafana.com/blog/2024/01/30/load-testing-websites/">How to Load Test a Website by Grafana Labs</a></li><li><a href="https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html">OWASP Password Storage Cheat Sheet</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=becd3a15db59" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dockerized Test Database for Django Unit Testing]]></title>
            <link>https://medium.com/@rzapriono/dockerized-test-database-for-django-unit-testing-ca1d868dea8d?source=rss-9921022861c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca1d868dea8d</guid>
            <dc:creator><![CDATA[Reza Apriono]]></dc:creator>
            <pubDate>Thu, 27 Mar 2025 03:40:46 GMT</pubDate>
            <atom:updated>2025-04-07T17:06:44.592Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*8-YOAIOlhuJG8phYnr1pSQ.png" /><figcaption>source: <a href="https://www.docker.com/company/newsroom/media-resources/">https://www.docker.com/company/newsroom/media-resources/</a></figcaption></figure><h3>Enhancing Your Software Testing with Advanced Techniques</h3><p>Modern applications inevitably interact with external systems — databases, APIs, authentication services. This creates a testing challenge: how do we verify our business logic without depending on these external components?</p><h3>Dockerized Test Database</h3><p>While mocking serves unit tests well, integration tests require interaction with a real database. Dockerized PostgreSQL provides an isolated test database that resets after each test run. Here’s a SonarCloud CI/CD configuration that implements that solution using the official Postgres 15 image to build and run tests on external database.</p><h4>Building the Docker Image for a PostgreSQL Test Database and Running Tests</h4><pre>...<br>services:<br>  postgres:<br>    image: postgres:15  # use PostgreSQL docker image<br>    env:<br>      POSTGRES_USER: postgres<br>      POSTGRES_PASSWORD: postgres<br>      POSTGRES_DB: test_db<br>    ports:<br>      - 5432:5432<br>    options: &gt;-<br>      --health-cmd=&quot;pg_isready -U postgres&quot;<br>      --health-interval=10s</pre><p>To implement this Dockerized test database, we need a job in our CI/CD pipeline to build the PostgreSQL Docker image and execute the tests. Here’s how it works:</p><ol><li><strong>Define the Docker Image</strong>: We start with the official postgres:15 image, as shown in the configuration above. You can extend this image by creating a custom Dockerfile to include initialization scripts (e.g., init.sql) that set up the database schema or seed test data. These scripts are placed in the /docker-entrypoint-initdb.d/ directory, which PostgreSQL automatically executes on startup.</li><li><strong>Build the Image</strong>: In the CI/CD pipeline (e.g., SonarCloud, GitHub Actions), a job builds the image using docker build.</li><li><strong>Run the Container</strong>: Using the docker-compose.yml configuration above, the PostgreSQL container is spun up alongside the Django app during testing. The env settings define the database credentials and name (test_db), while the ports mapping ensures the container is accessible on localhost:5432. The options include a health check (pg_isready) to confirm the database is ready before tests start.</li><li><strong>Execute Tests</strong>: With the container running, the Django test suite connects to the database using the credentials provided (e.g., DATABASE_URL=postgres://postgres:postgres@postgres:5432/test_db). Run the tests with python manage.py test, and the isolated database ensures a clean slate for each run.</li><li><strong>Cleanup</strong>: After the tests finish, the CI/CD job tears down the container, leaving no persistent state. This ensures repeatability and prevents test pollution.</li></ol><h3>Advantages of a Dockerized Test Database Approach</h3><p>This approach offers several advantages:</p><ul><li><strong>Containerized databases are isolated and ephemeral</strong> — they’re created fresh for each test run and discarded afterward, ensuring no test pollution.</li><li><strong>Using identical Docker images across all environments</strong> (development, CI, staging) eliminates the “works on my machine” problem.</li><li><strong>Local containerized databases provide much faster feedback</strong> than cloud-hosted alternatives during development. The implementation also includes proper health checks to ensure the database is ready before tests execute, demonstrating attention to reliability details.</li><li><strong>Consistency Across Environments</strong>: The same Docker image ensures the test database matches production-like conditions, reducing environment-specific bugs.</li><li><strong>Speed and Efficiency</strong>: Spinning up a Docker container is faster than resetting a local database manually, and preconfigured test data in the image speeds up setup.</li><li><strong>Reproducibility</strong>: Versioned Docker images lock in the exact database configuration (e.g., PostgreSQL version, schema), making it easy to replicate test failures or share setups with teammates.</li></ul><h3>Disadvantages of Not Using a Dockerized Test Database</h3><p>When you don’t use a Dockerized test database, you often run into issues like the one shown in the terminal output below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*ZrDNLF-Ev5lqSRjNEqlhiw.png" /><figcaption>The current test database can’t be destroyed</figcaption></figure><p>In this screenshot, I attempted to run Django tests with python manage.py test forum, but the process failed during database setup. The error message reads: django.db.utils.OperationalError: database “test_postgres” is being accessed by other users. The detail clarifies that another session is using the database, preventing Django from dropping and recreating it. When prompted to destroy the old test database (test_postgres), I selected yes, but the operation still failed because of concurrent access.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*21yw1_BEBIJcHfrj8_SP1Q.png" /><figcaption>Sentry detecting OperationalError</figcaption></figure><p>This issue arises because a non-Dockerized test database (e.g., a local PostgreSQL instance) is often shared across processes or test runs. If another process — like a lingering Django development server, a manual psql session, or a previous test run — has an open connection, PostgreSQL won’t allow the database to be dropped. This leads to test failures that are unrelated to your code, wasting time and causing frustration.</p><p>The terminal output above highlights just one of many problems you’ll encounter if you skip a Dockerized test database. Here are some key disadvantages:</p><ul><li><strong>Data Persistence Issues</strong>: Without Docker, tests often run against a shared or local database. As shown in the terminal screenshot, this can result in leftover data or connections from previous runs, leading to inconsistent test results. A test might pass once but fail later due to unexpected data or locked resources.</li><li><strong>Concurrency Conflicts</strong>: Running tests in parallel without isolated databases causes race conditions or lock contention, as seen in the terminal output where another session blocked the database drop. This leads to flaky tests that pass or fail unpredictably.</li></ul><h3>Errors Detected by Sentry</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V3si064EV6POVl8paQn2-w.png" /><figcaption>OperationalError detected by Sentry</figcaption></figure><p>This Sentry error report shows a django.db.utils.OperationalError with the same message as in the terminal output: database “test_postgres” is being accessed by other users. This example underscores the importance of a Dockerized test database. By using Docker, you ensure that test databases are isolated and ephemeral, preventing them from being misused in production. Moreover, Docker’s consistency across environments helps catch configuration issues early, before they lead to production failures like the one Sentry caught.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca1d868dea8d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monitoring Tools applied in BudidayaPlus Project]]></title>
            <link>https://medium.com/@rzapriono/monitoring-tools-applied-in-budidayaplus-project-144d6d79f9b4?source=rss-9921022861c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/144d6d79f9b4</guid>
            <dc:creator><![CDATA[Reza Apriono]]></dc:creator>
            <pubDate>Mon, 24 Mar 2025 00:33:27 GMT</pubDate>
            <atom:updated>2025-05-12T06:03:11.340Z</atom:updated>
            <content:encoded><![CDATA[<h3>Monitoring Tools Applied in BudidayaPlus Project</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WQozu_OPZAT-Ee28k0SdMA.png" /><figcaption>source:<a href="https://gili842.medium.com/sentry-enhancing-javascript-application-reliability-with-real-time-error-tracking-e22b6e17c038">https://gili842.medium.com/sentry-enhancing-javascript-application-reliability-with-real-time-error-tracking-e22b6e17c038</a></figcaption></figure><p>When developing a Django project, handling errors efficiently is crucial to maintaining a stable and reliable application. Sentry is an excellent tool that provides real-time error tracking, performance monitoring, and debugging capabilities. In this blog post, I’ll walk through my experience setting up Sentry in a Django project, sharing key configurations and useful tips.</p><h3>Installing Sentry</h3><p>Before integrating Sentry into a Django project, you need to install the Sentry SDK. This can be done using pip:</p><pre>pip install sentry-sdk[django]</pre><p>Once installed, the next step is to configure Sentry within the Django settings.</p><p>Don’t forget to also add it to requirements.txt.</p><pre>django-ninja<br>djangorestframework-simplejwt<br>django-environ<br>psycopg2-binary<br>gunicorn<br>coverage<br>django-ninja-jwt<br>python-dotenv<br>Django<br>django-cors-headers<br>django-stubs<br>sentry-sdk[django]</pre><p>When other developer tries to run it, they can simply use the command</p><pre>pip install -r requirements.txt</pre><p>Here’s a breakdown of the Sentry configuration:</p><ol><li><strong>dsn</strong>: This is your unique Sentry Data Source Name (DSN). It connects your Django project to Sentry so that errors and performance data can be sent to your Sentry dashboard.</li><li><strong>send_default_pii=True</strong>: This enables the collection of Personally Identifiable Information (PII), such as user IPs and request headers. Useful if you need to track user-specific errors, but be mindful of privacy concerns.</li><li><strong>traces_sample_rate=1.0</strong>: Controls the percentage of transactions captured for performance monitoring.1.0 means 100% of transactions are captured, which is useful for full tracing in development but might be too much for production.</li><li><strong>_experiments={&quot;continuous_profiling_auto_start&quot;: True}</strong>: Enables automatic profiling, helping track CPU and memory usage to optimize performance. This is useful for identifying performance bottlenecks in your application.</li></ol><h3>Configuring Sentry in Django</h3><p>To enable Sentry for error tracking, add the following configuration to your settings.py file:</p><pre>import sentry_sdk<br><br>sentry_sdk.init(<br>    dsn=&quot;https://d53d83da381b3e92d55a2f9399859789@o4509004052627456.ingest.de.sentry.io/4509004056428624&quot;,<br>    # Add data like request headers and IP for users,<br>    # see https://docs.sentry.io/platforms/python/data-management/data-collected/ for more info<br>    send_default_pii=True,<br>    # Set traces_sample_rate to 1.0 to capture 100%<br>    # of transactions for tracing.<br>    traces_sample_rate=1.0,<br>    _experiments={<br>        # Set continuous_profiling_auto_start to True<br>        # to automatically start the profiler on when<br>        # possible.<br>        &quot;continuous_profiling_auto_start&quot;: True,<br>    },<br>)</pre><h3>Testing Sentry Integration</h3><p>To confirm that Sentry is properly set up, you can trigger a test error within your Django project:</p><pre>from sentry_sdk import capture_exception<br><br>def trigger_error():<br>    try:<br>        1 / 0  # Intentional division by zero error<br>    except ZeroDivisionError as e:<br>        capture_exception(e)</pre><p>Add this view to your urls.py for easy access:</p><pre>from django.urls import path<br>from .views import trigger_error<br><br>urlpatterns = [<br>    path(&quot;sentry-debug/&quot;, trigger_error),<br>]</pre><p>Then, visit /sentry-debug/ in your browser. If everything is set up correctly, you should see the error appear in the Sentry dashboard.</p><p>Here’s an example of the dashboard:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mb3IboUomWTEI5LfZzr1VA.png" /></figure><h3>Errors Caught from the Server (Staging Environment)</h3><h4>1. TypeError</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b4HLoTkDGj0rO42qCNR1iA.png" /></figure><p>The TypeError arises because the code is attempting to concatenate (combine) a string (str) with an object of type AccessToken, which is not a string. In Python, the + operator for strings only works when both operands are strings. If one of the operands is not a string (in this case, an AccessToken object), Python raises a TypeError.</p><p><strong>Impact Assesment:</strong></p><ul><li>Only 1 user affected</li><li>Just 1 event recorded</li><li>User IP: 3.238.39.38</li></ul><p>This error is an insignificant one, because it’s actually happened when I try to debug the authentication process. I tried to log the access token to know if the token that FE receive match with the token generated from BE. This happens because refresh.access_token needs to casted to String first to be printed. To solve this, simply cast it using String(refresh.access_token).</p><p>After doing that, the issue on sentry dashboard can now be marked as Resolved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z6JaLfvFUaI_tRyjJhu4Ag.png" /></figure><h4>2. IntegrityError</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BnmLFHehy9-iLgwE5LeCzw.png" /></figure><p>The error is occurring because the FishSampling model have a null value in the fish_dead column of the fish_sampling_fishsampling table, but this column has a not-null constraint. This means the database requires a value for this field, but for some reason, it&#39;s receiving null.</p><p>Looking at the error details:</p><ul><li>Database table: fish_sampling_fishsampling</li><li>Column with issue: fish_dead</li><li>Error: Null value violates the NOT NULL constraint</li><li>Failing row contains: (3885ab72–46a9–4f4b-a37d-c180f8a8dfba, 5, 5, 2025–04–10 02:29:31…, null)</li></ul><p><strong>Impact Assesment:</strong></p><ul><li>The screenshot shows 4 under Users metric, suggesting this error is impacting 4 unique users.</li><li>There are 10 total events/occurrences of this error</li></ul><p>This error happened because of the change on fish sampling feature. The fish dead that was part of the feature, is changed into a single new feature because of the difference it has with other samplings. While the other samplings has target, fish death doesn’t. So making it into a new feature would be better. To resolve this, we simply delete the fish_dead field on fish sampling because it is not used anymore.</p><p>After doing that, the issue on sentry dashboard can now be marked as Resolved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xFPbB0ZtxgW1aCPsyxFlDg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=144d6d79f9b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SOLID Principle in BudidayaPlus Project]]></title>
            <link>https://medium.com/@rzapriono/solid-principle-in-budidayaplus-project-d0d7e540e18a?source=rss-9921022861c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0d7e540e18a</guid>
            <dc:creator><![CDATA[Reza Apriono]]></dc:creator>
            <pubDate>Mon, 24 Mar 2025 00:30:00 GMT</pubDate>
            <atom:updated>2025-04-18T06:36:08.335Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*SBI0a95XZjOTygUx19qh2w.gif" /><figcaption>source: <a href="https://dev.to/ibrahemahmad/solid-principles-in-react-building-maintainable-react-applications-2n1l">https://dev.to/ibrahemahmad/solid-principles-in-react-building-maintainable-react-applications-2n1l</a></figcaption></figure><p>Object-Oriented Principles and SOLID principles are foundational concepts in software engineering that promote clean, maintainable, and scalable code. In this blog, we’ll explore how these concepts are applied in Django application and food sampling data and also forum feature in BudidayaPlus.</p><p>All the commits that implement OO and SOLID are available at:</p><ul><li><a href="https://github.com/PPL-5B/budidayaplus-BE/commits/44-get_data_tabel_perbandingan_jumlah_pakan/">https://github.com/PPL-5B/budidayaplus-BE/commits/44-get_data_tabel_perbandingan_jumlah_pakan/</a></li><li><a href="https://github.com/PPL-5B/budidayaplus-FE/commits/43-tabel_perbandingan_jumlah_pakan/">https://github.com/PPL-5B/budidayaplus-FE/commits/43-tabel_perbandingan_jumlah_pakan/</a></li><li><a href="https://github.com/PPL-5B/budidayaplus-FE/commits/SCRUM-98-ContactUs/">https://github.com/PPL-5B/budidayaplus-FE/commits/SCRUM-98-ContactUs/</a></li><li><a href="https://github.com/PPL-5B/budidayaplus-BE/tree/113-Models_Schema_Repository_Kematian_Ikan">https://github.com/PPL-5B/budidayaplus-BE/commits/113-Models_Schema_Repository_Kematian_Ikan</a></li><li><a href="https://github.com/PPL-5B/budidayaplus-BE/commits/SCRUM-93-READ-FORUM/">https://github.com/PPL-5B/budidayaplus-BE/commits/SCRUM-93-READ-FORUM/</a></li><li><a href="https://github.com/PPL-5B/budidayaplus-FE/commits/SCRUM-136-VoteForum/">https://github.com/PPL-5B/budidayaplus-FE/commits/SCRUM-136-VoteForum/</a></li></ul><h3>Object Oriented Principles</h3><p>OO principles guide how we structure code around objects to model real-world entities effectively:</p><ul><li><strong>Encapsulation</strong>: Bundling data and methods, restricting direct access.</li><li><strong>Abstraction</strong>: Hiding complexity behind simpler interfaces.</li><li><strong>Inheritance</strong>: Reusing code by deriving new classes from existing ones.</li><li><strong>Composition</strong>: Building complex objects by combining simpler ones.</li><li><strong>Polymorphism</strong>: Allowing different objects to be treated uniformly via a common interface.</li></ul><p>Here’s how I implement OO Principles in BudidayaPlus, especially on food sampling backend using Django:</p><h4>1. Encapsulation</h4><pre># food_sampling_service.py<br>class FoodSamplingService:<br>    def __init__(self, repository: FoodSamplingRepository):<br>        self.repository = repository<br><br>    def create_food_sampling(self, pond_id: str, cycle_id: str, reporter_id: int, payload: FoodSamplingCreateSchema):<br>        pond = self.repository.get_pond(pond_id)<br>        reporter = self.repository.get_reporter(reporter_id)<br>        cycle = self.repository.get_cycle(cycle_id)<br>        food_sampling = self.repository.create_food_sampling(<br>            pond=pond, reporter=reporter, cycle=cycle,<br>            food_quantity=payload.food_quantity, recorded_at=payload.recorded_at<br>        )<br>        return food_sampling</pre><p>Encapsulation bundles data and methods into a single unit while restricting direct access. Here, FoodSamplingService encapsulates the repository attribute, initialized in the constructor. External code can’t access repository directly — it must use methods like create_food_sampling. This protects the internal state and ensures controlled interaction, a core tenet of encapsulation.</p><h4>2. Abstraction</h4><pre># food_sampling_repository.py<br>class FoodSamplingRepository:<br>    @staticmethod<br>    def get_pond(pond_id: str) -&gt; Pond:<br>        return get_object_or_404(Pond, pond_id=pond_id)<br><br>    @staticmethod<br>    def create_food_sampling(pond: Pond, reporter: User, cycle: Cycle, food_quantity: int, recorded_at: date):<br>        return FoodSampling.objects.create(<br>            pond=pond, reporter=reporter, cycle=cycle,<br>            food_quantity=food_quantity, recorded_at=recorded_at<br>        )</pre><p>Abstraction hides complex implementation details behind simpler interfaces. FoodSamplingRepository abstracts database operations into clean, static methods. For example, get_pond shields the caller from Django’s get_object_or_404 logic, and create_food_sampling simplifies object creation. This allows the service layer to focus on business logic without worrying about data access specifics.</p><h4>3. Inheritance</h4><pre># models.py<br>from django.db import models<br>import uuid<br><br>class FoodSampling(models.Model):<br>    sampling_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)<br>    cycle = models.ForeignKey(Cycle, on_delete=models.CASCADE)<br>    pond = models.ForeignKey(Pond, on_delete=models.CASCADE)<br>    reporter = models.ForeignKey(User, on_delete=models.CASCADE)<br>    food_quantity = models.FloatField()<br>    recorded_at = models.DateTimeField(auto_now_add=True)</pre><p>Inheritance enables a class to reuse behavior from a parent class. FoodSampling inherits from models.Model, a Django base class, gaining database functionality like saving, querying, and field management without redefining them. This reuse reduces code duplication and leverages Django’s ORM, showcasing inheritance in action.</p><h4>4. Composition</h4><pre># models.py (continued from above)<br>class FoodSampling(models.Model):<br>    cycle = models.ForeignKey(Cycle, on_delete=models.CASCADE)<br>    pond = models.ForeignKey(Pond, on_delete=models.CASCADE)<br>    reporter = models.ForeignKey(User, on_delete=models.CASCADE)</pre><p>Composition builds complex objects by combining simpler ones, favoring “has-a” relationships. FoodSampling uses composition via ForeignKey fields: it “has a” Pond, Cycle, and User (reporter). These relationships form a cohesive entity, combining independent objects to represent a food sampling record, demonstrating composition over inheritance.</p><h3>SOLID Principles</h3><p>SOLID principles ensure OO designs remain robust:</p><ul><li><strong>S</strong>: Single Responsibility Principle</li><li><strong>O</strong>: Open/Closed Principle</li><li><strong>L</strong>: Liskov Substitution Principle</li><li><strong>I</strong>: Interface Segregation Principle</li><li><strong>D</strong>: Dependency Inversion Principle</li></ul><p>The forum feature backend, built with Django, also implements some of the points from SOLID principle. Let’s see how it implements SOLID principles with its existing code.</p><h3>1. Single Responsiblity Principle</h3><pre># forum/api.py<br>...<br>@router.get(&quot;/user_votes&quot;, auth=JWTAuth())<br>def get_votes_by_user(request):<br>    &quot;&quot;&quot;<br>    Mendapatkan semua vote yang diberikan oleh user yang sedang login.<br>    &quot;&quot;&quot;<br>    if not request.user.is_authenticated:<br>        return Response({&quot;error&quot;: &quot;You are not authorized to access this resource.&quot;}, status=403)<br><br>    votes = ForumVote.objects.filter(user=request.user).values(&quot;forum__id&quot;, &quot;forum__description&quot;, &quot;vote_choice&quot;)<br>    return JsonResponse({&quot;votes&quot;: list(votes)}, safe=False)<br><br>@router.get(&quot;/get_replies/{forum_id}&quot;, response=List[ForumOutputSchema], auth=JWTAuth())<br>def get_replies(request, forum_id: UUID):<br>    try:<br>        forum = ForumRepository.get_forum_by_id(forum_id)<br>        replies = ForumRepository.get_replies(forum)<br>        return replies<br>    except Exception:<br>        return Response({&quot;error&quot;: &quot;Forum not found or invalid forum ID&quot;}, status=404)</pre><p>SRP states that a module should have one reason to change. Each function in the api.py file has a single, well-defined responsibility. For example:</p><ul><li>get_votes_by_user: This function is responsible for retrieving all votes cast by the currently logged-in user. It ensures that the votes are fetched from the database and returned in a JSON response.</li><li>get_forums_by_user : This function is responsible for retrieving all forums created by the currently logged-in user. It ensures that the forums are fetched using the ForumRepository and returned.</li></ul><h4><strong>Why it follows SRP:</strong></h4><ul><li>The get_votes_by_user function only handles the task of retrieving and returning user votes. It delegates the database query to the ORM (ForumVote.objects.filter), keeping the function focused on its primary responsibility.</li><li>The get_forums_by_user function only handles the task of retrieving and returning forums created by the user. It delegates the database query to the ForumRepository, ensuring the function remains focused on its primary task.</li></ul><p>This ensures that each function is focused on one task, making the code easier to maintain and understand.</p><h3>2. Open Closed Principle</h3><pre># forum/repositories/forum_repository.py<br><br>class ForumRepository:<br>    @staticmethod<br>    def get_forum_by_id(forum_id: UUID):<br>        return Forum.objects.get(id=forum_id)<br><br>    @staticmethod<br>    def get_forums_by_user(user):<br>        return Forum.objects.filter(user=user)<br><br>    @staticmethod<br>    def list_forums():<br>        return Forum.objects.all()<br><br>    @staticmethod<br>    def create_forum(user, description, parent=None):<br>        return Forum.objects.create(user=user, description=description, parent=parent)</pre><p>OCP requires entities to be open for extension but closed for modification. The ForumRepository class is responsible for encapsulating database operations. If you need to add new functionality (e.g., retrieving forums by a specific category or filtering by date), you can add new methods to the repository without altering the existing ones.</p><h4>Extending the Repository (Example)</h4><p>Suppose you want to add a feature to retrieve forums created within a specific date range. You can add a new method to the ForumRepository without modifying the existing methods.</p><pre>class ForumRepository:<br>    # Existing methods...<br><br>    @staticmethod<br>    def get_forums_by_date_range(start_date, end_date):<br>        &quot;&quot;&quot;<br>        Retrieve forums created within a specific date range.<br>        &quot;&quot;&quot;<br>        return Forum.objects.filter(created_at__range=(start_date, end_date))</pre><p>You can now use the new method in an API endpoint without modifying the existing repository methods.</p><pre>@router.get(&quot;/forums_by_date&quot;, response=List[ForumOutputSchema], auth=JWTAuth())<br>def get_forums_by_date(request, start_date: str, end_date: str):<br>    &quot;&quot;&quot;<br>    Retrieve forums created within a specific date range.<br>    &quot;&quot;&quot;<br>    forums = ForumRepository.get_forums_by_date_range(start_date, end_date)<br>    return forums</pre><h4>Why It Follows OCP:</h4><ul><li>The ForumRepository class is <strong>open for extension</strong> because you can add new methods like get_forums_by_date_range without altering the existing methods.</li><li>It is <strong>closed for modification</strong> because the existing methods (get_forum_by_id, get_forums_by_user, etc.) remain unchanged, ensuring that existing functionality is not affected.</li></ul><p>This approach keeps the repository class flexible and maintainable while adhering to the <strong>Open/Closed Principle</strong>.</p><h3>3. Dependency Inversion Principle</h3><pre># forum/api.py<br>@router.put(&quot;/{forum_id}&quot;, response=ForumOutputSchema, auth=JWTAuth())<br>def update_forum(request, forum_id: UUID, data: ForumUpdateSchema):<br>    &quot;&quot;&quot;<br>    Endpoint to update the description of a forum.<br>    &quot;&quot;&quot;<br>    forum = ForumRepository.get_forum_by_id(forum_id)<br>    <br>    if request.user != forum.user:<br>        return {&quot;error&quot;: &quot;You are not authorized to update this forum post.&quot;}, 403<br>    <br>    updated_forum = ForumRepository.update_forum(forum_id, data.description)<br>    return updated_forum</pre><pre># forum/repositories/forum_repository.py<br>class ForumRepository:<br>    @staticmethod<br>    def update_forum(forum_id: UUID, description: str):<br>        &quot;&quot;&quot;<br>        Update the description of a forum.<br>        &quot;&quot;&quot;<br>        forum = Forum.objects.get(id=forum_id)<br>        forum.description = description<br>        forum.save()<br>        return forum</pre><p>DIP requires high-level modules to depend on abstractions. The forum code already demonstrates adherence to this principle by relying on the ForumRepository for database operations instead of directly interacting with the database models. This abstraction decouples the API logic from the database implementation, making the code more flexible and testable.</p><h4>How It Follows DIP:</h4><ol><li><strong>High-Level Module (API Function):</strong></li></ol><ul><li>The update_forum function is the high-level module that handles the request and response logic.</li><li>It does not directly interact with the database models (e.g., Forum.objects.get or Forum.save).</li></ul><p><strong>2. Low-Level Module (Repository):</strong></p><ul><li>The ForumRepository is the low-level module that encapsulates the database operations.</li><li>The ForumRepository.update_forum method is responsible for updating the forum in the database.</li></ul><p><strong>3. Abstraction:</strong></p><ul><li>The API function depends on the abstraction provided by the ForumRepository, not on the concrete implementation of the database models.</li></ul><h4>Why It Follows DIP:</h4><ul><li>The update_forum API function does not depend on the Forum model directly. Instead, it relies on the ForumRepository abstraction.</li><li>If the database implementation changes (e.g., switching from Django ORM to another database library), only the ForumRepository needs to be updated, and the API function remains unchanged.</li></ul><h4>Benefits of DIP in This Example:</h4><ol><li><strong>Decoupling:</strong> The API logic is decoupled from the database implementation, making the code easier to maintain and test.</li><li><strong>Flexibility:</strong> Changes to the database logic (e.g., adding logging or validation) can be made in the repository without affecting the API layer.</li><li><strong>Testability:</strong> The ForumRepository can be mocked during testing, allowing the API function to be tested independently of the database.</li></ol><h3>Application and Benefits of SOLID Principle in BudidayaPlus</h3><p>SOLID principles guide the backend development of our BudidayaPlus project, ensuring clean, maintainable, and scalable code. In this section, we’ll explore how these principles are applied in the FoodSamplingService class, specifically in the get_latest_food_sampling method, and highlight the benefits of these practices during changes, referencing a commit that demonstrates this in practice.</p><p>The get_latest_food_sampling method retrieves the most recent food sampling data for a given cycle and pond, ensuring proper authorization and data validation. Here’s the relevant code snippet after the change:</p><pre># food_sampling/services/food_sampling_service.py<br>class FoodSamplingService:<br>    DATA_NOT_FOUND = &quot;Data tidak ditemukan&quot;<br>    INVALID_FOOD_QUANTITY = &quot;Input kuantitas makanan tidak valid&quot;<br>    UNAUTHORIZED_ACCESS = &quot;Anda tidak memiliki akses untuk melihat data ini&quot;<br><br>    food_sampling_target = {i: {&#39;food_quantity&#39;: i} for i in range(1, 31)}<br><br>    def __init__(self, repository: FoodSamplingRepository):<br>        self.repository = repository<br><br>    def check_cycle_active(self, cycle: Cycle):<br>        today = datetime.now().date()<br>        if not (cycle.start_date &lt;= today &lt;= cycle.end_date):<br>            raise HttpError(400, self.DATA_NOT_FOUND)<br><br>    def authorize_user(self, user, pond: Pond):<br>        supervisor = get_supervisor(user)<br>        if pond.owner != supervisor:<br>            raise HttpError(401, self.UNAUTHORIZED_ACCESS)<br><br>    def get_food_sampling(self, cycle_id: str, pond_id: str, sampling_id: str, user) -&gt; FoodSampling:<br>        cycle = self.repository.get_cycle(cycle_id)<br>        pond = self.repository.get_pond(pond_id)<br>        food_sampling = self.repository.get_food_sampling_by_id(sampling_id)<br><br>        self.check_cycle_active(cycle)<br><br>        if food_sampling.cycle != cycle or food_sampling.pond != pond:<br>            raise HttpError(404, self.DATA_NOT_FOUND)<br><br>        self.authorize_user(user, pond)<br><br>        target_food_quantity = self.food_sampling_target.get(1, {}).get(&#39;food_quantity&#39;, 0)<br>        food_sampling.target_food_quantity = target_food_quantity<br><br>        return food_sampling<br><br>    def get_latest_food_sampling(self, cycle_id: str, pond_id: str, user) -&gt; FoodSampling:<br>        cycle = self.repository.get_cycle(cycle_id)<br>        pond = self.repository.get_pond(pond_id)<br><br>        self.check_cycle_active(cycle)<br><br>        food_sampling = self.repository.get_latest_food_sampling(pond, cycle)<br>        if food_sampling is None:<br>            raise HttpError(404, self.DATA_NOT_FOUND)<br><br>        try:<br>            self.authorize_user(user, pond)<br>        except:<br>            raise HttpError(401, self.UNAUTHORIZED_ACCESS)<br><br>        target_food_quantity = self.food_sampling_target.get(1, {}).get(&#39;food_quantity&#39;, 0)<br>        food_sampling.target_food_quantity = target_food_quantity<br><br>        return food_sampling</pre><h3>Applying SOLID Principles</h3><p>This code demonstrates adherence to the <strong>Single Responsibility Principle (SRP)</strong> and <strong>Open/Closed Principle (OCP)</strong>:</p><ul><li><strong>Single Responsibility Principle (SRP)</strong>: The get_latest_food_sampling method has a clear, singular responsibility: to retrieve and validate the latest food sampling data for a specific pond and cycle. It delegates tasks like cycle validation (check_cycle_active), authorization (authorize_user), and data retrieval (get_latest_food_sampling) to other components, keeping its logic focused and modular. Each method or class it interacts with (e.g., FoodSamplingRepository) also adheres to SRP by handling only its designated task, such as querying data or managing authorization.</li><li><strong>Open/Closed Principle (OCP)</strong>: The FoodSamplingService is designed to be open for extension but closed for modification. The method integrates new functionality, like assigning target_food_quantity, without altering the core logic of data retrieval or authorization. This extensibility allows new features to be added (e.g., additional data processing) without disrupting existing behavior.</li></ul><h4>The Change: Adding Target Food Quantity Assignment</h4><p>The <a href="https://github.com/PPL-5B/budidayaplus-BE/commit/e24f24c9b0c8301c29c157e11584e6fc61f2acd0">commit </a>modified the get_latest_food_sampling method to include the assignment of target_food_quantity to the food_sampling object. The change was localized to the service layer and did not affect the API endpoints, demonstrating the robustness of the design. The diff for this commit includes:</p><pre>+        target_food_quantity = self.food_sampling_target.get(1, {}).get(&#39;food_quantity&#39;, 0)<br>+        food_sampling.target_food_quantity = target_food_quantity</pre><p>This addition retrieves a default food quantity from food_sampling_target and assigns it to the food_sampling object before returning it.</p><h3>Benefits When Changes Occur</h3><p>Applying SOLID principles made this change seamless and maintainable:</p><ul><li><strong>SRP Benefit</strong>: The get_latest_food_sampling method’s single responsibility ensured that adding the target_food_quantity assignment didn’t require changes to unrelated parts of the codebase, such as the repository or API layers. The service layer encapsulated the logic for processing the food sampling data, keeping the change isolated and preventing ripple effects across the system.</li><li><strong>OCP Benefit</strong>: The method’s design allowed for the extension of functionality — adding the target_food_quantity assignment — without modifying the existing logic for cycle validation, authorization, or data retrieval. The API endpoints consuming this service remained unaffected, as the change was confined to the service layer, showcasing how the system is open for extension but closed for modification.</li></ul><p>SOLID principles, as applied in the get_latest_food_sampling method of FoodSamplingService, streamline development and maintenance in the BudidayaPlus backend. By adhering to SRP and OCP, the commit to add target_food_quantity assignment was straightforward, localized, and did not impact the API layer, as evidenced in the backend commit history. This approach ensures the project remains flexible and efficient, a critical advantage during ongoing development.</p><h3>Best Practices of Backend Development Using Django Ninja</h3><p>Django Ninja is a powerful, fast, and intuitive framework for building APIs with Django, leveraging Python’s type hints and a schema-driven approach. To create scalable, maintainable, and secure backend applications with Django Ninja, adopting best practices is essential. These practices will help you harness Django Ninja’s full potential while ensuring clean code and robust functionality.</p><h4>1. Use of Schemas for Data Validation</h4><pre># forum/api.py<br>@router.post(&quot;/create&quot;, response=ForumOutputSchema, auth=JWTAuth())<br>def create_forum(request, data: ForumCreateSchema):<br>    # Validates the incoming data using ForumCreateSchema<br>    new_forum = ForumRepository.create_forum(<br>        user=request.user,<br>        description=data.description,<br>        parent=None<br>    )<br>    return new_forum</pre><ul><li>The forum feature uses schemas like ForumCreateSchema, ForumOutputSchema, and ForumReplySchema to validate and structure incoming and outgoing data. This ensures that the API adheres to a consistent data format and reduces the risk of invalid data being processed.</li></ul><pre># forum/schemas.py<br>class ForumCreateSchema(Schema):<br>    &quot;&quot;&quot;<br>    Schema for creating a new Forum entry.<br>    Optionally includes a parent_id to indicate this post is a reply.<br>    &quot;&quot;&quot;<br>    description: str<br>    parent_id: Optional[UUID4] = None</pre><ul><li><strong>Best Practice:</strong> Always use schemas for request and response validation to ensure data consistency and reduce errors.</li></ul><h4>2. Authentication and Authorization</h4><pre># forum/api.py<br>@router.delete(&quot;/delete/{forum_id}&quot;, auth=JWTAuth())<br>def delete_forum(request, forum_id: UUID):<br>    if forum.user != request.user:<br>        return Response({&quot;error&quot;: &quot;You are not authorized to delete this forum.&quot;}, status=403)</pre><ul><li>The code uses JWTAuth() to secure endpoints, ensuring that only authenticated users can access certain resources. Additionally, custom authorization checks are implemented (e.g., verifying if the user is authorized to delete or update a forum).</li><li><strong>Best Practice:</strong> Use authentication mechanisms like JWT and implement custom authorization checks to secure sensitive operations.</li></ul><h4>3. Separation of Concerns</h4><pre># forum/repositories/forum_repository.py:<br>class ForumRepository:<br>    @staticmethod<br>    def get_forum_by_id(forum_id: UUID):<br>        return get_object_or_404(Forum, id=forum_id)</pre><ul><li>The code separates business logic into a ForumRepository class, which handles database operations. This keeps the API layer clean and focused on request handling and response generation.</li><li><strong>Best Practice:</strong> Use repositories or service layers to encapsulate business logic and database operations, making the code more modular and testable.</li></ul><h4>4. Error Handling</h4><pre>try:<br>    parent_forum = ForumRepository.get_forum_by_id(UUID(data.parent_id))<br>except Exception:<br>    return Response({&quot;error&quot;: &quot;Invalid parent forum ID&quot;}, status=400)</pre><ul><li>The code uses proper error handling with meaningful error messages and appropriate HTTP status codes (e.g., 400 Bad Request, 403 Forbidden, 404 Not Found).</li><li><strong>Best Practice:</strong> Always handle exceptions gracefully and return meaningful error messages with appropriate HTTP status codes.</li></ul><h4>5. Use of Properties for Model Logic</h4><pre>@property<br>def upvotes(self):<br>    return self.votes.filter(vote_choice=&#39;up&#39;).count()</pre><ul><li>The Forum model uses properties like upvotes and downvotes to encapsulate logic related to vote counts. This keeps the logic close to the data it operates on</li><li><strong>Best Practice:</strong> Use model properties to encapsulate logic related to the model, improving code readability and maintainability.</li></ul><h4>6. Use of UUIDs for Identifiers</h4><pre>id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)</pre><ul><li>The Forum and ForumVote models use UUIDField as the primary key, which is more secure and scalable than integer-based IDs.</li><li><strong>Best Practice:</strong> Use UUIDs for identifiers to improve security and scalability, especially in distributed systems.</li></ul><h3>Best Practices of Front End Development Using Next js and TypeScript</h3><p>Next.js, paired with TypeScript, offers a robust framework for building modern, scalable, and type-safe front-end applications. This powerful combination enables developers to create performant, SEO-friendly, and maintainable web applications with ease. These practices will help you leverage Next.js and TypeScript to deliver clean, efficient, and high-quality code.</p><h4>1. Type Safety with TypeScript</h4><pre>interface ForumCardProps {<br>  forum: Forum;<br>  onDeleteSuccess?: (id: string) =&gt; void;<br>  onVoteSuccess?: (updatedForum: Forum) =&gt; void;<br>}</pre><ul><li><strong>Strongly Typed Props</strong>: The ForumCard component uses a ForumCardProps interface to define the expected props, ensuring type safety and better developer experience.</li><li><strong>Reusable Types</strong>: The Forum type is imported from a shared type definition (@/types/forum), promoting reusability and consistency across the codebase.</li></ul><h4>2. Component-Based Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*IpVwUB7j0gRLclJNFqz1xg.png" /><figcaption>Forum feature components</figcaption></figure><ul><li><strong>Reusable Components</strong>: The ForumCard component is modular and reusable, encapsulating all logic and UI related to a single forum card.</li><li><strong>Separation of Concerns</strong>: The DeleteForumContainer is a separate component, handling the delete modal logic. This keeps the ForumCard component focused on its primary responsibilities.</li></ul><h4>3. Hooks for State Management</h4><pre>const {<br>  upvotes,<br>  downvotes,<br>  userVote,<br>  isLoading,<br>  isInitialized,<br>  handleUpvote,<br>  handleDownvote,<br>  handleCancelVote,<br>} = useVote(forum.id);</pre><ul><li><strong>Custom Hooks</strong>: The useVote hook abstracts voting logic (e.g., upvotes, downvotes, canceling votes). This adheres to the <strong>DRY (Don’t Repeat Yourself)</strong> principle and keeps the component clean.</li></ul><h4>4. Conditional Rendering</h4><pre>if (!isInitialized) {<br>  return &lt;div className=&quot;w-full border rounded-lg p-4 shadow-md bg-white&quot;&gt;Loading...&lt;/div&gt;;<br>}</pre><ul><li><strong>Loading States</strong>: The component displays a loading placeholder (Loading...) when the data is not initialized, improving user experience.</li></ul><h4>5. Event Handling with Callbacks</h4><pre>onDeleteSuccess?.(forum.id);<br>onVoteSuccess?.({<br>  ...forum,<br>  upvotes,<br>  downvotes,<br>});</pre><ul><li><strong>Callback Props</strong>: The onDeleteSuccess and onVoteSuccess props allow parent components to handle events (e.g., updating the forum list after a delete or vote) without tightly coupling the logic.</li></ul><h4>6. Error Handling</h4><pre>catch (error) {<br>  console.error(&#39;Error voting:&#39;, error);<br>}</pre><ul><li><strong>Error Logging</strong>: Errors during voting are caught and logged to the console, preventing the app from crashing.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0d7e540e18a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>