Skip to content

Commit

Permalink
[feat]: use responses and exits (#87)
Browse files Browse the repository at this point in the history
* feat(inertia-sails): remove location and render method implementations

* feat(inertia-sails): remove unneeded methos and have sharedProps as a property in sails.inertia
  • Loading branch information
DominusKelvin authored Feb 29, 2024
1 parent 60c921a commit 60a3721
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 102 deletions.
30 changes: 13 additions & 17 deletions inertia-sails/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,6 @@
const inertia = require('./private/inertia-middleware')
module.exports = function defineInertiaHook(sails) {
let hook
let sharedProps = {}
let sharedViewData = {}
let rootView = 'app'
const routesToBindInertiaTo = [
'GET r|^((?![^?]*\\/[^?\\/]+\\.[^?\\/]+(\\?.*)?).)*$|',
// (^^Leave out assets)
Expand All @@ -22,37 +19,36 @@ module.exports = function defineInertiaHook(sails) {
return {
defaults: {
inertia: {
rootView: 'app',
version: 1
}
},
initialize: async function () {
hook = this
sails.inertia = hook

sails.inertia.sharedProps = {}
sails.inertia.sharedViewData = {}
sails.on('router:before', function routerBefore() {
routesToBindInertiaTo.forEach(function iterator(routeAddress) {
sails.router.bind(
routeAddress,
inertia(sails, { hook, sharedProps, sharedViewData, rootView })
)
sails.router.bind(routeAddress, inertia(hook))
})
})
},

share: (key, value = null) => (sharedProps[key] = value),
share: (key, value = null) => (sails.inertia.sharedProps[key] = value),

getShared: (key = null) => sharedProps[key] ?? sharedProps,
getShared: (key = null) =>
sails.inertia.sharedProps[key] ?? sails.inertia.sharedProps,

flushShared: (key) => {
key ? delete sharedProps[key] : (sharedProps = {})
key
? delete sails.inertia.sharedProps[key]
: (sails.inertia.sharedProps = {})
},

viewData: (key, value) => (sharedViewData[key] = value),

getViewData: (key) => sharedViewData[key] ?? sharedViewData,

setRootView: (newRootView) => (rootView = newRootView),
viewData: (key, value) => (sails.inertia.sharedViewData[key] = value),

getRootView: () => rootView
getViewData: (key) =>
sails.inertia.sharedViewData[key] ?? sails.inertia.sharedViewData
}
}
90 changes: 5 additions & 85 deletions inertia-sails/private/inertia-middleware.js
Original file line number Diff line number Diff line change
@@ -1,100 +1,20 @@
const { encode } = require('querystring')
const isInertiaRequest = require('./is-inertia-request')

const {
INERTIA,
PARTIAL_DATA,
PARTIAL_COMPONENT
} = require('./inertia-headers')

const getPartialData = require('./get-partial-data')
const resolveValidationErrors = require('./resolve-validation-errors')
function inertia(sails, { hook, sharedProps, sharedViewData, rootView }) {
function inertia(hook) {
return function inertiaMiddleware(req, res, next) {
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.render = function (component, props = {}, viewData = {}) {
const allProps = {
...sharedProps,
...props
}

const allViewData = {
...sharedViewData,
...viewData
}

let url = req.url || req.originalUrl
const assetVersion = sails.config.inertia.version
const currentVersion =
typeof assetVersion == 'function' ? assetVersion() : assetVersion

const page = {
component,
version: currentVersion,
props: allProps,
url
}
hook.share('flash', flash)

// Implements inertia partial reload. See https://inertiajs.com/partial-reload
if (req.get(PARTIAL_DATA) && req.get(PARTIAL_COMPONENT) === component) {
const only = req.get(PARTIAL_DATA).split(',')
page.props = only.length ? getPartialData(props, only) : page.props
}

const queryParams = req.query
if (req.method == 'GET' && Object.keys(queryParams).length) {
// Keep original request query params
url += `?${encode(queryParams)}`
}
const validationErrors = resolveValidationErrors(req)
req.flash('errors', validationErrors)

if (isInertiaRequest(req)) {
res.set(INERTIA, true)
res.set('Vary', 'Accept')
return res.json(page)
} else {
// Implements full page reload
return sails.hooks.views.render(rootView, {
page,
viewData: allViewData
})
}
}
/**
* Handle 303 and external redirects
* see https://inertiajs.com/redirects#303-response-code
* @param {string} url - The URL to redirect to.
*/
hook.location = function (url) {
if (isInertiaRequest(req)) {
res.set('X-Inertia-Location', url)
}
return res.redirect(
['PUT', 'PATCH', 'DELETE'].includes(req.method) ? 303 : 409,
url
)
hook.share('errors', req.flash('errors')[0] || {})
}

return next()
Expand Down

0 comments on commit 60a3721

Please sign in to comment.