Skip to content

fix: replaces fetch API with octokit.getContent#2570

Merged
stalniy merged 3 commits intomainfrom
fix/fetching-templates
Jan 27, 2026
Merged

fix: replaces fetch API with octokit.getContent#2570
stalniy merged 3 commits intomainfrom
fix/fetching-templates

Conversation

@stalniy
Copy link
Contributor

@stalniy stalniy commented Jan 26, 2026

Why

in order to use the GH_TOKEN to fetch files content because direct fetch API call timeouts sometimes

Summary by CodeRabbit

  • Chores
    • Updated Octokit dependency, adjusted Jest transform settings, bumped dev tooling and added a JS compiler runtime.
    • Switched internal template fetching to use Octokit instead of global fetch; added ignore/skip options for template processing.
  • Tests
    • Refactored tests to remove global fetch mocks, using Octokit-driven mocks and path-based content stubs.
  • CI/Build
    • Simplified lockfile/version handling in workflows and Docker build steps; adjusted coverage ignore patterns.

✏️ Tip: You can customize this high-level summary in your review settings.

@stalniy stalniy requested a review from a team as a code owner January 26, 2026 23:06
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 26, 2026

📝 Walkthrough

Walkthrough

Replaces direct global fetch with Octokit REST raw content retrieval in template fetching; adds ignore-by-keywords and ignore-by-paths options propagated through processing; updates tests and consumers to use Octokit only. Also bumps @octokit/rest, adjusts Jest transformIgnorePatterns, and updates CI/docker lockfile scripts.

Changes

Cohort / File(s) Summary
Jest configuration
apps/api/jest.config.js
Added transformIgnorePatterns to allow transforming specific node_modules packages (@octokit, universal-user-agent, before-after-hook).
API package
apps/api/package.json
Bumped @octokit/rest from ^18.12.0^22.0.1.
Root package
package.json
Updated lint-staged devDependency ^15.4.0^16.2.7; added @swc/core@1.15.10 to trustedDependencies.
TemplateFetcher implementation
apps/api/src/template/services/template-fetcher/template-fetcher.service.ts
Removed fetch constructor param; added private #octokit; introduced fetchFileContent using Octokit REST (raw); added ProcessCategoryOptions with ignoreByKeywords/ignoreByPaths; updated method signatures to accept templateSource context and propagate ignore options; added skip/ignore logging and rate-limit tracking.
TemplateGallery consumer
apps/api/src/template/services/template-gallery/template-gallery.service.ts
Updated TemplateFetcherService instantiation to remove fetch argument and pass Octokit client directly with options.
TemplateFetcher tests
apps/api/src/template/services/template-fetcher/template-fetcher.service.spec.ts
Removed fetch-mock and mockFetchResponses; refactored tests to construct service as (templateProcessor, logger, octokit) and mock Octokit/path-based content responses.
Build / CI workflows & scripts
.github/workflows/create-pre-release-pr.yml, packages/docker/Dockerfile.*, apps/api/scripts/buildAkashTemplatesCache.ts
Replaced post-generation git diff logic with inline Node.js lockfile-updating script; dockerfiles updated to inline Node.js package-lock mutation; removed explicit concurrency options passed to TemplateGalleryService in build script.
Codecov config
.codecov.yml
Adjusted ignore pattern from apps/api/src/*/routers/**/*.ts to apps/api/src/*/routes/**/*.ts.

Sequence Diagram(s)

sequenceDiagram
    participant Gallery as TemplateGalleryService
    participant Fetcher as TemplateFetcherService
    participant Octo as Octokit (REST)
    participant Proc as TemplateProcessorService
    participant Log as LoggerService

    Gallery->>Fetcher: instantiate(templateProcessor, logger, octokit, options)
    Gallery->>Fetcher: fetchTemplatesInfo(categories, options)
    Fetcher->>Log: debug "processing category"
    Fetcher->>Octo: repos.getContent(owner, repo, path, mediaType=raw, ref?)
    Octo-->>Fetcher: raw file content / directory listing
    Fetcher->>Proc: process template files (README, deploy, config)
    Proc-->>Fetcher: processed template metadata
    Fetcher->>Log: warn/info on ignored templates or errors
    Fetcher-->>Gallery: categories with template info
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested reviewers

  • baktun14
  • ygrishajev

