Skip to content

Add server API#8

Open
dejarno wants to merge 1 commit into
mainfrom
10-13-demo_36b9511d_add_server_api
Open

Add server API#8
dejarno wants to merge 1 commit into
mainfrom
10-13-demo_36b9511d_add_server_api

Conversation

@dejarno

@dejarno dejarno commented Oct 13, 2025

Copy link
Copy Markdown
Owner

TL;DR

Added a basic Express server with a search endpoint for tasks.

What changed?

Created a new server.js file in the graphite-demo directory that:

  • Sets up an Express server running on port 3000
  • Includes sample task data with IDs and descriptions
  • Implements a /search endpoint that filters tasks based on a query parameter

How to test?

  1. Start the server: node graphite-demo/server.js
  2. Test the search endpoint with:
    • All tasks: GET http://localhost:3000/search
    • Filtered tasks: GET http://localhost:3000/search?query=report
  3. Verify that the endpoint returns JSON with the filtered task list

Why make this change?

This provides a simple backend API for task searching functionality, which can be integrated with a frontend application. The implementation allows for case-insensitive partial matching on task descriptions.

Summary by CodeRabbit

  • New Features
    • Added a search endpoint for filtering tasks by description. Users can query tasks using case-insensitive matching and receive results in JSON format for easy integration.

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

@coderabbitai

coderabbitai Bot commented Oct 13, 2025

Copy link
Copy Markdown

Walkthrough

Adds a new file graphite-demo/server.js implementing an Express server that listens on port 3000, maintains an in-memory tasks array, and exposes a GET /search endpoint that filters tasks by case-insensitive query string matching.

Changes

Cohort / File(s) Summary
New demo server
graphite-demo/server.js
Introduces Express server on port 3000 with in-memory tasks array containing three sample tasks. Implements GET /search endpoint that accepts query parameter, filters tasks by case-insensitive description containment, and returns matching results as JSON. Logs server startup message.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Poem

🐰 Hop-hop-hooray! A new server sprouts,
Search through tasks with queries and clouts,
Port 3000 listening so bright,
Filtering whiskers—queries alight!
Demo magic, demo delight! ✨

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title concisely summarizes the primary change: adding a server API. It clearly reflects the creation of an Express server with a /search endpoint. It is specific enough to indicate the main new functionality without unnecessary detail.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 10-13-demo_36b9511d_add_server_api

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

dejarno commented Oct 13, 2025

Copy link
Copy Markdown
Owner Author

This stack of pull requests is managed by Graphite. Learn more about stacking.

@dejarno dejarno mentioned this pull request Oct 13, 2025
@dejarno dejarno marked this pull request as ready for review October 16, 2025 11:07
Comment thread graphite-demo/server.js
@@ -0,0 +1,33 @@
const express = require('express');
const app = express();

@aikido-pr-checks aikido-pr-checks Bot Oct 16, 2025

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Express is not emitting security headers - high severity
You're using an Express server, but not using Helmet. Helmet can help protect your app from some well-known web vulnerabilities by setting HTTP headers. Examples are HSTS headers that enforce SSL, CSP headers that protect against XSS attacks. Other headers protect against putting your app in an iframe to launch social engineering attacks which could be used for account takeovers.

Show Remediation

Remediation - high confidence
This patch mitigates security header vulnerabilities in the Express app by adding the 'helmet' middleware to set protective HTTP headers.

Suggested change
const app = express();
const helmet = require('helmet');
const app = express();
app.use(helmet());

View details in Aikido Security

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (2)
graphite-demo/server.js (2)

21-29: Consider adding security middleware.

For production use, consider adding:

  • CORS configuration to control cross-origin requests
  • Helmet.js for security headers
  • Rate limiting to prevent abuse

Example implementation:

const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const rateLimit = require('express-rate-limit');

const app = express();

// Security middleware
app.use(helmet());
app.use(cors({
  origin: process.env.ALLOWED_ORIGINS?.split(',') || '*'
}));

// Rate limiting
const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100 // limit each IP to 100 requests per windowMs
});
app.use('/search', limiter);

31-33: Add error handling for server startup.

The server doesn't handle errors during startup (e.g., port already in use).

Apply this diff to add error handling:

-app.listen(port, () => {
-  console.log(`Server running on port ${port}`);
-});
+app.listen(port, () => {
+  console.log(`Server running on port ${port}`);
+}).on('error', (err) => {
+  if (err.code === 'EADDRINUSE') {
+    console.error(`Port ${port} is already in use`);
+  } else {
+    console.error('Server error:', err);
+  }
+  process.exit(1);
+});
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8f73b91 and eff223e.

