Created
September 5, 2022 14:15
-
-
Save mrhammadasif/006ee88d75d5fa7cd56e45f16308409b to your computer and use it in GitHub Desktop.
Dynamic Routes in json-server with CORS enabled for API server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const dynamicMiddleware = require( 'express-dynamic-middleware' ) | |
const jsonServer = require( "json-server" ) | |
const jsonFile = "db.json" | |
const server = jsonServer.create() | |
let router = jsonServer.router( jsonFile ) | |
let dynamicRouter = dynamicMiddleware.create( router ) | |
const defaults = jsonServer.defaults() | |
server.use( '/:name', function ( req, res, next ) { | |
if ( req.method === 'POST' ) { | |
if ( !router.db.get( req.params.name ).value() ) { | |
router.db.defaults( { [req.params.name]: [] } ).write() | |
dynamicRouter.unuse( router ) | |
router = jsonServer.router( jsonFile ) | |
dynamicRouter = dynamicMiddleware.create( router ) | |
server.use( dynamicRouter.handle() ) | |
} | |
} | |
next() | |
} ) | |
server.use( defaults ) | |
server.use( dynamicRouter.handle() ) | |
server.listen( 8899, () => { | |
console.log( 'API listening on port 8080.' ) | |
} ) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
... | |
"dependencies": { | |
"body-parser": "^1.20.0", | |
"cors": "^2.8.5", | |
"express-dynamic-middleware": "^1.0.0", | |
"json-server": "^0.17.0" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment