Skip to content

Fix: Normalize userId to integer in POST/PUT requestsFix: Normalize userId to integer in POST/PUT requests #217

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
16 changes: 16 additions & 0 deletions src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,32 @@ const data = require('../data.json')
const app = jsonServer.create()
const router = jsonServer.router(clone(data), { _isFake: true })

// Reset state for each request (except root)
app.use((req, res, next) => {
if (req.path === '/') return next()
router.db.setState(clone(data))
next()
})

// Middleware to normalize userId to integer in POST and PUT
app.use((req, res, next) => {
if (
(req.method === 'POST' || req.method === 'PUT') &&
req.body &&
typeof req.body.userId === 'string'
) {
const parsed = parseInt(req.body.userId, 10)
req.body.userId = isNaN(parsed) ? req.body.userId : parsed
}
next()
})

// Default middleware (logger, static, CORS, etc)
app.use(jsonServer.defaults({
logger: process.env.NODE_ENV !== 'production'
}))

// Use JSON Server router
app.use(router)

module.exports = app