📒 Files selected for processing (1)
  • graphite-demo/server.js (1 hunks)

Comment thread graphite-demo/server.js
@@ -0,0 +1,33 @@
const express = require('express');

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

Verify Express dependency is declared.

Ensure that express is listed in the project's dependencies.

Run the following script to verify the Express dependency:


🏁 Script executed:

#!/bin/bash
# Description: Check if express is declared in package.json

# Check if package.json exists and contains express
if [ -f "package.json" ]; then
  echo "=== Checking for express in package.json ==="
  cat package.json | jq '.dependencies.express // .devDependencies.express // "NOT FOUND"'
else
  echo "ERROR: package.json not found"
  exit 1
fi

Length of output: 56


Add express to dependencies in package.json
Express is required in server.js but missing from the dependencies section of package.json.

🤖 Prompt for AI Agents
In graphite-demo/server.js at line 1, express is required but not listed in
package.json dependencies; update package.json by adding express to the
"dependencies" (preferred: run npm install --save express to add it
automatically) or manually add an appropriate version entry (e.g., "express":
"^x.y.z") and run npm install to ensure it's installed and locked.

Comment thread graphite-demo/server.js
@@ -0,0 +1,33 @@
const express = require('express');
const app = express();
const port = 3000;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major

Make port configurable via environment variable.

Hardcoding the port prevents flexibility across environments (development, staging, production).

Apply this diff to make the port configurable:

-const port = 3000;
+const port = process.env.PORT || 3000;
🤖 Prompt for AI Agents
In graphite-demo/server.js around line 3, the port is hardcoded as 3000; change
it to read from process.env.PORT with a fallback to 3000 (e.g., const port =
parseInt(process.env.PORT, 10) || 3000) so the app is configurable across
environments, ensuring you parse the env var to a number and keep 3000 as the
default if none is provided.

Comment thread graphite-demo/server.js
Comment on lines +21 to +29
app.get('/search', (req, res) => {
// Retrieve the query parameter
const query = req.query.query?.toLowerCase() || '';

// Filter tasks based on the query
const filteredTasks = tasks.filter(task => task.description.toLowerCase().includes(query));

res.json(filteredTasks);
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Add error handling and input validation.

The endpoint lacks error handling and input validation, which could lead to crashes or security issues:

  • No try-catch around the filter operation
  • No validation on query length or content
  • No protection against resource exhaustion from expensive queries

Apply this diff to add basic error handling and validation:

 app.get('/search', (req, res) => {
-  // Retrieve the query parameter
-  const query = req.query.query?.toLowerCase() || '';
-
-  // Filter tasks based on the query
-  const filteredTasks = tasks.filter(task => task.description.toLowerCase().includes(query));
-
-  res.json(filteredTasks);
+  try {
+    // Retrieve and validate the query parameter
+    const query = req.query.query?.toLowerCase() || '';
+    
+    // Validate query length
+    if (query.length > 100) {
+      return res.status(400).json({ error: 'Query too long' });
+    }
+
+    // Filter tasks based on the query
+    const filteredTasks = tasks.filter(task => task.description.toLowerCase().includes(query));
+
+    res.json(filteredTasks);
+  } catch (error) {
+    console.error('Error in /search endpoint:', error);
+    res.status(500).json({ error: 'Internal server error' });
+  }
 });
🤖 Prompt for AI Agents
In graphite-demo/server.js around lines 21 to 29, wrap the handler body in a
try-catch and add validation/safeguards: validate req.query.query is a string,
trim it, enforce a reasonable max length (e.g. 100 chars) and restrict
characters (e.g. allow only alphanumeric, spaces, hyphens) returning 400 for
invalid input; protect against expensive operations by using a case-insensitive
substring search on the sanitized query, limit the returned results to a safe
maximum (e.g. 100 items), and on unexpected errors return a 500 with a simple
error message while logging the error server-side.

@dejarno

dejarno commented Nov 3, 2025

Copy link
Copy Markdown
Owner Author

📈 Code Coverage Summary

  • Coverage on new code: 92.0% (230/250 lines)
  • Status: ✅ Meets 90% requirement for new code.

@sonarqubecloud

sonarqubecloud Bot commented Nov 3, 2025

Copy link
Copy Markdown

Quality Gate Failed Quality Gate failed

Failed conditions
1 Security Hotspot

See analysis details on SonarQube Cloud

Comment thread graphite-demo/server.js
// Filter tasks based on the query
const filteredTasks = tasks.filter(task => task.description.toLowerCase().includes(query));

res.json(filteredTasks);

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Suggested change
res.json(filteredTasks);
res.json(filteredTasks + 1);

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.

1 participant