inertia-sails 0.0.8 → 0.1.0

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.
Files changed (3) hide show
  1. package/README.md +104 -0
  2. package/index.js +66 -81
  3. package/package.json +1 -1
package/README.md ADDED
@@ -0,0 +1,104 @@
1
+ # Inertia.js Sails Adapter
2
+
3
+ ## Installation
4
+
5
+ ## Backend
6
+
7
+ The quickest way to get setup an Inertia powered Sails app is to use the [create-sails](https://github.com/sailscastshq/create-sails) scaffolding tool. Just run
8
+
9
+ ```sh
10
+ npx create-sails <project-name>
11
+ ```
12
+
13
+ > Do replace `<project-name>` with the name you want your project to be.
14
+
15
+ ## Frontend
16
+ 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
+ ## Usage
19
+
20
+ ### Responses
21
+
22
+ Sending back an Inertia responses is pretty simple, just use the `sails.inertia.render` method in your Sails actions(You can look at the example actions if you used create-sails). The `render` method accepts two arguments, the first is the name of the component you want to render from within your `pages` directory in `assets/js` (without the file extension).
23
+
24
+ The second argument is the props object where you can provide props to your components.
25
+
26
+ ## Shared Data
27
+
28
+ If you have data that you want to be provided as a prop to every component (a common use-case is informationa about the authenticated user) you can use the `sails.inertia.share` method.
29
+
30
+ In Sails having a custom hook by running `sails generate hook custom` will scaffolding a project level hook in which you can share the loggedIn user information for example. Below is a real world use case:
31
+
32
+ ```js
33
+ /**
34
+ * custom hook
35
+ *
36
+ * @description :: A hook definition. Extends Sails by adding shadow routes, implicit actions, and/or initialization logic.
37
+ * @docs :: https://sailsjs.com/docs/concepts/extending-sails/hooks
38
+ */
39
+
40
+ module.exports = function defineCustomHook(sails) {
41
+ return {
42
+ /**
43
+ * Runs when this Sails app loads/lifts.
44
+ */
45
+ initialize: async function () {
46
+ sails.log.info('Initializing custom hook (`custom`)')
47
+ },
48
+ routes: {
49
+ before: {
50
+ 'GET /': {
51
+ skipAssets: true,
52
+ fn: async function (req, res, next) {
53
+ if (req.session.userId) {
54
+ const loggedInUser = await User.findOne({
55
+ id: req.session.userId,
56
+ })
57
+ if (!loggedInUser) {
58
+ sails.log.warn(
59
+ 'Somehow, the user record for the logged-in user (`' +
60
+ req.session.userId +
61
+ '`) has gone missing....'
62
+ )
63
+ delete req.session.userId
64
+ return res.redirect('/signin')
65
+ }
66
+ sails.inertia.share('loggedInUser', loggedInUser)
67
+ return next()
68
+ }
69
+ return next()
70
+ },
71
+ },
72
+ },
73
+ },
74
+ }
75
+ }
76
+ ```
77
+
78
+ ## Configuration
79
+ 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
+
81
+ ```js
82
+ /**
83
+ * Inertia configuration
84
+ * (sails.config.inertia)
85
+ *
86
+ * Use the settings below to configure session integration in your app.
87
+ *
88
+ * For more information on Inertia configuration, visit:
89
+ * https://inertia-sails.sailscasts.com
90
+ */
91
+
92
+ module.exports.inertia = {
93
+ /**
94
+ * https://inertiajs.com/asset-versioning
95
+ * You can pass a string, number that changes when your assets change
96
+ * or a function that returns the said string, number.
97
+ * e.g 4 or () => 4
98
+ */
99
+ // version: 1,
100
+ }
101
+ ```
102
+
103
+
104
+ Visit [inertiajs.com](https://inertiajs.com/) to learn more.
package/index.js CHANGED
@@ -19,13 +19,76 @@ module.exports = function defineInertiaHook(sails) {
19
19
  let sharedProps = {}
20
20
  let sharedViewData = {}
21
21
  let rootView = 'app'
22
+
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.status(statusCode)
75
+ res.set('X-Inertia-Location', 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
+ }
22
85
  return {
23
86
  defaults: {
24
87
  inertia: {
25
88
  version: 1,
26
89
  },
27
90
  },
28
- initialize: async function (cb) {
91
+ initialize: async function () {
29
92
  hook = this
30
93
  sails.inertia = hook
31
94
 
@@ -36,7 +99,8 @@ module.exports = function defineInertiaHook(sails) {
36
99
 
37
100
  hook.share('errors', {})
38
101
 
39
- return cb()
102
+ // Register Inertia middleware
103
+ sails.registerActionMiddleware(inertiaMiddleware, '*')
40
104
  },
41
105
 
42
106
  share: (key, value = null) => (sharedProps[key] = value),
@@ -54,84 +118,5 @@ module.exports = function defineInertiaHook(sails) {
54
118
  setRootView: (newRootView) => (rootView = newRootView),
55
119
 
56
120
  getRootView: () => rootView,
57
-
58
- routes: {
59
- before: {
60
- 'GET /*': {
61
- skipAssets: true,
62
- fn: function (req, res, next) {
63
- hook.render = function (component, props = {}, viewData = {}) {
64
- const allProps = {
65
- ...sharedProps,
66
- ...props,
67
- }
68
-
69
- const allViewData = {
70
- ...sharedViewData,
71
- ...viewData,
72
- }
73
-
74
- let url = req.url || req.originalUrl
75
- const assetVersion = sails.config.inertia.version
76
- const currentVersion =
77
- typeof assetVersion == 'function'
78
- ? assetVersion()
79
- : assetVersion
80
-
81
- const page = {
82
- component,
83
- version: currentVersion,
84
- props: {},
85
- url,
86
- }
87
-
88
- // Implements inertia partial reload. See https://inertiajs.com/partial-reload
89
- let dataKeys
90
- if (
91
- req.get(PARTIAL_DATA) &&
92
- req.get(PARTIAL_COMPONENT) === component
93
- ) {
94
- dataKeys = req.get(PARTIAL_DATA).split(',')
95
- } else {
96
- dataKeys = Object.keys(allProps)
97
- }
98
-
99
- page.props = getPageProps(allProps, dataKeys)
100
-
101
- const queryParams = req.query
102
- if (req.method == 'GET' && Object.keys(queryParams).length) {
103
- // Keep original request query params
104
- url += `?${encode(queryParams)}`
105
- }
106
-
107
- // Implements inertia requests
108
- if (isInertiaRequest(req)) {
109
- return res.status(200).json(page)
110
- }
111
-
112
- // Implements full page reload
113
- return sails.hooks.views.render(rootView, {
114
- page,
115
- viewData: allViewData,
116
- })
117
- }
118
- hook.location = function (url = req.headers['referer']) {
119
- const statusCode = ['PUT', 'PATCH', 'DELETE'].includes(req.method)
120
- ? 303
121
- : 409
122
- res.status(statusCode)
123
- res.set('X-Inertia-Location', url)
124
- }
125
-
126
- // Set Inertia headers
127
- if (isInertiaRequest(req)) {
128
- res.set(INERTIA, true)
129
- res.set('Vary', 'Accept')
130
- }
131
- return next()
132
- },
133
- },
134
- },
135
- },
136
121
  }
137
122
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "inertia-sails",
3
- "version": "0.0.8",
3
+ "version": "0.1.0",
4
4
  "description": "The Sails adapter for Inertia.",
5
5
  "main": "index.js",
6
6
  "sails": {