Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Node
node_modules/

# Env files
.env
.env.*

# Logs
logs/
*.log
npm-debug.log*

# Runtime data
pids/
*.pid
*.seed
*.pid.lock

# Coverage
coverage/
.nyc_output/

# Build output
dist/
build/

# OS/editor
.DS_Store
.vscode/
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
# Coursework

Exercises to practice and solidify your understanding of the Decomposition module of the Software Development Course.

## Middleware exercises

This repo includes two Express examples for the Sprint 3 middleware prep:

- Custom middlewares: [middleware-custom/](middleware-custom)
- Off-the-shelf middleware: [middleware-off-the-shelf/](middleware-off-the-shelf)

Each folder has its own README with run instructions.
29 changes: 29 additions & 0 deletions middleware-custom/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Custom middleware example

This Express app uses two custom middlewares:
- `requestLogger` logs each request with status and duration.
- `requireApiKey` protects `POST /messages` using an API key header.

## Run locally

```bash
npm install
npm start
```

Set a custom API key (optional):

```bash
API_KEY=my-secret npm start
```

## Try it

```bash
curl http://localhost:3000/health
curl http://localhost:3000/messages
curl -X POST http://localhost:3000/messages \
-H "Content-Type: application/json" \
-H "x-api-key: cyf" \
-d '{"user":"Azin","message":"Hello"}'
```
10 changes: 10 additions & 0 deletions middleware-custom/middlewares/requestLogger.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
module.exports = function requestLogger(req, res, next) {
const startedAt = Date.now();

res.on("finish", () => {
const durationMs = Date.now() - startedAt;
console.log(`${req.method} ${req.originalUrl} ${res.statusCode} ${durationMs}ms`);
});

next();
};
10 changes: 10 additions & 0 deletions middleware-custom/middlewares/requireApiKey.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
module.exports = function requireApiKey(req, res, next) {
const expectedKey = process.env.API_KEY || "cyf";
const providedKey = req.header("x-api-key");

if (providedKey !== expectedKey) {
return res.status(401).json({ error: "Invalid API key" });
}

next();
};
Loading
Loading