Skip to content

Commit 595465e

Browse files
committed
Upd clean feature patch changes
1 parent d32f76d commit 595465e

File tree

6 files changed

+32
-136
lines changed

6 files changed

+32
-136
lines changed

README.md

+9-54
Original file line numberDiff line numberDiff line change
@@ -204,64 +204,19 @@ json-server -s ./static -s ./node_modules
204204

205205
## Middleware
206206

207-
```sh
208-
json-server --middleware logger.mjs
209-
```
207+
You can add your middlewares from the CLI using `--middleware` option:
210208

211209
```js
212-
// logger.mjs
213-
import chalk from 'chalk';
214-
215-
export default (req, _res, next) => {
216-
const currentDate = new Date().toISOString();
217-
console.log(chalk.green(req.method), chalk.yellow(req.url), chalk.blue(`${currentDate}`));
218-
219-
// Check if the request body is already parsed
220-
if (req.body && Object.keys(req.body).length > 0) {
221-
console.log(chalk.magenta('Body:'), req.body);
222-
} else {
223-
// Manually parse the request body if not already parsed
224-
let body = '';
225-
req.on('data', (chunk) => {
226-
body += chunk.toString();
227-
});
228-
req.on('end', () => {
229-
if (body) {
230-
try {
231-
const parsedBody = JSON.parse(body);
232-
console.log(chalk.magenta('Body:'), parsedBody);
233-
} catch (error) {
234-
console.log(chalk.red('Failed to parse body'), error);
235-
}
236-
}
237-
next();
238-
});
239-
return;
240-
}
241-
242-
next();
243-
};
210+
// hello.js
211+
module.exports = (req, res, next) => {
212+
res.header('X-Hello', 'World')
213+
next()
214+
}
244215
```
245216

246-
This will output:
247-
248-
```sh
249-
Index:
250-
http://localhost:3000/
251-
252-
Static files:
253-
Serving ./public directory if it exists
254-
255-
Endpoints:
256-
http://localhost:3000/posts
257-
http://localhost:3000/comments
258-
http://localhost:3000/profile
259-
260-
PATCH /posts/1 2025-01-03T08:25:13.138Z
261-
Body: { title: 'foo', body: 'bar', userId: 1 }
262-
POST /posts 2025-01-03T08:25:18.661Z
263-
Body: { title: 'foo', body: 'bar', userId: 1 }
264-
GET /posts 2025-01-03T08:25:20.159Z
217+
```bash
218+
json-server db.json --middleware ./hello.js
219+
json-server db.json --middleware ./first.js ./second.js
265220
```
266221

267222
## Notable differences with v0.17

middleware/logger.mjs

-31
This file was deleted.

package.json

+1-2
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@
1818
"dev": "tsx watch src/bin.ts fixtures/db.json",
1919
"build": "rm -rf lib && tsc",
2020
"test": "node --import tsx/esm --test src/*.test.ts",
21-
"logger": "tsx watch src/bin.ts fixtures/db.json --middleware=middleware/logger.mjs",
2221
"lint": "eslint src",
2322
"prepare": "husky",
2423
"prepublishOnly": "npm run build"
@@ -61,4 +60,4 @@
6160
"sirv": "^2.0.4",
6261
"sort-on": "^6.1.0"
6362
}
64-
}
63+
}

src/app.ts

+2-4
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ const isProduction = process.env['NODE_ENV'] === 'production'
1616
export type AppOptions = {
1717
logger?: boolean
1818
static?: string[]
19-
middleware?: (req: unknown, res: unknown, next: unknown) => void
19+
middlewares?: ((req: unknown, res: unknown, next: unknown) => void)[]
2020
}
2121

2222
const eta = new Eta({
@@ -38,9 +38,7 @@ export function createApp(db: Low<Data>, options: AppOptions = {}) {
3838
.forEach((dir) => app.use(sirv(dir, { dev: !isProduction })))
3939

4040
// Use middleware if specified
41-
if (options.middleware) {
42-
app.use(options.middleware)
43-
}
41+
options.middlewares?.forEach(m => app.use(m));
4442

4543
// CORS
4644
app

src/bin.ts

+20-23
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ Options:
2222
-p, --port <port> Port (default: 3000)
2323
-h, --host <host> Host (default: localhost)
2424
-s, --static <dir> Static files directory (multiple allowed)
25-
--middleware <file> Middleware file
25+
--middleware, -m <file> Paths to middleware files (multiple allowed)
2626
--help Show this message
2727
--version Show version number
2828
`)
@@ -57,7 +57,9 @@ function args(): {
5757
},
5858
middleware: {
5959
type: 'string',
60-
default: '',
60+
short: 'm',
61+
multiple: true,
62+
default: []
6163
},
6264
help: {
6365
type: 'boolean',
@@ -119,25 +121,27 @@ function args(): {
119121
}
120122
}
121123

122-
// Load middleware
123-
async function loadMiddleware(middlewarePath: string) {
124-
const resolvedPath = resolve(process.cwd(), middlewarePath)
125-
if (existsSync(resolvedPath)) {
126-
const middlewareModule = await import(resolvedPath)
127-
return middlewareModule.default || middlewareModule
128-
} else {
129-
console.error(`Middleware file not found: ${resolvedPath}`)
130-
process.exit(1)
131-
}
132-
}
133-
134-
const { file, port, host, static: staticArr, middleware } = args()
124+
const { file, port, host, static: staticArr, middleware: middlewarePaths } = args()
135125

136126
if (!existsSync(file)) {
137127
console.log(chalk.red(`File ${file} not found`))
138128
process.exit(1)
139129
}
140130

131+
// Load middlewares if specified
132+
const middlewareFunctions = await Promise.all(
133+
middlewarePaths.map(async p => {
134+
if (!existsSync(p)){
135+
console.error(`Middleware file not found: ${resolvedPath}`)
136+
return process.exit(1)
137+
}
138+
console.log(chalk.gray(`Loading middleware from ${middlewarePaths}`))
139+
const resolvedPath = resolve(process.cwd(), p)
140+
const middlewareModule = await import(resolvedPath)
141+
return middlewareModule.default || middlewareModule
142+
})
143+
);
144+
141145
// Handle empty string JSON file
142146
if (readFileSync(file, 'utf-8').trim() === '') {
143147
writeFileSync(file, '{}')
@@ -158,18 +162,11 @@ const observer = new Observer(adapter)
158162
const db = new Low<Data>(observer, {})
159163
await db.read()
160164

161-
// Load middleware if specified
162-
let middlewareFunction
163-
if (middleware) {
164-
console.log(chalk.gray(`Loading middleware from ${middleware}`))
165-
middlewareFunction = await loadMiddleware(middleware)
166-
}
167-
168165
// Create app
169166
const app = createApp(db, {
170167
logger: false,
171168
static: staticArr,
172-
middleware: middlewareFunction,
169+
middlewares: middlewareFunctions,
173170
})
174171

175172
function logRoutes(data: Data) {

test.http

-22
This file was deleted.

0 commit comments

Comments
 (0)