Skip to content
CAI
Software that uses CAICheck a score

gabriellopes00/clean-typescript-api

51.0

Adequate · 21 September 2026

2k

lines of production code

TypeScript

primary language

4

measurements over time

CAI band scale
CAI trend line
CAI lens gauges

What this system is

This is a Node.js backend application that manages user accounts and survey data, implemented using a clean architecture with distinct domain, data, and presentation layers. It provides REST and GraphQL APIs for user authentication, survey creation, and result tracking, backed by MongoDB. The system enforces strict validation, security headers, and error handling to ensure reliable data persistence and access control.

Features

Add DbLoadAccountByToken use case and its tests

Introduces the DbLoadAccountByToken class, which implements the LoadAccountByToken interface to load an account by token. The implementation decrypts the access token and then queries the LoadAccountByTokenRepository, returning null if decryption fails or if the repository returns null. A corresponding test suite (db-load-account-by-token.spec.ts) is added to verify the interaction with the Decrypter and the repository, including edge cases like null returns and thrown errors.

src/data/usecases/load-account · high confidence

Add GraphQL resolvers for login, signup, and survey features

The application now exposes GraphQL endpoints for user authentication and survey management. Users can authenticate via a login query and register via a signup mutation. Additionally, the system supports querying available surveys, as well as loading and saving survey results through dedicated query and mutation operations.

src/main/graphql/resolvers · high confidence

Add mock data factories for account, survey, and survey result models

New mock data factories are introduced in the domain layer to support testing and development. Specifically, \mock-account.ts\ provides \fakeAccountModel\ and related parameters for account operations, \mock-survey.ts\ supplies \fakeSurveyModel\ and \fakeSurveysModel\ arrays for survey data, and \mock-survey-result.ts\ offers \fakeSurveyResultModel\ and \fakeSurveyResultParams\ for survey result interactions. These files standardize the structure of test fixtures for accounts, surveys, and their associated results.

src/domain/mocks · high confidence

Add survey loading by ID use case

Introduced the DbLoadSurveyById use case, which retrieves a survey by its ID via the LoadSurveyByIdRepository. The implementation ensures that the repository is called with the correct ID, returns the survey on success, and propagates errors if the repository throws.

src/data/usecases/load-survey-by-id · high confidence

Added Bcrypt and JWT cryptography adapters

New cryptographic implementations have been introduced to the infrastructure layer. The BcryptAdapter provides password hashing and comparison capabilities, while the JwtAdapter enables JSON Web Token encryption and decryption. These adapters wrap the 'bcrypt' and 'jsonwebtoken' libraries respectively, exposing standardized interfaces for secure data processing.

src/infra/cryptography · high confidence

Added DbAddSurvey use case and its tests

Introduced the DbAddSurvey class, which implements the AddSurvey interface by delegating to the AddSurveyRepository. The implementation accepts AddSurveyParams and forwards the add call to the repository. A corresponding test suite was added to verify that the use case correctly passes parameters to the repository and propagates errors.

src/data/usecases/add-survey · high confidence

Added MongoDB log repository implementation and tests

A new MongoLogRepository class has been introduced to handle error logging to MongoDB, implementing the LogErrorRepository interface by inserting error stack traces and timestamps into the 'errors' collection. Corresponding unit tests have been added to verify that error logs are correctly persisted in the database.

src/infra/db/mongodb/log · high confidence

Added logging decorator for controller error handling

A new LogControllerDecorator was introduced to automatically log server errors (status 500) from controllers. This decorator wraps a controller and, upon receiving a server error response, forwards the error stack trace to a LogErrorRepository for logging purposes, ensuring consistent error tracking across the application.

src/main/decorators · medium confidence

Adds TypeScript type for Express Request

A new TypeScript declaration file, \src/@types/express-request.d.ts\, was added to extend the Express \Request\ interface. This change introduces an optional \accountId\ property to the request object, enabling type-safe access to the account identifier in Express request handlers.

src/@types · high confidence

Centralized factory layer for dependency injection

The \src/main/factories\ directory now provides a comprehensive set of factory functions that wire together controllers, validations, and use cases. This includes factories for login, signup, and survey operations (add, load, save results), each assembling the necessary repositories, adapters (like Bcrypt and JWT), and validation components. This change introduces a consistent, centralized way to instantiate application components, ensuring that all entry points in the main layer use the same underlying implementations.

src/main/factories · high confidence