Poem

🐇 I hopped through code and swapped a net for keys,
Octokit now fetches files with gentle ease.
Tests trimmed their mocks and follow path-lit ways,
Jest learns new node modules under moonlit rays.
A rabbit's nibble — templates bloom today!

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: replacing fetch API calls with octokit.getContent for file retrieval.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov
Copy link

codecov bot commented Jan 26, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 49.77%. Comparing base (43c75c0) to head (d421ba5).
⚠️ Report is 1 commits behind head on main.
✅ All tests successful. No failed tests found.

❌ Your project status has failed because the head coverage (78.01%) is below the target coverage (80.00%). You can increase the head coverage or adjust the target coverage.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2570      +/-   ##
==========================================
- Coverage   50.86%   49.77%   -1.09%     
==========================================
  Files        1071     1025      -46     
  Lines       29901    29088     -813     
  Branches     6630     6573      -57     
==========================================
- Hits        15209    14480     -729     
+ Misses      14388    14252     -136     
- Partials      304      356      +52     
Flag Coverage Δ
api 78.01% <100.00%> (-1.04%) ⬇️
deploy-web 31.46% <ø> (+<0.01%) ⬆️
log-collector 75.35% <ø> (ø)
notifications 87.94% <ø> (ø)
provider-console 81.48% <ø> (ø)
provider-proxy 84.35% <ø> (ø)
Files with missing lines Coverage Δ
...vices/template-fetcher/template-fetcher.service.ts 95.16% <100.00%> (-1.67%) ⬇️
...vices/template-gallery/template-gallery.service.ts 98.26% <100.00%> (ø)

... and 129 files with indirect coverage changes

🚀 New features to boost your workflow:
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

baktun14
baktun14 previously approved these changes Jan 26, 2026
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/api/src/template/services/template-fetcher/template-fetcher.service.ts (1)

83-101: Add type guard for response.data in fetchFileContent

mediaType.format="raw" is the correct way to fetch raw content in Octokit v22, but String(response.data) can mask errors if the response unexpectedly returns a non-string value. Add a type check before returning, matching the pattern used in fetchDirectoryContent:

Suggested change
-    if (response.status !== 200) {
-      throw new Error(`Failed to fetch content from ${owner}/${repo}/${path}`);
-    }
-
-    return String(response.data);
+    if (response.status !== 200 || typeof response.data !== "string") {
+      throw new Error(`Failed to fetch content from ${owner}/${repo}/${path}`);
+    }
+
+    return response.data;
🤖 Fix all issues with AI agents
In `@apps/api/package.json`:
- Line 66: The dependency bump to "@octokit/rest": "^22.0.1" requires Node.js
≥20 and ESM-first imports; verify the runtime and code accordingly by ensuring
the project's Node target is >=20 (update runtime config/CI), convert any
CommonJS requires of "@octokit/rest" to ESM-style imports (e.g., replace
require(...) with import { Octokit } from "@octokit/rest" where used), and if
this is a TypeScript project update tsconfig.json (adjust "module" and
"moduleResolution" to "node16" or "nodenext" as appropriate) so TypeScript
resolves the package's conditional exports; check all usages of Octokit and
build/CI settings to prevent runtime import/resolution failures.

@socket-security
Copy link

socket-security bot commented Jan 27, 2026

Review the following changes in direct dependencies. Learn more about Socket for GitHub.

Diff Package Supply Chain
Security
Vulnerability Quality Maintenance License
Added@​dotenvx/​dotenvx@​1.14.09710010095100

View full report

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Fix all issues with AI agents
In
`@apps/api/src/template/services/template-fetcher/template-fetcher.service.spec.ts`:
- Around line 631-639: The test helper function setup currently has no parameter
and should accept a single inline-typed options parameter; update the setup
signature to take one object parameter (with an inline type describing optional
templateProcessor: TemplateProcessorService, logger: LoggerService, and octokit:
Octokit) with defaults that create mocks, then use those values to construct the
TemplateFetcherService instance and return them (referencing setup,
TemplateFetcherService, templateProcessor, logger, octokit to locate the code).

