{"id":29132080,"url":"https://github.com/nextlevelshit/node-cache-api","last_synced_at":"2026-05-10T02:16:25.953Z","repository":{"id":300191623,"uuid":"1005472509","full_name":"nextlevelshit/node-cache-api","owner":"nextlevelshit","description":"Most simple implementation of a API Server with expressJS","archived":false,"fork":false,"pushed_at":"2025-06-29T18:46:29.000Z","size":238,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-06-29T19:24:38.874Z","etag":null,"topics":["api","expressjs","node","nodejs"],"latest_commit_sha":null,"homepage":"https://nextlevelshit.github.io/2025-node-api/","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"wtfpl","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/nextlevelshit.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-06-20T09:29:10.000Z","updated_at":"2025-06-29T18:46:32.000Z","dependencies_parsed_at":"2025-06-20T10:42:39.542Z","dependency_job_id":"32b5c47a-7db3-4678-a4d4-259162cc4d1f","html_url":"https://github.com/nextlevelshit/node-cache-api","commit_stats":null,"previous_names":["nextlevelshit/2025-node-api","nextlevelshit/node-cache-api"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/nextlevelshit/node-cache-api","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nextlevelshit%2Fnode-cache-api","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nextlevelshit%2Fnode-cache-api/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nextlevelshit%2Fnode-cache-api/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nextlevelshit%2Fnode-cache-api/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/nextlevelshit","download_url":"https://codeload.github.com/nextlevelshit/node-cache-api/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nextlevelshit%2Fnode-cache-api/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32625943,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-04T10:08:07.713Z","status":"ssl_error","status_checked_at":"2026-05-04T10:08:02.005Z","response_time":58,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api","expressjs","node","nodejs"],"created_at":"2025-06-30T06:12:19.725Z","updated_at":"2026-05-04T21:31:52.242Z","avatar_url":"https://github.com/nextlevelshit.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Node.js ExpressJS API (Caching Service)\n\nA modern, minimal Node.js REST API built with ES modules, Express 5, and comprehensive testing via Vitest. Perfect for teaching contemporary web development patterns and testing strategies.\n\n## TL;DR\n\n```bash\nnpm install\nnpm start\n# API running on http://localhost:1312\n```\n\n## What's Inside\n\nThis isn't your typical Express boilerplate. We're running:\n\n- **Express 5.x** with ES modules (no more `require()` nonsense)\n- **In-memory cache service** for blazing-fast data operations\n- **Four-tier testing strategy** with static analysis, unit, integration, and E2E coverage\n- **Zero dependencies** for core functionality (Express + testing tools only)\n- **Modern JavaScript** patterns throughout\n- **Proper error handling** and HTTP status codes\n\n## Architecture\n\n```\nsrc/\n├── app.js                # Express app factory\n├── routes/\n│   └── api.js            # RESTful API endpoints\n└── services/\n    └── Cache.js          # In-memory key-value store\n```\n\nThe cache service handles all CRUD operations with optional debug logging and override capabilities. API routes provide a clean REST interface over HTTP.\n\n## API Reference\n\n### Core Endpoints\n\n```http\nGET    /api           # List all keys\nGET    /api/:key      # Retrieve data by key\nPOST   /api           # Create new entry (auto-generated key)\nPUT    /api/:key      # Update existing or create new\nDELETE /api/:key      # Remove entry\nDELETE /api           # Clear all entries\n```\n\n### Examples\n\n**Create data:**\n\n```bash\ncurl -X POST http://localhost:1312/api \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"name\":\"Wolfgang\",\"city\":\"Stuttgart\"}'\n# Returns: {\"key\":\"1735401234567\"}\n```\n\n**Retrieve data:**\n\n```bash\ncurl http://localhost:1312/api/1735401234567\n# Returns: {\"name\":\"Wolfgang\",\"city\":\"Stuttgart\"}\n```\n\n**Update data (merge behavior):**\n\n```bash\ncurl -X PUT http://localhost:1312/api/1735401234567 \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"age\":25}'\n# Returns: {\"key\":\"1735401234567\",\"data\":{\"name\":\"Wolfgang\",\"city\":\"Stuttgart\",\"age\":25}}\n```\n\n## Testing Strategy: The Four Pillars 🏛️\n\nThis project implements a comprehensive four-tier testing approach. Each tier serves a specific purpose and tests different aspects of your application with increasing realism but decreasing speed.\n\n### 1. Static Analysis: Code Quality Checks 🔍\n\n**What it tests:** Syntax errors and code quality issues without execution  \n**Tool:** ESLint  \n**Speed:** ⚡ ~10ms  \n**When to run:** Before every commit\n\n```bash\nnpm run lint\n```\n\n**Key characteristics:**\n\n- Catches syntax errors, unused variables, undefined references\n- Zero runtime overhead\n- First line of defense against bugs\n\n### 2. Unit Tests: Testing in Isolation 🔬\n\n**What they test:** Individual functions and classes with all dependencies mocked  \n**Tool:** Vitest with mocks  \n**Speed:** ⚡ ~50ms  \n**When to run:** Constantly during development\n\n```javascript\n// From Cache.unit.test.js\ntest(\"creates and retrieves data with custom key\", () =\u003e {\n  const cache = new Cache();\n  const testData = { user: \"wolfgang\", city: \"stuttgart\" };\n  const key = cache.create(testData, \"custom-key\");\n\n  expect(key).toBe(\"custom-key\");\n  expect(cache.get(\"custom-key\")).toEqual(testData);\n});\n```\n\n**Key characteristics:**\n\n- **Complete isolation** - every dependency is mocked\n- **Deterministic** - same input always produces same output\n- **Fast** - no I/O, no network, no filesystem\n- **Focused** - test one function at a time\n\n### 3. Integration Tests: Component Interaction Testing 🔗\n\n**What they test:** How your components work together, but still in-process  \n**Tool:** Vitest + Supertest (no real server)  \n**Speed:** 🟡 ~200ms  \n**When to run:** Before commits\n\n```javascript\n// From app.integration.test.js\nimport request from \"supertest\"; // ← Key difference: supertest, not fetch\nimport { createApp } from \"./app.js\";\n\ntest(\"full CRUD lifecycle with real cache\", async () =\u003e {\n  // supertest creates a test server internally - no real HTTP\n  const createResponse = await request(app) // ← In-process request\n    .post(\"/api\")\n    .send({ name: \"integration-test\", status: \"active\" });\n\n  expect(createResponse.status).toBe(201);\n  const { key } = createResponse.body;\n\n  // Verify it's actually in the cache (real cache instance)\n  expect(cache.keys).toContain(key);\n});\n```\n\n**Key characteristics:**\n\n- **Real components** - actual Cache and Express app instances\n- **Supertest magic** - simulates HTTP without actual server startup\n- **In-process** - everything runs in the same Node.js process\n- **No network** - no real TCP connections or ports\n\n**Further links:**\n\n- [Unit Testing vs Integration Testing - Key Differences](https://www.alexhyett.com/unit-testing-vs-integration-testing/#:~:text=Do%20integration%20tests%20use%20mocks,running%20just%20before%20a%20release.)\n\n### 4. E2E Tests: Full Stack Reality 🌐\n\n**What they test:** Your entire application exactly as users experience it  \n**Tool:** Vitest + real fetch() + real server  \n**Speed:** 🔴 ~1000ms  \n**When to run:** Before deployments\n\n```javascript\n// From index.e2e.test.js\nbeforeAll(async () =\u003e {\n  // Start actual server on real port\n  server = createServer(app);\n  await new Promise((resolve) =\u003e server.listen(TEST_PORT, resolve));\n});\n\ntest(\"complete user journey\", async () =\u003e {\n  // Real HTTP request over TCP to actual running server\n  const createResponse = await fetch(`${baseUrl}/api`, {\n    // ← Real fetch, not supertest\n    method: \"POST\",\n    headers: { \"Content-Type\": \"application/json\" },\n    body: JSON.stringify({\n      message: \"e2e test data\",\n      timestamp: new Date().toISOString(),\n    }),\n  });\n\n  expect(createResponse.status).toBe(201);\n});\n```\n\n**Key characteristics:**\n\n- **Real server** - actual HTTP server listening on TCP port\n- **Real network** - genuine HTTP requests over localhost\n- **Real environment** - tests server startup, CORS, middleware stack\n- **User perspective** - exactly what your users experience\n\n## The Critical Differences Explained\n\n| Test Type       | Import Pattern                     | Request Method              | Server Status | Speed     | What's Real             |\n| --------------- | ---------------------------------- | --------------------------- | ------------- | --------- | ----------------------- |\n| **Unit**        | `import { Cache }`                 | Direct method calls         | No server     | ⚡ 10ms   | Nothing - all mocked    |\n| **Integration** | `import request from \"supertest\"`  | `request(app).get()`        | Simulated     | 🟡 100ms  | Components, not network |\n| **E2E**         | `beforeAll(() =\u003e server.listen())` | `fetch(\"http://localhost\")` | Real server   | 🔴 1000ms | Everything              |\n\n### Why This Matters\n\n**Integration tests catch:** \"My cache works, my routes work, but they don't work _together_\"\n\n```javascript\n// Integration - tests that cache + routes integrate properly\nconst response = await request(app).post(\"/api\").send(data);\nexpect(cache.keys).toContain(response.body.key); // Direct cache access\n```\n\n**E2E tests catch:** \"Everything works in isolation, but fails when deployed\"\n\n```javascript\n// E2E - tests the complete network stack\nconst response = await fetch(`http://localhost:${port}/api`, { ... });\n// No direct cache access - testing through the network boundary\n```\n\n## Test Execution \u0026 Development Workflow\n\n```bash\n# Development with hot reload\nnpm start\n\n# Run specific test tiers (in order of feedback speed)\nnpm run test.unit        # 50ms - Run constantly\nnpm run test.integration # 200ms - Run before commits\nnpm run test.e2e         # 1000ms - Run before deployments\n\n# Run all tests\nnpm test\n\n# Coverage report\nnpm run test.coverage\n```\n\n### The Testing Pyramid in Action\n\n```\n    E2E (Few, Slow, High Confidence)\n      /\\\n     /  \\\n    /    \\   Integration (Some, Medium, Component Confidence)\n   /      \\\n  /        \\\n /__________\\ Unit (Many, Fast, Logic Confidence)\n```\n\n**Development workflow:**\n\n1. **Write unit tests first** - fast feedback on logic\n2. **Add integration tests** - verify components play nice\n3. **Minimal E2E tests** - critical user journeys only\n\n## Test Environment Setup\n\n### Unit Tests\n\n```javascript\n// All dependencies mocked\nconst mockCache = {\n  get: vi.fn(),\n  create: vi.fn(),\n  // ... complete mock interface\n};\n```\n\n### Integration Tests\n\n```javascript\n// Real instances, no mocks\ncache = new Cache({ debug: false });\napp = createApp(cache, { port: 1312 });\n// supertest handles the HTTP simulation\n```\n\n### E2E Tests\n\n```javascript\n// Real server lifecycle\nbeforeAll(async () =\u003e {\n  server = createServer(app);\n  await new Promise((resolve) =\u003e server.listen(TEST_PORT, resolve));\n});\n\nafterAll(async () =\u003e {\n  await new Promise((resolve) =\u003e server.close(resolve));\n});\n```\n\n## Cache Service Deep Dive\n\nThe `Cache` class is the heart of data persistence:\n\n```javascript\nimport { Cache } from \"./src/services/Cache.js\";\n\nconst cache = new Cache({\n  debug: true, // Enable console logging\n  override: true, // Allow key overwrites with merge\n});\n\n// Basic operations\nconst key = cache.create({ user: \"data\" });\nconst data = cache.get(key);\ncache.update(key, { more: \"data\" });\ncache.remove(key);\n\n// Collections\ncache.keys; // All keys as array\ncache.values; // All values as array\ncache.clear(); // Nuclear option\n```\n\n## Production Considerations\n\nThis is a development/learning project. For production:\n\n- Add persistent storage (Redis, PostgreSQL, etc.)\n- Implement authentication/authorization\n- Add rate limiting and request validation\n- Set up proper logging (Winston, Pino)\n- Add health checks and metrics\n- Configure CORS appropriately\n- Add database integration tests\n- Set up CI/CD with all test tiers\n\n## Why This Stack?\n\n- **ES Modules**: The future of JavaScript modularity\n- **Express 5**: Latest stable with improved async support\n- **Vitest**: Faster than Jest, built for ES modules, superior DX\n- **Minimal dependencies**: Less attack surface, easier auditing\n- **Test-driven**: Comprehensive coverage from day one\n- **Educational**: Clear separation of concerns for learning\n\n## Testing Philosophy\n\n\u003e \"The right test at the right level catches bugs at the right time.\"\n\nThis project demonstrates that **test architecture \u003e test coverage**. Each tier serves a specific purpose:\n\n- **Static analysis** → Catch syntax errors before runtime\n- **Unit tests** → Fast feedback on logic errors\n- **Integration tests** → Component interaction verification\n- **E2E tests** → User experience validation\n\nThe four-tier approach ensures you catch bugs at the optimal level - fixing a unit test takes seconds, debugging an E2E failure takes minutes.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnextlevelshit%2Fnode-cache-api","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnextlevelshit%2Fnode-cache-api","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnextlevelshit%2Fnode-cache-api/lists"}