@kaspernj/api-maker 1.0.133 → 1.0.134

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/package.json CHANGED
@@ -16,7 +16,7 @@
16
16
  ]
17
17
  },
18
18
  "name": "@kaspernj/api-maker",
19
- "version": "1.0.133",
19
+ "version": "1.0.134",
20
20
  "description": "",
21
21
  "main": "index.js",
22
22
  "repository": {
@@ -0,0 +1,57 @@
1
+ import Params from "./params.cjs"
2
+ import React from "react"
3
+
4
+ export default (WrappedComponent, ModelClass, args = {}) => class modelLoadWrapper extends React.PureComponent {
5
+ camelizedLower = ModelClass.modelName().camelizedLower()
6
+ paramsVariableName = `${ModelClass.modelName().paramKey()}_id`
7
+
8
+ state = {
9
+ model: undefined,
10
+ modelId: this.props.match.params[this.paramsVariableName] || this.props.match.params.id
11
+ }
12
+
13
+ componentDidMount() {
14
+ if (args.newIfNoId && !this.getModelId()) {
15
+ this.loadNewModel()
16
+ } else if (!args.optional || this.getModelId()) {
17
+ this.loadExistingModel()
18
+ }
19
+ }
20
+
21
+ getModelId() {
22
+ return this.props.match.params[this.paramsVariableName] || this.props.match.params.id
23
+ }
24
+
25
+ async loadExistingModel() {
26
+ const {modelId} = digs(this.shape, "modelId")
27
+ const query = await ModelClass.ransack({id_eq: modelId})
28
+
29
+ if (args.preload) query.preload(args.preload)
30
+ if (args.select) query.select(args.select)
31
+
32
+ const model = await query.first()
33
+
34
+ this.setState({model})
35
+ }
36
+
37
+ loadNewModel() {
38
+ const params = Params.parse()
39
+ const paramKey = ModelClass.modelName().paramKey()
40
+ const modelData = params[paramKey] || {}
41
+ const model = new ModelClass(modelData)
42
+
43
+ this.setState({model})
44
+ }
45
+
46
+ render() {
47
+ const {model, modelId} = digs(this.state, "model", "modelId")
48
+ const wrappedComponentProps = {}
49
+
50
+ wrappedComponentProps[this.camelizedLower] = model
51
+ wrappedComponentProps[`${this.camelizedLower}Id`] = modelId
52
+
53
+ return (
54
+ <WrappedComponent {...wrappedComponentProps} {...this.props} />
55
+ )
56
+ }
57
+ }
@@ -3,6 +3,10 @@ module.exports = class ModelName {
3
3
  this.data = data
4
4
  }
5
5
 
6
+ camelizedLower() {
7
+ return this.data.modelClassData.camelizedLower
8
+ }
9
+
6
10
  human (args) {
7
11
  let argsToUse = args
8
12
 
@@ -20,4 +24,8 @@ module.exports = class ModelName {
20
24
 
21
25
  return this.data.i18n.t(key)
22
26
  }
27
+
28
+ paramKey() {
29
+ return this.data.modelClassData.paramKey
30
+ }
23
31
  }