In `@apps/api/src/template/services/template-fetcher/template-fetcher.service.ts`:
- Around line 168-179: The comparison against options.ignoreByPaths uses exact
equality and can miss variants like "./jenkins" or "jenkins/"; update the check
in the template-fetcher logic (the block that logs
TEMPLATE_SOURCE_PROCESSING_SKIPPED and any similar check later) to normalize
both sides before comparing: create/inline a small normalizer (e.g., trim
whitespace, remove leading "./", remove trailing slashes, and optionally
lowercase) and compare normalize(templateSource.path) === normalize(ignorePath)
or use .some() over normalized ignore entries; apply the same normalization to
the duplicate check around lines 345-356 so both locations use the same
normalizePath helper and behavior.
🧹 Nitpick comments (1)
apps/api/src/template/services/template-fetcher/template-fetcher.service.ts (1)

125-149: Avoid double-fetching README when keyword filtering is enabled.

README content is fetched once for keyword filtering and then fetched again inside processTemplateSource. This doubles GitHub API calls per template and eats rate limits. Consider passing the already-fetched README into processTemplateSource to reuse it.

♻️ Suggested refactor to reuse README
-  private async processTemplateSource(
-    templateSource: TemplateSource,
-    directoryItems: GithubDirectoryItem[],
-    options: { includeConfigJson?: boolean }
-  ): Promise<any> {
+  private async processTemplateSource(
+    templateSource: TemplateSource,
+    directoryItems: GithubDirectoryItem[],
+    options: { includeConfigJson?: boolean },
+    prefetchedReadme?: string | null
+  ): Promise<any> {
     try {
       if (templateSource.path.startsWith("http:") || templateSource.path.startsWith("https:")) {
         throw new Error("Absolute URL not supported");
       }

-      const readme = await this.findFileContentAsync("README.md", directoryItems, templateSource);
+      const readme = prefetchedReadme ?? (await this.findFileContentAsync("README.md", directoryItems, templateSource));
       const [deploy, guide, configJsonText] = await Promise.all([
         this.findFileContentAsync(["deploy.yaml", "deploy.yml"], directoryItems, templateSource),
         this.findFileContentAsync("GUIDE.md", directoryItems, templateSource),
         options.includeConfigJson ? this.findFileContentAsync("config.json", directoryItems, templateSource) : Promise.resolve(null)
       ]);
-          return this.processTemplateSource(templateSource, directoryItems, options);
+          return this.processTemplateSource(templateSource, directoryItems, options, readme);

Also applies to: 190-203

@stalniy stalniy force-pushed the fix/fetching-templates branch 7 times, most recently from 78f6d43 to bd4c1e6 Compare January 27, 2026 22:59
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Fix all issues with AI agents
In @.codecov.yml:
- Line 3: The ignore glob currently only excludes nested route directories via
"apps/api/src/*/routes/**/*.ts" but misses the top-level routers directory, so
update the coverage ignore list to also include the pattern
"apps/api/src/routers/**/*.ts" (alongside the existing
"apps/api/src/*/routes/**/*.ts") so the seven top-level TypeScript router files
remain excluded from coverage.

In `@packages/docker/Dockerfile.node`:
- Around line 20-21: The current Dockerfile.node step runs `npm version ...` and
then mutates `package-lock.json` only by setting `lockfile.version` to "1.0.0";
update the inline Node script invoked by `node -e` to also set the
workspace-specific lockfile entry (i.e.,
`lockfile.packages['$WORKSPACE'].version`) to "1.0.0" so the workspace package
version in npm lockfile v3 is reset as in Dockerfile.nextjs; locate the `npm
version --allow-same-version 1.0.0 -w $WORKSPACE --no-workspaces-update` line
and the following `node -e "const fs=...; const lockfile=...;
fs.writeFileSync(...)"` invocation and modify the script to load
package-lock.json, set both `lockfile.version` and
`lockfile.packages['$WORKSPACE'].version` to "1.0.0", then write the file back.

@stalniy stalniy force-pushed the fix/fetching-templates branch from bd4c1e6 to d421ba5 Compare January 27, 2026 23:10
@stalniy stalniy closed this Jan 27, 2026
@stalniy stalniy reopened this Jan 27, 2026
@stalniy stalniy merged commit 079f0d4 into main Jan 27, 2026
120 of 202 checks passed
@stalniy stalniy deleted the fix/fetching-templates branch January 27, 2026 23:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

Comments