Implement MongoDB repository for saving and loading survey results

Added the MongoSurveyResultRepository class, which implements the SaveSurveyResultsRepository and LoadSurveyResultRepository interfaces. This provides the database layer for persisting user answers to surveys and retrieving aggregated survey result statistics, including answer counts, percentages, and the current user's specific response.

src/infra/db/mongodb/survey-result · high confidence

Implemented MongoDB repository for survey data access

Added the MongoSurveyRepository class, which implements the AddSurveyRepository, LoadSurveyRepository, and LoadSurveyByIdRepository interfaces. This repository handles inserting new surveys, loading all surveys for an account (including a computed didAnswer field based on user responses), and retrieving a specific survey by its ID, using MongoHelper for database interactions.

src/infra/db/mongodb/survey · high confidence

Implemented database-backed survey loading with repository integration

Added the DbLoadSurvey use-case implementation which integrates with the LoadSurveyRepository to fetch a list of surveys for a given account ID. The implementation delegates to the repository's loadAll method and returns the resulting SurveyModel array. A corresponding test suite was added to verify that the repository is called correctly, that the list of surveys is returned on success, and that errors from the repository are propagated.

src/data/usecases/load-survey · high confidence

Initial Express server configuration and modular setup

The application's server entry point and configuration layer have been established. The server now connects to MongoDB before listening for requests. The Express app is configured with body parsing, CORS, and default JSON content-type headers. New capabilities include serving static files, a Swagger UI for API documentation, and an Apollo GraphQL server. Additionally, a custom 404 handler and a no-cache middleware are integrated into the request pipeline.

src/main/config · high confidence

Initial GraphQL schema and authentication directive

The application now exposes a GraphQL API with type definitions for login, signup, surveys, and survey results. A new \@auth\ directive enforces authentication on protected fields, ensuring that only authenticated users can access survey data and submit results.

src/main/graphql/type-defs · medium confidence

Introduce MongoDB helper and query builder utilities

Added a new MongoDB helper module that manages client connections, including automatic reconnection when the client is down, and provides a map function to transform MongoDB's '\_id' field to 'id' in returned data. Also added a QueryBuilder class that constructs MongoDB aggregation pipeline stages (match, unwind, lookup, project, group, sort) for building complex queries.

src/infra/db/mongodb/helpers · high confidence

Introduces domain models and use cases for account management, authentication, and survey interactions

Adds new domain models for accounts, surveys, and survey results, alongside corresponding use cases (AddAccount, AddSurvey, Authentication, LoadAccountByToken, LoadSurvey, LoadSurveyById, LoadSurveyResult, SaveSurveyResults) that define the core business logic for user registration, authentication, and survey participation.

src/domain/usecases · high confidence

Introduces new repository interfaces for survey data access

The survey data layer now defines five new repository interfaces—AddSurveyRepository, LoadSurveyByIdRepository, LoadSurveyRepository, LoadSurveyResultRepository, and SaveSurveyResultsRepository. These interfaces specify the contracts for adding, loading (by ID and all), and saving survey results, establishing the data-access layer required for the new survey functionality.

src/data/interfaces/db/survey · high confidence

New adapter layer for Express and Apollo Server

Added three new adapter files in src/main/adapters to bridge the application's internal controllers with external HTTP frameworks. The express-routes.ts file maps HTTP requests to controllers and returns JSON responses, while express-middleware.ts handles middleware logic for Express. Additionally, apollo-server-resolver-adapter.ts provides a resolver adapter for Apollo Server, handling HTTP status codes and errors. These adapters standardize how the application interacts with Express and Apollo Server.

src/main/adapters · high confidence

New authentication and survey management endpoints

The application now exposes new API routes for user authentication and survey management. Users can authenticate via new login and signup endpoints. For surveys, the system enforces access control: the GET /surveys and PUT /surveys/:surveyId/results endpoints require a valid access token, returning 403 if missing. The POST /surveys endpoint requires an 'AdmAuth' (admin) token, returning 403 without one. Additionally, the GET /surveys/:surveyId/results endpoint is now available to retrieve survey results.

src/main/routes · high confidence

New authentication middleware for API protection

A new AuthMiddleware has been introduced to validate user sessions by verifying access tokens. It ensures that requests include a valid token, calls the LoadAccountByToken use case to validate the account, and returns appropriate HTTP responses: 403 Forbidden for missing or invalid tokens, 200 OK for successful validation, and 500 Internal Server Error if the validation service throws an exception.

