@mapomodule/core 1.0.0-alpha.0 → 1.0.0-alpha.13

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/CHANGELOG.md ADDED
@@ -0,0 +1,59 @@
1
+ # Change Log
2
+
3
+ All notable changes to this project will be documented in this file.
4
+ See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
+
6
+ # [1.0.0-alpha.13](https://github.com/lotrekagency/mapo/compare/v1.0.0-alpha.12...v1.0.0-alpha.13) (2022-03-01)
7
+
8
+
9
+ ### Features
10
+
11
+ * added snack message in the requst interceptor ([acf9cd1](https://github.com/lotrekagency/mapo/commit/acf9cd1efbabc13eb99af7f4bfe0dcf096112ec0))
12
+
13
+
14
+
15
+
16
+
17
+ # [1.0.0-alpha.10](https://github.com/lotrekagency/mapo/compare/v1.0.0-alpha.9...v1.0.0-alpha.10) (2022-02-11)
18
+
19
+
20
+ ### Bug Fixes
21
+
22
+ * fix crud requests without multipart policy ([5875833](https://github.com/lotrekagency/mapo/commit/5875833209872a2609b653a089fff80c447b14e9))
23
+
24
+
25
+ ### Features
26
+
27
+ * **core:** Completely rewritten multipart capabilities, now the crud helper autodiscovers whet to use a multipart request. ([0a6546c](https://github.com/lotrekagency/mapo/commit/0a6546c9adeaf1fcf57a88105101e476b8b786dc))
28
+
29
+
30
+
31
+
32
+
33
+ # [1.0.0-alpha.9](https://github.com/lotrekagency/mapo/compare/v1.0.0-alpha.8...v1.0.0-alpha.9) (2022-02-08)
34
+
35
+ **Note:** Version bump only for package @mapomodule/core
36
+
37
+
38
+
39
+
40
+
41
+ # [1.0.0-alpha.8](https://github.com/lotrekagency/mapo/compare/v1.0.0-alpha.7...v1.0.0-alpha.8) (2022-01-23)
42
+
43
+
44
+ ### Bug Fixes
45
+
46
+ * **auth:** logout user only on 401 ([818f3d5](https://github.com/lotrekagency/mapo/commit/818f3d5ff315635438ac9bc9566a1b2fd2c5cf03))
47
+ * **permission:** fix bad store initialization on ssr ([f075824](https://github.com/lotrekagency/mapo/commit/f075824561d6a71ce07ecbba70e994102abd623b))
48
+ * **permissions:** add route permissions with routename instead on path ([16ff6ee](https://github.com/lotrekagency/mapo/commit/16ff6eee5e3a8ddbf9e7aea1ba05e8a88fb43932))
49
+
50
+
51
+
52
+
53
+
54
+ # [1.0.0-alpha.6](https://github.com/lotrekagency/mapo/compare/v1.0.0-alpha.5...v1.0.0-alpha.6) (2021-12-26)
55
+
56
+
57
+ ### Features
58
+
59
+ * **core:** reject promise for crud methods if no endpoint was passed during configuration ([bb8d447](https://github.com/lotrekagency/mapo/commit/bb8d4474efe41af5d7f38dbcd47731133d6ba154))
package/LICENSE.md ADDED
@@ -0,0 +1,20 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) Lotrek 2021
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
package/api/crud.js CHANGED
@@ -1,4 +1,13 @@
1
- const trimslashes = (str) => str.replace(/^\/|\/$/g, '')
1
+ const transformRequestInMultipart = require('@mapomodule/core/api/multipart')
2
+ const trimslashes = (str) => (str || "").replace(/^\/|\/$/g, '')
3
+ const preparePayload = (payload, options) => {
4
+ const { multipart } = (options || {})
5
+ if (!(payload instanceof FormData) && (typeof multipart === 'string') && multipart !== 'disable') {
6
+ payload = transformRequestInMultipart(payload, multipart);
7
+ }
8
+ return payload
9
+ }
10
+ const endpointError = "This crud is badly configured. No endpoint was passed"
2
11
 
3
12
  /**
4
13
  * This function generates a fully functional crud helper given the endpoint.
@@ -16,7 +25,8 @@ const createRepository = ($axios) => (endpoint, higherConf = {}) => ({
16
25
  * @returns {Promise<external:AxiosResponse>}
17
26
  */
18
27
  list(config) {
19
- return $axios.$get(`/${trimslashes(endpoint)}/`, { ...higherConf, ...config })
28
+ const func = $axios.$get(`/${trimslashes(endpoint)}/`, { ...higherConf, ...config })
29
+ return endpoint !== null ? func : Promise.reject(endpointError)
20
30
  },
21
31
 
22
32
  /**
@@ -24,10 +34,13 @@ const createRepository = ($axios) => (endpoint, higherConf = {}) => ({
24
34
  * @alias $api.crud.create
25
35
  * @param {Object} payload The payload containing the data that we want to send.
26
36
  * @param {external:AxiosRequestConfig} [config] This is a further axios configuration object that allows you to override the options previously setted.
37
+ * @param {MapoRequestConfig} options Additional option configuration. Here you can configure some mapo reserved options. Like the multipart autodiscover politic.
27
38
  * @returns {Promise<external:AxiosResponse>}
28
39
  */
29
- create(payload, config) {
30
- return $axios.$post(`/${trimslashes(endpoint)}/`, payload, { ...higherConf, ...config })
40
+ create(payload, config, options) {
41
+
42
+ const func = $axios.$post(`/${trimslashes(endpoint)}/`, preparePayload(payload, options), { ...higherConf, ...config })
43
+ return endpoint !== null ? func : Promise.reject(endpointError)
31
44
  },
32
45
 
33
46
  /**
@@ -38,7 +51,8 @@ const createRepository = ($axios) => (endpoint, higherConf = {}) => ({
38
51
  * @returns {Promise<external:AxiosResponse>}
39
52
  */
40
53
  detail(id, config) {
41
- return $axios.$get(`/${trimslashes(endpoint)}/${id}/`, { ...higherConf, ...config })
54
+ const func = $axios.$get(`/${trimslashes(endpoint)}/${id}/`, { ...higherConf, ...config })
55
+ return endpoint !== null ? func : Promise.reject(endpointError)
42
56
  },
43
57
 
44
58
  /**
@@ -46,10 +60,12 @@ const createRepository = ($axios) => (endpoint, higherConf = {}) => ({
46
60
  * @alias $api.crud.updateOrCreate
47
61
  * @param {Object} payload The payload containing the data that we want to send.
48
62
  * @param {external:AxiosRequestConfig} [config] This is a further axios configuration object that allows you to override the options previously setted.
63
+ * @param {MapoRequestConfig} options Additional option configuration. Here you can configure some mapo reserved options. Like the multipart autodiscover politic.
49
64
  * @returns {Promise<external:AxiosResponse>}
50
65
  */
51
- updateOrCreate(payload, config) {
52
- return payload.id ? this.update(payload.id, payload, { ...higherConf, ...config }) : this.create(payload, { ...higherConf, ...config })
66
+ updateOrCreate(payload, config, options) {
67
+ const func = payload.id ? this.update(payload.id, payload, { ...higherConf, ...config }, options) : this.create(payload, { ...higherConf, ...config }, options)
68
+ return endpoint !== null ? func : Promise.reject(endpointError)
53
69
  },
54
70
 
55
71
  /**
@@ -58,10 +74,12 @@ const createRepository = ($axios) => (endpoint, higherConf = {}) => ({
58
74
  * @param {String} id The id of the data we want to update.
59
75
  * @param {Object} payload The payload containing the data that we want to send.
60
76
  * @param {external:AxiosRequestConfig} [config] This is a further axios configuration object that allows you to override the options previously setted.
77
+ * @param {MapoRequestConfig} options Additional option configuration. Here you can configure some mapo reserved options. Like the multipart autodiscover politic.
61
78
  * @returns {Promise<external:AxiosResponse>}
62
79
  */
63
- update(id, payload, config) {
64
- return $axios.$put(`/${trimslashes(endpoint)}/${id}/`, payload, { ...higherConf, ...config })
80
+ update(id, payload, config, options) {
81
+ const func = $axios.$put(`/${trimslashes(endpoint)}/${id}/`, preparePayload(payload, options), { ...higherConf, ...config })
82
+ return endpoint !== null ? func : Promise.reject(endpointError)
65
83
  },
66
84
 
67
85
  /**
@@ -70,10 +88,12 @@ const createRepository = ($axios) => (endpoint, higherConf = {}) => ({
70
88
  * @param {String} id The id of the data we want to partially update.
71
89
  * @param {Object} payload The payload containing the data that we want to send.
72
90
  * @param {external:AxiosRequestConfig} [config] This is a further axios configuration object that allows you to override the options previously setted.
91
+ * @param {MapoRequestConfig} options Additional option configuration. Here you can configure some mapo reserved options. Like the multipart autodiscover politic.
73
92
  * @returns {Promise<external:AxiosResponse>}
74
93
  */
75
- partialUpdate(id, payload, config) {
76
- return $axios.$patch(`/${trimslashes(endpoint)}/${id}/`, payload, { ...higherConf, ...config })
94
+ partialUpdate(id, payload, config, options) {
95
+ const func = $axios.$patch(`/${trimslashes(endpoint)}/${id}/`, preparePayload(payload, options), { ...higherConf, ...config })
96
+ return endpoint !== null ? func : Promise.reject(endpointError)
77
97
  },
78
98
  /**
79
99
  * This makes a DELETE http call to the crud endpoint slash the given id. Returns as a promise the server response.
@@ -83,7 +103,8 @@ const createRepository = ($axios) => (endpoint, higherConf = {}) => ({
83
103
  * @returns {Promise<external:AxiosResponse>}
84
104
  */
85
105
  delete(id, config) {
86
- return $axios.$delete(`/${trimslashes(endpoint)}/${id}/`, { ...higherConf, ...config })
106
+ const func = $axios.$delete(`/${trimslashes(endpoint)}/${id}/`, { ...higherConf, ...config })
107
+ return endpoint !== null ? func : Promise.reject(endpointError)
87
108
  }
88
109
  })
89
110
  /**
@@ -96,4 +117,10 @@ const createRepository = ($axios) => (endpoint, higherConf = {}) => ({
96
117
  * @see https://axios-http.com/docs/req_config
97
118
  */
98
119
 
120
+ /**
121
+ * Additional option configuration. Here you can configure some mapo reserved options.
122
+ * @typedef {MapoRequestConfig} MapoRequestConfig
123
+ * @property {string} multipart - Set the multipart politic. Accepts `'auto'|'force|'disable'`. If auto is set the request is transformed in multipart if any file is in the payload. If set to force the request is transformed in multipart no matter if files are found. If set to `'disable'` the request is never transformed in multipart.
124
+ */
125
+
99
126
  module.exports = createRepository
package/api/multipart.js CHANGED
@@ -1,4 +1,4 @@
1
- const deepClone = require('@mapomodule/utils/helpers/objHelpers').deepClone
1
+ const { deepClone, getPointed, setPointed, filesInObject } = require('@mapomodule/utils/helpers/objHelpers')
2
2
 
3
3
  /**
4
4
  * This lets you transform a js object containing files in a multipart request with all the classic data in a single attribute (data)
@@ -6,33 +6,29 @@ const deepClone = require('@mapomodule/utils/helpers/objHelpers').deepClone
6
6
  *
7
7
  * @alias $api.multipart
8
8
  * @param {Object} payload The payload of the request that needs to be trasformed.
9
- * @param {String[]} file_attributes The list of dotted path of all the file attributes that need to be attached to the request.
9
+ * @param {String | String[]} file_attributes The list of dotted path of all the file attributes that need to be attached to the request. If unset autodiscovery is applyed. If set to 'fallback' if no files are found it returns the payload as it is.
10
10
  * @returns {external:FormData}
11
11
  */
12
- function transformRequestInMultipart(payload, file_attributes = []) {
13
-
14
- const cleanObject = (object, file_attributes, base = '', files = {}) => {
15
- for (const key in object) {
16
- if (file_attributes.includes(key) && object[key] && typeof object[key] != 'string') {
17
- files[base + key] = object[key];
18
- delete object[key];
19
- }
20
- if (typeof object[key] == 'object') {
21
- cleanObject(object[key], file_attributes, base + key + '.', files);
22
- }
23
- if (file_attributes.includes(key) && object[key] && typeof object[key] == 'string') {
24
- delete object[key];
25
- }
12
+ function transformRequestInMultipart(payload, file_attributes = "auto") {
13
+ var file_paths = []
14
+ if (["auto", "force"].includes(file_attributes)) {
15
+ file_paths = filesInObject(payload)
16
+ if (file_attributes == "auto" && !file_paths.length){
17
+ return payload
26
18
  }
27
- return { data: object, files: files };
19
+ } else if (Array.isArray(file_attributes)) {
20
+ file_paths = file_attributes
28
21
  }
29
-
30
- const tmp_obj = deepClone(payload);
31
- const blob = cleanObject(tmp_obj, file_attributes);
22
+ const data = deepClone(payload);
23
+ const files = file_paths.reduce((acc, path) => {
24
+ const file = getPointed(data, path, undefined)
25
+ setPointed(data, path, undefined);
26
+ return { [path]: file, ...acc }
27
+ }, {})
32
28
  const formData = new FormData();
33
- formData.append('data', JSON.stringify(blob.data));
34
- for (const key in blob.files) {
35
- formData.append(key, blob.files[key]);
29
+ formData.append('data', JSON.stringify(data));
30
+ for (const key in files) {
31
+ formData.append(key, files[key]);
36
32
  }
37
33
  return formData;
38
34
  }
package/index.js CHANGED
@@ -2,6 +2,13 @@ import createRepository from '@mapomodule/core/api/crud'
2
2
  import transformRequestInMultipart from '@mapomodule/core/api/multipart'
3
3
  import initInterceptors from '@mapomodule/core/interceptor'
4
4
 
5
+ function getRouteMiddlewares(route) {
6
+ const meta = Array.isArray(route?.meta) ? route.meta[0] : route.meta
7
+ const { middleware } = meta || {}
8
+ return (typeof middleware === "string" ? [middleware] : middleware) || []
9
+ }
10
+
11
+
5
12
  export default (ctx, inject) => {
6
13
 
7
14
  initInterceptors(ctx)
@@ -39,9 +46,23 @@ export default (ctx, inject) => {
39
46
  get token() { return ctx.store.getters['mapo/user/token'] },
40
47
  get info() { return ctx.store.getters['mapo/user/info'] },
41
48
  get username() { return ctx.store.getters['mapo/user/username'] },
42
- get permissions() { return ctx.store.getters['mapo/user/pagePermission'](ctx.app.context.route.path) },
49
+ get permissions() { return ctx.store.getters['mapo/user/pagePermission'](ctx.app?.context?.route?.name || "") },
43
50
  get role() { return ctx.store.getters['mapo/user/role'] }
44
- }
51
+ },
52
+ /**
53
+ *
54
+ * This returns the current route middlewares if routemeta is enabled.
55
+ */
56
+ get routeMiddlewares() {
57
+ return getRouteMiddlewares(ctx.app?.context?.route || {})
58
+ },
59
+ /**
60
+ *
61
+ * This returns the middlewares of a given route if routemeta is enabled.
62
+ * @param { Object } route { meta } the route object with meta info.
63
+ * @returns { Array }
64
+ */
65
+ getRouteMiddlewares: getRouteMiddlewares
45
66
  },
46
67
  /**
47
68
  * From here you can manage the default popup messaging system of mapo.
@@ -9,19 +9,23 @@ module.exports = ({ $axios, store }) => {
9
9
  })
10
10
 
11
11
  $axios.onResponse((response) => {
12
- if (response.status !== 200) {
13
- if (response.status === 401 || response.status === 402 || response.status === 403) {
14
- store.dispatch('mapo/user/logout');
15
- }
12
+ if (response.status === 401) {
13
+ store.dispatch('mapo/user/logout');
14
+ }
15
+ if (response.status == 403) {
16
+ store.dispatch("mapo/app/showSnackMessage", { message: "Permission denied..", color: "error" })
16
17
  }
17
18
  return response
18
19
  })
19
-
20
+
20
21
  $axios.onError((error) => {
21
22
  const { status } = error.response || {}
22
- if (status === 401 || status === 402 || status === 403) {
23
+ if (status === 401) {
23
24
  store.dispatch('mapo/user/logout');
24
25
  }
26
+ if (status == 403) {
27
+ store.dispatch("mapo/app/showSnackMessage", { message: "Permission denied..", color: "error" })
28
+ }
25
29
  return Promise.reject(error)
26
30
  })
27
31
  }
@@ -5,7 +5,7 @@ Middleware.permissions = Middleware.permissions || async function ({ route, erro
5
5
  if (!route.meta.permissions) return
6
6
  const userInfo = store.getters['mapo/user/info']
7
7
  if (userInfo.is_superuser) {
8
- await store.dispatch('mapo/user/addPagePermission', {key: route.path, value: ["add", "change", "delete", "view"]})
8
+ await store.dispatch('mapo/user/addPagePermission', {key: route.name, value: ["add", "change", "delete", "view"]})
9
9
  return
10
10
  }
11
11
  const { model } = route.meta.permissions
@@ -13,7 +13,7 @@ Middleware.permissions = Middleware.permissions || async function ({ route, erro
13
13
  if (!userPermission.includes('view')) {
14
14
  return error({ statusCode: 404, message: 'This page could not be found' })
15
15
  } else {
16
- await store.dispatch('mapo/user/addPagePermission', {key: route.path, value: userPermission})
16
+ await store.dispatch('mapo/user/addPagePermission', {key: route.name, value: userPermission})
17
17
  return
18
18
  }
19
19
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mapomodule/core",
3
- "version": "1.0.0-alpha.0",
3
+ "version": "1.0.0-alpha.13",
4
4
  "description": "This is part of Mapo nuxt module. Injects the core mapo plugin helpers.",
5
5
  "author": "bnznamco <gabriele.baldi.01@gmail.com>",
6
6
  "keywords": [
@@ -13,10 +13,10 @@
13
13
  "repository": "https://github.com/lotrekagency/mapo",
14
14
  "main": "./module.js",
15
15
  "dependencies": {
16
- "@mapomodule/utils": "^1.0.0-alpha.0"
16
+ "@mapomodule/utils": "^1.0.0-alpha.13"
17
17
  },
18
18
  "publishConfig": {
19
19
  "access": "public"
20
20
  },
21
- "gitHead": "801fe7de298f06e335793291c4955abf62edd077"
21
+ "gitHead": "b0fac0f5ebde4c65cc5347dbb841392dc04ef5e8"
22
22
  }