diff --git a/README.md b/README.md index 808d2e11a..5a49bb2a2 100644 --- a/README.md +++ b/README.md @@ -83,6 +83,7 @@ __Please help me build OSS__ 👉 [GitHub Sponsors](https://github.com/sponsors/ * [HTTPS](#https) * [Add custom routes](#add-custom-routes) * [Add middlewares](#add-middlewares) + * [Add custom renderer](#add-custom-renderer) * [CLI usage](#cli-usage) * [Module](#module) + [Simple example](#simple-example) @@ -392,6 +393,27 @@ json-server db.json --middlewares ./hello.js json-server db.json --middlewares ./first.js ./second.js ``` +### Add custom renderer + +You can add your custom renderer from the CLI using `--custom-renderer` option: + +```js +// renderer.js +module.exports = (req, res) => { + res.jsonp({ + version: "v1", + statusCode: 200, + isError: false, + message: "The Request successful.", + result: res.locals.data, + }) +} +``` + +```bash +json-server db.json --custom-renderer ./renderer.js +``` + ### CLI usage ``` @@ -413,6 +435,7 @@ Options: --id, -i Set database id property (e.g. _id) [default: "id"] --foreignKeySuffix, --fks Set foreign key suffix, (e.g. _id as in post_id) [default: "Id"] + --custom-renderer, --cr Path to custom renderer file --quiet, -q Suppress log messages from output [boolean] --help, -h Show help [boolean] --version, -v Show version number [boolean] diff --git a/src/cli/index.js b/src/cli/index.js index d817f9d7b..27a7c073f 100644 --- a/src/cli/index.js +++ b/src/cli/index.js @@ -25,6 +25,10 @@ module.exports = function () { alias: 'r', description: 'Path to routes file', }, + 'custom-renderer': { + alias: 'cr', + description: 'Path to custom renderer file', + }, middlewares: { alias: 'm', array: true, diff --git a/src/cli/run.js b/src/cli/run.js index c4238f473..e6b22a0be 100644 --- a/src/cli/run.js +++ b/src/cli/run.js @@ -35,7 +35,7 @@ function prettyPrint(argv, object, rules) { console.log() } -function createApp(db, routes, middlewares, argv) { +function createApp(db, routes, middlewares, argv, customRenderer) { const app = jsonServer.create() const { foreignKeySuffix } = argv @@ -74,6 +74,11 @@ function createApp(db, routes, middlewares, argv) { } router.db._.id = argv.id + + if (argv.customRenderer) { + router.render = customRenderer; + } + app.db = router.db app.use(router) @@ -123,11 +128,17 @@ module.exports = function (argv) { }) } + let customRenderer + if (argv.customRenderer) { + console.log(chalk.gray(' Loading', argv.customRenderer)); + customRenderer = require(path.resolve(argv.customRenderer)) + } + // Done console.log(chalk.gray(' Done')) // Create app and server - app = createApp(db, routes, middlewares, argv) + app = createApp(db, routes, middlewares, argv, customRenderer) server = app.listen(argv.port, argv.host) // Enhance with a destroy function