src/presentation/middlewares · high confidence

New database repository interfaces for account and logging

The codebase introduces new repository interfaces to define the data access layer for account operations and error logging. Specifically, it adds interfaces for storing and loading access tokens, adding and loading account data by email or token, and logging errors. These interfaces establish the contracts for database interactions, such as \AddAccountRepository\ for creating accounts, \LoadAccountRepository\ for retrieving accounts by email, \LoadAccountByTokenRepository\ for authentication flows, \AccessTokenRepository\ for token management, and \LogErrorRepository\ for error tracking.

src/data/interfaces/db/account · high confidence

New login and signup controllers with authentication integration

The application now includes new Login and SignUp controllers that handle user authentication and account creation. The SignUpController validates input, creates an account, and returns an access token on success, while also handling errors such as duplicate emails (403) and server failures (500). The LoginController similarly validates input, authenticates users, and returns an access token, with appropriate error handling for invalid credentials (401) and server errors (500). Both controllers integrate with domain use cases (AddAccount, Authenticator) and validation services, ensuring a consistent API response structure.

src/presentation/controllers/signup · medium confidence

New middleware infrastructure and security headers

The application now includes a dedicated middleware layer that enforces security and content handling headers. A no-cache middleware has been added to prevent browser and proxy caching of responses. CORS is explicitly enabled to allow cross-origin requests. Additionally, the app enforces JSON content types and parses request bodies as JSON. These changes ensure consistent header management and secure, cache-free responses across the application.

src/main/middlewares · high confidence

New validation layer with composite and specific validators

The validation logic has been restructured into a dedicated layer, introducing a ValidationComposite that chains multiple validation rules. Specific validators for required fields, email format, and field comparison are now implemented as distinct classes (RequiredFieldValidation, EmailValidation, CompareFieldsValidation) that implement a shared Validation interface. This change provides a more modular and testable approach to input validation, allowing for flexible composition of validation rules.

src/validation · high confidence

Removals

Removed empty project setup files

The placeholder 'Node Project Setup' module and its associated test file have been removed from the src directory. This cleanup eliminates the default scaffolded code and its corresponding test suite, indicating the removal of initial boilerplate in favor of actual application logic.

src · high confidence

Behavioural changes

Add Survey controller enforces validation and returns appropriate HTTP status codes

The AddSurveyController now validates incoming survey requests before processing. If validation fails, it returns a 400 Bad Request. On success, it returns a 204 No Content. If the underlying AddSurvey use case throws an error, the controller returns a 500 Internal Server Error. The controller also injects the current date into the data passed to the AddSurvey use case.

src/presentation/controllers/survey/add-survey · high confidence

Add email validation adapter

A new EmailValidatorAdapter is introduced in the infrastructure layer to handle email validation. This adapter wraps the 'validator' library's isEmail function, implementing the EmailValidator interface to provide a consistent validation mechanism for email addresses.

src/infra/validation · high confidence

Implemented database-backed authentication use case with comprehensive test coverage

Added the DbAuthentication use case, which orchestrates the login flow by loading the account by email, verifying the password via HashComparer, generating an access token via Encrypter, and storing the token in the database. The implementation ensures that errors from any of these dependencies (LoadAccountRepository, HashComparer, Encrypter, or AccessTokenRepository) are propagated as thrown exceptions, while returning null for invalid credentials or missing accounts. The entry also includes a full suite of unit tests for db-authentication.spec.ts, verifying correct method calls, error handling, and the inclusion of the user's name in the authentication response.

src/data/usecases/authentication · high confidence

Introduces dedicated interfaces for cryptographic operations

The data layer now defines specific interfaces for encryption, decryption, hashing, and hash comparison. This separation clarifies the contract for each cryptographic function, allowing implementations to be swapped or updated independently.

src/data/interfaces/cryptography · high confidence

MongoDB account repository implements token-based access with role-based filtering

The MongoAccountRepository now implements the LoadAccountByTokenRepository interface, allowing accounts to be retrieved by access token. The loadByToken method supports an optional role parameter and includes logic to grant access to users with the 'adm' role, ensuring that administrative users can access any route via their token.

src/infra/db/mongodb/account · medium confidence

Prevent duplicate account creation by checking for existing email

The DbAddAccount use case now checks for an existing account via LoadAccountRepository before creating a new one. If an account with the same email already exists, the operation returns null instead of creating a duplicate. This behavioral change ensures that the system prevents duplicate account registrations by validating the email address before hashing the password and calling the AddAccountRepository.

