Skip to content

(feat): add middleware #1630

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 7 commits into
base: main
Choose a base branch
from
Draft
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
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,23 @@ json-server -s ./static
json-server -s ./static -s ./node_modules
```

## Middleware

You can add your middlewares from the CLI using `--middleware` option:

```js
// hello.js
module.exports = (req, res, next) => {
res.header('X-Hello', 'World')
next()
}
```

```bash
json-server db.json --middleware ./hello.js
json-server db.json --middleware ./first.js ./second.js
```

## Notable differences with v0.17

- `id` is always a string and will be generated for you if missing
Expand Down
4 changes: 4 additions & 0 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ const isProduction = process.env['NODE_ENV'] === 'production'
export type AppOptions = {
logger?: boolean
static?: string[]
middlewares?: ((req: unknown, res: unknown, next: unknown) => void)[]
}

const eta = new Eta({
Expand All @@ -36,6 +37,9 @@ export function createApp(db: Low<Data>, options: AppOptions = {}) {
?.map((path) => (isAbsolute(path) ? path : join(process.cwd(), path)))
.forEach((dir) => app.use(sirv(dir, { dev: !isProduction })))

// Use middleware if specified
options.middlewares?.forEach(m => app.use(m));

// CORS
app
.use((req, res, next) => {
Expand Down
43 changes: 35 additions & 8 deletions src/bin.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#!/usr/bin/env node
import { existsSync, readFileSync, writeFileSync } from 'node:fs'
import { extname } from 'node:path'
import { extname, resolve } from 'node:path'
import { parseArgs } from 'node:util'

import chalk from 'chalk'
Expand All @@ -19,11 +19,12 @@ function help() {
console.log(`Usage: json-server [options] <file>

Options:
-p, --port <port> Port (default: 3000)
-h, --host <host> Host (default: localhost)
-s, --static <dir> Static files directory (multiple allowed)
--help Show this message
--version Show version number
-p, --port <port> Port (default: 3000)
-h, --host <host> Host (default: localhost)
-s, --static <dir> Static files directory (multiple allowed)
--middleware, -m <file> Paths to middleware files (multiple allowed)
--help Show this message
--version Show version number
`)
}

Expand All @@ -33,6 +34,7 @@ function args(): {
port: number
host: string
static: string[]
middleware: string
} {
try {
const { values, positionals } = parseArgs({
Expand All @@ -53,6 +55,12 @@ function args(): {
multiple: true,
default: [],
},
middleware: {
type: 'string',
short: 'm',
multiple: true,
default: []
},
help: {
type: 'boolean',
},
Expand Down Expand Up @@ -100,6 +108,7 @@ function args(): {
port: parseInt(values.port as string),
host: values.host as string,
static: values.static as string[],
middleware: values.middleware as string[],
}
} catch (e) {
if ((e as NodeJS.ErrnoException).code === 'ERR_PARSE_ARGS_UNKNOWN_OPTION') {
Expand All @@ -112,13 +121,27 @@ function args(): {
}
}

const { file, port, host, static: staticArr } = args()
const { file, port, host, static: staticArr, middleware: middlewarePaths } = args()

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

// Load middlewares if specified
const middlewareFunctions = await Promise.all(
middlewarePaths.map(async p => {
const resolvedPath = resolve(process.cwd(), p)
if (!existsSync(resolvedPath)){
console.error(`Middleware file not found: ${resolvedPath}`)
return process.exit(1)
}
console.log(chalk.gray(`Loading middleware from ${resolvedPath}`))
const middlewareModule = await import(resolvedPath)
return middlewareModule.default || middlewareModule
})
);

// Handle empty string JSON file
if (readFileSync(file, 'utf-8').trim() === '') {
writeFileSync(file, '{}')
Expand All @@ -140,7 +163,11 @@ const db = new Low<Data>(observer, {})
await db.read()

// Create app
const app = createApp(db, { logger: false, static: staticArr })
const app = createApp(db, {
logger: false,
static: staticArr,
middlewares: middlewareFunctions,
})

function logRoutes(data: Data) {
console.log(chalk.bold('Endpoints:'))
Expand Down