inertia-sails 0.1.3 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -13,6 +13,7 @@ The quickest way to get setup an Inertia powered Sails app is to use the [create
13
13
  > Do replace `<project-name>` with the name you want your project to be.
14
14
 
15
15
  ## Frontend
16
+
16
17
  If you are using the [create-sails](https://github.com/sailscastshq/create-sails) scaffolding tool then the Frontend framework you choose from the CLI prompt should already be setup for you.
17
18
 
18
19
  ## Usage
@@ -52,7 +53,7 @@ module.exports = function defineCustomHook(sails) {
52
53
  fn: async function (req, res, next) {
53
54
  if (req.session.userId) {
54
55
  const loggedInUser = await User.findOne({
55
- id: req.session.userId,
56
+ id: req.session.userId
56
57
  })
57
58
  if (!loggedInUser) {
58
59
  sails.log.warn(
@@ -67,15 +68,16 @@ module.exports = function defineCustomHook(sails) {
67
68
  return next()
68
69
  }
69
70
  return next()
70
- },
71
- },
72
- },
73
- },
71
+ }
72
+ }
73
+ }
74
+ }
74
75
  }
75
76
  }
76
77
  ```
77
78
 
78
79
  ## Configuration
80
+
79
81
  If you used the `create-sails` scaffolding tool, you will find the configuration file for Inertia.js in `config/inertia.js`. You will mostly use this file for asset-versioning in Inertia by setting either a number or string that you can update when your assets changes. Below is an example of how this file looks like:
80
82
 
81
83
  ```js
@@ -100,5 +102,4 @@ module.exports.inertia = {
100
102
  }