src/data/usecases/add-account · high confidence

Save survey result now returns the saved data

The DbSaveSurveyResults use case has been updated to return the saved SurveyResultsModel after successfully saving a survey result. Previously, the save operation likely did not return the resulting data, meaning callers could not immediately access the saved state without making a separate call. This change ensures that the save method returns the SurveyResultsModel, streamlining workflows that need the saved data immediately after the save operation.

src/data/usecases/save-survey-result · high confidence

Standardized HTTP response helpers for consistent status codes

A new set of HTTP response helper functions has been introduced to standardize how the application constructs HTTP responses. This includes specific handlers for common status codes such as 403 (Forbidden), 400 (Bad Request), 401 (Unauthorized), 500 (Server Error), 200 (OK), and 204 (No Content). Controllers can now use these utilities to return consistent response objects, ensuring that endpoints like the sign-up and survey creation flows return the correct status codes (e.g., 403 for account creation failures and 204 for successful survey creation) as intended by the recent controller updates.

src/presentation/helpers · medium confidence

Standardized error classes for HTTP response mapping

The presentation layer now uses a set of specific error classes to map internal states to HTTP responses. A new AccessDeniedError is introduced to handle 403 Forbidden responses, while UnauthorizedError, MissingParamError, InvalidParamError, EmailAlreadyInUseError, and ServerError are standardized to support 401, 400, and 500 status codes respectively. These changes ensure that controllers return appropriate HTTP status codes based on the specific error type thrown during request processing.

src/presentation/errors · high confidence

Standardized presentation-layer interfaces for controllers, middleware, and validation

The presentation layer now uses explicit TypeScript interfaces to define contracts for HTTP responses, controllers, middleware, and validation logic. Specifically, HttpResponse and HttpRequest interfaces are introduced to standardize the shape of HTTP interactions, while Controller, Middleware, and Validation interfaces provide typed contracts for request handling, middleware execution, and validation operations. This change improves type safety and consistency across the presentation layer by centralizing interface definitions and ensuring all components adhere to these standardized contracts.

src/presentation/interfaces · high confidence

Survey loading controller now returns 204 for empty results

The LoadSurveyController has been refactored to use a new request interface and now returns a 204 (No Content) HTTP status when the survey list is empty, rather than an empty array or error. This change ensures that clients receive a distinct signal for 'no surveys found' versus 'surveys found', improving API clarity for empty states.

src/presentation/controllers/survey/load-survey · high confidence

Survey result controllers enforce validation and error handling

The LoadSurveyResult and SaveSurveyResult controllers now enforce strict validation and error handling. LoadSurveyResult returns 403 for invalid survey IDs and 500 on internal errors. SaveSurveyResult validates that the provided answer is one of the survey's valid options, returning 403 for invalid answers, and returns 500 on internal errors. Both controllers ensure correct data is passed to their respective use cases and return appropriate HTTP status codes.

src/presentation/controllers/survey-result · high confidence

Survey result loading now falls back to survey details when no results exist

The DbLoadSurveyResults use case has been updated to handle cases where no survey results are found in the database. Previously, the system might have returned null or failed silently. Now, if the primary LoadSurveyResultRepository returns null, the system automatically falls back to the LoadSurveyByIdRepository to construct a survey result object using the survey's metadata (id, date, question, and answers). This ensures that users always receive a structured survey result object, even if no specific answers have been recorded yet, with default values for counts and percentages.

src/data/usecases/load-survey-result · high confidence

Updated project configuration and tooling setup

The project's configuration files have been updated to reflect a new directory structure and testing setup. The TypeScript path aliases in tsconfig.json and babel.config.js were changed from generic names (like @controllers, @models) to domain-driven names (@data, @domain, @infra, etc.). Additionally, Jest configuration was modified to use a MongoDB memory server preset for integration tests, and coverage collection was restricted to exclude interface and main entry-point files. The ESLint configuration was also updated to include TypeScript-specific parsers and rules, and the print width for Prettier was increased to 100 characters.

(repo-wide) · high confidence

Test coverage

Added integration tests for GraphQL login and signup flows

Added new integration tests for the GraphQL API, specifically covering the login query and signup mutation. The test suite verifies that the login query returns an unauthorized error for invalid credentials and returns an account object for valid credentials, while the signup mutation is tested to ensure it creates a new account successfully.

