From 57e7e0756bd8c806d18fa7bc4c2f57fe4ae545c0 Mon Sep 17 00:00:00 2001 From: Kelvin Oghenerhoro Omereshone Date: Wed, 28 Feb 2024 10:53:55 +0100 Subject: [PATCH] fix: only share errors and flash messages when it's an inertia request (#85) --- inertia-sails/private/inertia-middleware.js | 42 +++++++++++---------- 1 file changed, 22 insertions(+), 20 deletions(-) diff --git a/inertia-sails/private/inertia-middleware.js b/inertia-sails/private/inertia-middleware.js index a48d0e04..17e48b28 100644 --- a/inertia-sails/private/inertia-middleware.js +++ b/inertia-sails/private/inertia-middleware.js @@ -11,27 +11,29 @@ const getPartialData = require('./get-partial-data') const resolveValidationErrors = require('./resolve-validation-errors') function inertia(sails, { hook, sharedProps, sharedViewData, rootView }) { return function inertiaMiddleware(req, res, next) { - /** - * Flash messages stored in the session. - * @typedef {Object} FlashMessages - * @property {Array} message - Flash message(s). - * @property {Array} error - Error message(s). - * @property {Array} success - Success message(s). - */ - const flash = { - message: req.flash('message'), - error: req.flash('error'), - success: req.flash('success') - } - hook.share('flash', flash) // Share the flash object as props - /** - * Validation errors stored in the session, resolved and formatted for Inertia.js. - * @type {Object} - */ - const validationErrors = resolveValidationErrors(req) - req.flash('errors', validationErrors) // Flash the validation error so we can share it later + if (isInertiaRequest(req)) { + /** + * Flash messages stored in the session. + * @typedef {Object} FlashMessages + * @property {Array} message - Flash message(s). + * @property {Array} error - Error message(s). + * @property {Array} success - Success message(s). + */ + const flash = { + message: req.flash('message'), + error: req.flash('error'), + success: req.flash('success') + } + hook.share('flash', flash) // Share the flash object as props + /** + * Validation errors stored in the session, resolved and formatted for Inertia.js. + * @type {Object} + */ + const validationErrors = resolveValidationErrors(req) + req.flash('errors', validationErrors) // Flash the validation error so we can share it later - hook.share('errors', req.flash('errors')[0] || {}) // Share validation errors as props + hook.share('errors', req.flash('errors')[0] || {}) // Share validation errors as props + } hook.render = function (component, props = {}, viewData = {}) { const allProps = {