101
103
  ```
102
104
 
103
-
104
105
  Visit [inertiajs.com](https://inertiajs.com/) to learn more.
package/index.js CHANGED
@@ -4,103 +4,39 @@
4
4
  * @description :: A hook definition. Extends Sails by adding shadow routes, implicit actions, and/or initialization logic.
5
5
  * @docs :: https://sailsjs.com/docs/concepts/extending-sails/hooks
6
6
  */
7
-
8
- const { encode } = require('querystring')
9
- const isInertiaRequest = require('./private/is-inertia-request')
10
- const {
11
- INERTIA,
12
- PARTIAL_DATA,
13
- PARTIAL_COMPONENT,
14
- } = require('./private/inertia-headers')
15
- const getPartialData = require('./private/get-partial-data')
16
-
7
+ const inertia = require('./private/inertia-middleware')
17
8
  module.exports = function defineInertiaHook(sails) {
18
9
  let hook
19
10
  let sharedProps = {}
20
11
  let sharedViewData = {}
21
12
  let rootView = 'app'
13
+ const routesToBindInertiaTo = [
14
+ 'GET r|^((?![^?]*\\/[^?\\/]+\\.[^?\\/]+(\\?.*)?).)*$|',
15
+ // (^^Leave out assets)
16
+ 'POST /*',
17
+ 'PATCH /*',
18
+ 'PUT /*',
19
+ 'DELETE /*'
20
+ ]
22
21
 
23
- const inertiaMiddleware = (req, res, next) => {
24
- hook.render = function (component, props = {}, viewData = {}) {
25
- const allProps = {
26
- ...sharedProps,
27
- ...props,
28
- }
29
-
30
- const allViewData = {
31
- ...sharedViewData,
32
- ...viewData,
33
- }
34
-
35
- let url = req.url || req.originalUrl
36
- const assetVersion = sails.config.inertia.version
37
- const currentVersion =
38
- typeof assetVersion == 'function' ? assetVersion() : assetVersion
39
-
40
- const page = {
41
- component,
42
- version: currentVersion,
43
- props: allProps,
44
- url,
45
- }
46
-
47
- // Implements inertia partial reload. See https://inertiajs.com/partial-reload
48
- if (req.get(PARTIAL_DATA) && req.get(PARTIAL_COMPONENT) === component) {
49
- const only = req.get(PARTIAL_DATA).split(',')
50
- page.props = only.length ? getPartialData(props, only) : page.props
51
- }
52
-
53
- const queryParams = req.query
54
- if (req.method == 'GET' && Object.keys(queryParams).length) {
55
- // Keep original request query params
56
- url += `?${encode(queryParams)}`
57
- }
58
-
59
- // Implements inertia requests
60
- if (isInertiaRequest(req)) {
61
- return res.status(200).json(page)
62
- }
63
-
64
- // Implements full page reload
65
- return sails.hooks.views.render(rootView, {
66
- page,
67
- viewData: allViewData,
68
- })
69
- }
70
- hook.location = function (url = req.headers['referer']) {
71
- const statusCode = ['PUT', 'PATCH', 'DELETE'].includes(req.method)
72
- ? 303
73
- : 409
74
- res.set('X-Inertia-Location', url)
75
- return res.redirect(statusCode, url)
76
- }
77
-
78
- // Set Inertia headers
79
- if (isInertiaRequest(req)) {
80
- res.set(INERTIA, true)
81
- res.set('Vary', 'Accept')
82
- }
83
- return next()
84
- }
85
22
  return {
86
23
  defaults: {
87
24
  inertia: {
88
- version: 1,
89
- },
25
+ version: 1
26
+ }
90
27
  },
91
28
  initialize: async function () {
92
29
  hook = this
93
30
  sails.inertia = hook
94
31
 
95
- hook.share('flash', {
96
- success: null,
97
- error: null,
32
+ sails.on('router:before', function routerBefore() {
33
+ routesToBindInertiaTo.forEach(function iterator(routeAddress) {
34
+ sails.router.bind(
35
+ routeAddress,
36
+ inertia(sails, { hook, sharedProps, sharedViewData, rootView })
37
+ )
38
+ })
98
39
  })
99
-
100
- hook.share('errors', {})
101
-
102
- // Register Inertia middleware
103
- sails.registerActionMiddleware(inertiaMiddleware, '*')
104
40
  },
105
41
 
106
42
  share: (key, value = null) => (sharedProps[key] = value),
@@ -117,6 +53,6 @@ module.exports = function defineInertiaHook(sails) {
117
53
 
118
54
  setRootView: (newRootView) => (rootView = newRootView),
119
55
 
120
- getRootView: () => rootView,
56
+ getRootView: () => rootView
121
57
  }
122
58
  }
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "inertia-sails",
3
- "version": "0.1.3",
3
+ "version": "0.1.6",
4
4
  "description": "The Sails adapter for Inertia.",
5
5
  "main": "index.js",
6
6
  "sails": {
@@ -8,9 +8,8 @@
8
8
  "hookName": "inertia"
9
9
  },
10
10
  "scripts": {
11
- "lint": "npx prettier --check .",
12
- "lint:fix": "npx prettier --write .",
13
- "prepare": "husky install"
11
+ "test": "echo \"Error: no test specified\" && exit 1",
12
+ "prepare": "cd .. && husky install"
14
13
  },
15
14
  "repository": {
16
15
  "type": "git",
@@ -26,15 +25,7 @@
26
25
  "author": "Kelvin Omereshone Oghenerhoro <kelvin@sailscasts.com>",
27
26
  "license": "MIT",
28
27
  "bugs": {
29
- "url": "https://github.com/sailscastshq/inertia-sails/issues"
28
+ "url": "https://github.com/sailscastshq/boring-stack/issues"
30
29
  },
31
- "homepage": "https://github.com/sailscastshq/inertia-sails#readme",
32
- "devDependencies": {
33
- "husky": "^8.0.2",
34
- "lint-staged": "^13.1.0",
35
- "prettier": "^2.6.2"
36
- },
37
- "lint-staged": {
38
- "**/*": "prettier --write --ignore-unknown"
39
- }
30
+ "homepage": "https://github.com/sailscastshq/boring-stack/inertia-sails#readme"
40
31
  }
@@ -0,0 +1,79 @@
1
+ const { encode } = require('querystring')
2
+ const isInertiaRequest = require('./is-inertia-request')
3
+
4
+ const {
5
+ INERTIA,
6
+ PARTIAL_DATA,
7
+ PARTIAL_COMPONENT
8
+ } = require('./inertia-headers')
9
+
10
+ const getPartialData = require('./get-partial-data')
11
+ const resolveValidationErrors = require('./resolve-validation-errors')
12
+ function inertia(sails, { hook, sharedProps, sharedViewData, rootView }) {
13
+ return function inertiaMiddleware(req, res, next) {
14
+ hook.share('errors', resolveValidationErrors(req))
15
+
16
+ hook.render = function (component, props = {}, viewData = {}) {
17
+ const allProps = {
18
+ ...sharedProps,
19
+ ...props
20
+ }
21
+
22
+ const allViewData = {
23
+ ...sharedViewData,
24
+ ...viewData
25
+ }
26
+
27
+ let url = req.url || req.originalUrl
28
+ const assetVersion = sails.config.inertia.version
29
+ const currentVersion =
30
+ typeof assetVersion == 'function' ? assetVersion() : assetVersion
31
+
32
+ const page = {
33
+ component,
34
+ version: currentVersion,
35
+ props: allProps,
36
+ url
37
+ }
38
+
39
+ // Implements inertia partial reload. See https://inertiajs.com/partial-reload
40
+ if (req.get(PARTIAL_DATA) && req.get(PARTIAL_COMPONENT) === component) {
41
+ const only = req.get(PARTIAL_DATA).split(',')
42
+ page.props = only.length ? getPartialData(props, only) : page.props
43
+ }
44
+
45
+ const queryParams = req.query
46
+ if (req.method == 'GET' && Object.keys(queryParams).length) {
47
+ // Keep original request query params
48
+ url += `?${encode(queryParams)}`
49
+ }
50
+
51
+ // Implements inertia requests
52
+ if (isInertiaRequest(req)) {
53
+ return res.status(200).json(page)
54
+ }
55
+
56
+ // Implements full page reload
57
+ return sails.hooks.views.render(rootView, {
58
+ page,
59
+ viewData: allViewData
60
+ })
61
+ }
62
+ hook.location = function (url = req.headers['referer']) {
63
+ const statusCode = ['PUT', 'PATCH', 'DELETE'].includes(req.method)
64
+ ? 303
65
+ : 409
66
+ res.set('X-Inertia-Location', url)
67
+ return res.redirect(statusCode, url)
68
+ }
69
+
70
+ // Set Inertia headers
71
+ if (isInertiaRequest(req)) {
72
+ res.set(INERTIA, true)
73
+ res.set('Vary', 'Accept')
74
+ }
75
+ return next()
76
+ }
77
+ }
78
+
79
+ module.exports = inertia
@@ -0,0 +1,40 @@
1
+ /**
2
+ * @module resolveValidationErrors
3
+ * @description Resolves and formats validation errors from the session for Inertia responses.
4
+ *
5
+ * @param {Object} req - The current HTTP request object.
6
+ * @returns {Object} An object representing the validation errors in the desired format.
7
+ */
8
+ module.exports = function resolveValidationErrors(req) {
9
+ if (!req.session || !req.session.errors) {
10
+ return {}
11
+ }
12
+
13
+ const flashedErrors = req.session.errors
14
+
15
+ const collectedErrors = Object.keys(flashedErrors).reduce((result, bag) => {
16
+ const errorsForBag = flashedErrors[bag]
17
+ const mappedErrors = errorsForBag.map((error) =>
18
+ error.replace(/"([^"]+)"/, '$1')
19
+ )
20
+ // Ensure that single errors are wrapped in an array
21
+ result[bag] = mappedErrors.length > 1 ? mappedErrors : mappedErrors[0]
22
+ return result
23
+ }, {})
24
+
25
+ const inertiaErrorBag = req.headers['x-inertia-error-bag']
26
+
27
+ if (inertiaErrorBag && collectedErrors[inertiaErrorBag]) {
28
+ const selectedErrors = {
29
+ [inertiaErrorBag]: collectedErrors[inertiaErrorBag]
30
+ }
31
+ return selectedErrors
32
+ }
33
+
34
+ if (collectedErrors.default) {
35
+ const defaultErrors = { default: collectedErrors.default }
36
+ return defaultErrors
37
+ }
38
+
39
+ return collectedErrors
40
+ }
package/.husky/pre-commit DELETED
@@ -1,4 +0,0 @@
1
- #!/usr/bin/env sh
2
- . "$(dirname -- "$0")/_/husky.sh"
3
-
4
- npx lint-staged
package/.prettierrc.js DELETED
@@ -1,4 +0,0 @@
1
- module.exports = {
2
- semi: false,
3
- singleQuote: true,
4
- }