src/main/graphql/\\tests\\_ · high confidence_

Dependencies

Upgrade project dependencies and tooling

The project's dependencies have been updated, including Babel packages (e.g., @babel/core to 7.13.14), Jest, and various type definitions. New dependencies such as apollo-server-express, graphql, jsonwebtoken, and validator have been added, alongside dev dependencies like coveralls and supertest. The package.json scripts have also been expanded to support Docker, debugging, and CI/CD workflows.

(dependencies) · medium confidence

Written by watchdog.canine.dev from the codebase's own history, inside the signed delivery this page is composed from.

How this codebase got here

Score

  • CAI 53 → 51 (-2.4)
  • Rubric changed (rubric-2026.08.19 → rubric-2026.09.15) — scores are not directly comparable.

Lenses

  • Code Health 96 → 99 (+2.2)
  • Architecture 100 → 84 (-15.9)
  • Maturity 54 → 57 (+2.8)
  • Readiness 33 → 30 (-3.8)
  • Security 74 → 79 (+5.5)

Resolved (57)

  • Coverage not included — suite not readable by the collector
  • Critical CVE: [GHSA redacted] (yarn.lock)
  • Critical CVE: [GHSA redacted] (yarn.lock)
  • Critical CVE: [GHSA redacted] (yarn.lock)
  • Critical CVE: [GHSA redacted] (yarn.lock)
  • Critical CVE: [GHSA redacted] (yarn.lock)
  • Critical CVE: [GHSA redacted] (yarn.lock)
  • Critical CVE: [GHSA redacted] (yarn.lock)
  • Dependency hygiene not measured — dependency manifest found but not parsed for hygiene
  • High CVE: [GHSA redacted] (yarn.lock)
  • High CVE: [GHSA redacted] (yarn.lock)
  • High CVE: [GHSA redacted] (yarn.lock)
  • High CVE: [GHSA redacted] (yarn.lock)
  • High CVE: [GHSA redacted] (yarn.lock)
  • High CVE: [GHSA redacted] (yarn.lock)
  • High CVE: [GHSA redacted] (yarn.lock)
  • High CVE: [GHSA redacted] (yarn.lock)
  • High CVE: [GHSA redacted] (yarn.lock)
  • High CVE: [GHSA redacted] (yarn.lock)
  • High CVE: [GHSA redacted] (yarn.lock)
  • …and 37 more

New (99)

  • Critical CVE: [GHSA redacted] (yarn.lock)
  • Critical CVE: [GHSA redacted] (yarn.lock)
  • Critical CVE: [GHSA redacted] (yarn.lock)
  • Critical CVE: [GHSA redacted] (yarn.lock)
  • Critical CVE: [GHSA redacted] (yarn.lock)
  • Critical CVE: [GHSA redacted] (yarn.lock)
  • Critical CVE: [GHSA redacted] (yarn.lock)
  • Documentation: no contributor guidance (README.md)
  • Documentation: no installation or build instructions (README.md)
  • Documentation: no usage examples (README.md)
  • High CVE: [GHSA redacted] (yarn.lock)
  • High CVE: [GHSA redacted] (yarn.lock)
  • High CVE: [GHSA redacted] (yarn.lock)
  • High CVE: [GHSA redacted] (yarn.lock)
  • High CVE: [GHSA redacted] (yarn.lock)
  • High CVE: [GHSA redacted] (yarn.lock)
  • High CVE: [GHSA redacted] (yarn.lock)
  • High CVE: [GHSA redacted] (yarn.lock)
  • High CVE: [GHSA redacted] (yarn.lock)
  • High CVE: [GHSA redacted] (yarn.lock)
  • …and 79 more

Written by watchdog.canine.dev from the codebase's own history, inside the signed delivery this page is composed from.

Survey your own repository

gabriellopes00/clean-typescript-api was measured the same way every project in this corpus was: the same rubric, at a pinned commit, with the result published in full. Point a surveyor at a repository you know and see whether you agree with it.

About this page

  • The score is its most recent published measurement, taken on 21 September 2026 at a pinned commit. It is not a live figure and does not change until the project is measured again.
  • Measured at commit 4190ae2423e11e5b99880c29d4f384c70b329a78 — the exact code this score is about.
  • Scored under rubric-2026.09.15 — the same rubric and the same method as every other entry in this index.
  • Measured by watchdog.canine.dev using codehealth-analyzer preprod-b84573e22831.