{"id":28263257,"url":"https://github.com/1999azzar/lru-caching-server","last_synced_at":"2026-02-25T17:35:51.908Z","repository":{"id":290412303,"uuid":"974358869","full_name":"1999AZZAR/lru-caching-server","owner":"1999AZZAR","description":"Node.js LRU caching server with MariaDB integration","archived":false,"fork":false,"pushed_at":"2025-06-03T09:52:35.000Z","size":98,"stargazers_count":0,"open_issues_count":1,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-06-14T18:08:06.892Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/1999AZZAR.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"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-04-28T16:49:16.000Z","updated_at":"2025-05-05T06:28:49.000Z","dependencies_parsed_at":"2025-06-14T18:08:08.633Z","dependency_job_id":"9bb57c55-7c22-4a1a-8272-2faa826028f7","html_url":"https://github.com/1999AZZAR/lru-caching-server","commit_stats":null,"previous_names":["1999azzar/lru-caching-server"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/1999AZZAR/lru-caching-server","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/1999AZZAR%2Flru-caching-server","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/1999AZZAR%2Flru-caching-server/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/1999AZZAR%2Flru-caching-server/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/1999AZZAR%2Flru-caching-server/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/1999AZZAR","download_url":"https://codeload.github.com/1999AZZAR/lru-caching-server/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/1999AZZAR%2Flru-caching-server/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":281322869,"owners_count":26481547,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-10-27T02:00:05.855Z","response_time":61,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"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":[],"created_at":"2025-05-20T07:14:09.267Z","updated_at":"2025-10-27T18:39:23.570Z","avatar_url":"https://github.com/1999AZZAR.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# LRU Caching Server\n\nA lightweight Node.js server using Express, Sequelize (MariaDB), and an in-memory LRU cache to speed up data retrieval.\n\n---\n\n## Features\n\n- **LRU Cache** with configurable size and TTL\n- **MariaDB** persistence via Sequelize ORM\n- **Cache→DB** fallback: reads hit cache first, then DB, and auto-populate cache\n- **Create \u0026 Cache**: POST endpoint inserts into DB and cache\n- **Error Handling** with clear HTTP status codes and messages\n- **Desktop Integration**: simple to hook into any desktop app (Electron, .NET, etc.)\n- **SQLite Fallback**: automatic in-memory DB when MariaDB is unavailable\n- **Clustering**: multi-core via Node.js cluster\n- **Security \u0026 CORS**: Helmet headers, CORS \u0026 rate limiting\n- **Logging**: HTTP request logs via Morgan\n- **Validation**: Joi schema validation\n- **Multi-level Cache**: in-memory LRU + Redis\n- **Metrics \u0026 Health**: `/metrics` \u0026 `/health` endpoints (Prometheus)\n- **Versioned API**: served under `/v1`\n- **Graceful Shutdown**: handles SIGTERM/SIGINT\n\n---\n\n## Getting Started\n\n1. Copy `.env.example` to `.env` and fill in your credentials and cache settings.\n2. Install dependencies:\n   ```bash\n   npm install\n   ```\n3. Start the server:\n   ```bash\n   npm start\n   ```\n**Note:** If MariaDB is not configured or reachable, the server will automatically fallback to an in-memory SQLite DB (no extra setup required).\n4. The API listens on `http://localhost:3000` by default.\n\n### Environment Variables\n\n```dotenv\nDB_HOST=localhost       # MariaDB host\nDB_PORT=3306            # MariaDB port\nDB_USER=root            # DB username\nDB_PASS=password        # DB password\nDB_NAME=mydb            # Database name\nCACHE_MAX=100           # Max number of items in cache\nCACHE_TTL=300000        # Cache TTL in ms (default 5m)\nPORT=3000               # HTTP port\nREDIS_HOST=127.0.0.1    # Redis host\nREDIS_PORT=6379         # Redis port\nCORS_ORIGIN=*           # CORS allowed origin\nRATE_LIMIT_WINDOW=900000 # Rate-limit window in ms (default 15m)\nRATE_LIMIT_MAX=100       # Max requests per window\n```\n\n---\n\n## Docker \u0026 Local Development\n\n```bash\ndocker-compose up -d\n```\n\n_Or_ build and run directly:\n```bash\ndocker build -t lru-caching . \\\n  \u0026\u0026 docker run --env-file .env -p 3000:3000 lru-caching\n```\n\nFollow logs:\n```bash\ndocker-compose logs -f\n```\n\nThe `docker-compose.yml` maps port `3306` for MariaDB and `3000` for the API.\n\n---\n\n## API Docs\n\nBrowse the interactive Swagger UI at:\n  - [http://localhost:3000/docs](http://localhost:3000/docs)\n  - [http://localhost:3000/v1/docs](http://localhost:3000/v1/docs)\n\n---\n\n## API Endpoints\n\n### GET /v1/items/:id\n\n- **200 OK** `{ source: 'cache'|'db', item }`\n- **404 Not Found** `{ error: 'Not found' }`\n- **500 Internal** `{ error: 'Internal Server Error' }`\n\n#### Example\n```bash\ncurl http://localhost:3000/v1/items/1\n```\n\n### POST /v1/items\n\n- **400 Bad Request** on missing `name`\n- **201 Created** returns new item and caches it\n- **500 Internal** on DB errors\n\n#### Body\n```json\n{ \"name\": \"foo\", \"value\": \"bar\" }\n```\n\n#### Example\n```bash\ncurl -X POST -H \"Content-Type: application/json\" \\\n  -d '{\"name\":\"foo\",\"value\":\"bar\"}' \\\n  http://localhost:3000/v1/items\n```\n\n### GET /metrics\n\n- **200 OK**: Prometheus metrics\n\n#### Example\n```bash\ncurl http://localhost:3000/metrics\n```\n\n### GET /health\n\n- **200 OK**: health status JSON\n\n#### Example\n```bash\ncurl http://localhost:3000/health\n```\n\n---\n\n## Error Handling \u0026 Logging\n\n- Input validation: missing or invalid fields ⇒ **400**\n- Not found ⇒ **404**\n- Unexpected failures ⇒ **500**, with console error logs\n- You can plug in a logger (winston/pino) in `src/index.js`\n\n---\n\n## Advanced Cache Policies\n\nConfiguration via env (`CACHE_MAX`, `CACHE_TTL`). You can also:\n\n```js\n// custom per-item TTL\ncache.set(key, value, { ttl: 1000 * 60 * 10 });  // 10m for this entry\n\n// allow stale reads while repopulating\nconst cache = new LRU({ max: 100, ttl: 300000, allowStale: true });\n\n// listen for evictions\ncache.on('evict', ({ key, value }) =\u003e {\n  console.log(`Evicted ${key}`);\n});\n```\n\n---\n\n## Desktop Integration\n\nYou can consume these endpoints from any desktop environment. Examples:\n\n### Electron / JavaScript\n\n```js\nimport axios from 'axios';\nconst API = 'http://localhost:3000';\n\nasync function fetchItem(id) {\n  try {\n    const { data } = await axios.get(`${API}/v1/items/${id}`);\n    console.log(data);\n  } catch (err) {\n    console.error(err.response?.data || err.message);\n  }\n}\n```\n\n### .NET / C#\n\n```csharp\nusing System.Net.Http;\nusing System.Text.Json;\n\nvar client = new HttpClient();\nvar resp = await client.GetAsync(\"http://localhost:3000/v1/items/1\");\nif (resp.IsSuccessStatusCode) {\n    var json = await resp.Content.ReadAsStringAsync();\n    var item = JsonSerializer.Deserialize\u003cItem\u003e(json);\n    Console.WriteLine(item.Name);\n}\n```\n\n### Python / Flask\n\n```python\nfrom flask import Flask, jsonify, request\nfrom requests import Session\n\napp = Flask(__name__)\napi_session = Session()\napi_session.base_url = \"http://localhost:3000/v1\"\n\n@app.route('/items/\u003cint:item_id\u003e')\ndef get_item(item_id):\n    try:\n        response = api_session.get(f'{api_session.base_url}/items/{item_id}')\n        response.raise_for_status()\n        return jsonify(response.json())\n    except Exception as e:\n        return jsonify({'error': str(e)}), 500\n\n@app.route('/items', methods=['POST'])\ndef create_item():\n    data = request.get_json()\n    try:\n        response = api_session.post(f'{api_session.base_url}/items', json=data)\n        response.raise_for_status()\n        return jsonify(response.json()), 201\n    except Exception as e:\n        return jsonify({'error': str(e)}), 500\n\nif __name__ == '__main__':\n    app.run(debug=True)\n```\n\nThis example shows how to:\n1. Create a Flask application that proxies requests to the LRU caching server\n2. Use `requests.Session` for efficient HTTP requests\n3. Handle errors and return appropriate HTTP status codes\n4. Maintain clean separation between your application and the caching layer\n\nYou can easily extend this example by adding:\n- Custom error handling middleware\n- Request validation\n- Rate limiting\n- Logging\n- Circuit breaker patterns for retry logic\n### Other Clients\n\nAny language that can make HTTP calls (Python `requests`, Java `HttpClient`, etc.) will work.\n\n---\n\n## Contributing\n\nFeel free to open issues or PRs for additional policies, endpoints, or integrations.\n\n---\n\n## License\n\nMIT \n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2F1999azzar%2Flru-caching-server","html_url":"https://awesome.ecosyste.ms/projects/github.com%2F1999azzar%2Flru-caching-server","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2F1999azzar%2Flru-caching-server/lists"}