@kaspernj/api-maker 1.0.346 → 1.0.348

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.346",
19
+ "version": "1.0.348",
20
20
  "type": "module",
21
21
  "description": "",
22
22
  "main": "index.js",
package/src/api.mjs CHANGED
@@ -1,7 +1,13 @@
1
1
  import config from "./config.mjs"
2
2
  import CustomError from "./custom-error.mjs"
3
3
  import FormDataObjectizer from "form-data-objectizer"
4
+ import Logger from "./logger.mjs"
4
5
  import qs from "qs"
6
+ import SessionStatusUpdater from "./session-status-updater.mjs"
7
+
8
+ const logger = new Logger({name: "ApiMaker / Api"})
9
+
10
+ // logger.setDebug(true)
5
11
 
6
12
  export default class Api {
7
13
  static get(path, pathParams = null) {
@@ -62,12 +68,14 @@ export default class Api {
62
68
  })
63
69
  }
64
70
 
65
- static requestLocal(args) {
71
+ static async requestLocal(args) {
66
72
  if (!args.headers) {
67
73
  args.headers = {}
68
74
  }
69
75
 
70
- const token = this._token()
76
+ const token = await this._token()
77
+
78
+ logger.debug(() => `Got token: ${token}`)
71
79
 
72
80
  if (token) {
73
81
  args.headers["X-CSRF-Token"] = token
@@ -82,19 +90,14 @@ export default class Api {
82
90
  args.data = args.rawData
83
91
  }
84
92
 
85
- return this.request(args)
93
+ return await this.request(args)
86
94
  }
87
95
 
88
96
  static put(path, data = {}) {
89
97
  return this.requestLocal({path, data, method: "PUT"})
90
98
  }
91
99
 
92
- static _token() {
93
- const tokenElement = document.querySelector("meta[name='csrf-token']")
94
-
95
- if (tokenElement)
96
- return tokenElement.getAttribute("content")
97
- }
100
+ static _token = async () => await SessionStatusUpdater.current().getCsrfToken()
98
101
 
99
102
  static _parseResponse(xhr) {
100
103
  const responseType = xhr.getResponseHeader("content-type")
@@ -14,7 +14,7 @@ import {ValidationErrors} from "./validation-errors.mjs"
14
14
  const shared = {}
15
15
 
16
16
  export default class ApiMakerCommandsPool {
17
- static addCommand (data, args = {}) {
17
+ static addCommand(data, args = {}) {
18
18
  let pool
19
19
 
20
20
  if (args.instant) {
@@ -34,17 +34,17 @@ export default class ApiMakerCommandsPool {
34
34
  return promiseResult
35
35
  }
36
36
 
37
- static current () {
37
+ static current() {
38
38
  if (!shared.currentApiMakerCommandsPool) shared.currentApiMakerCommandsPool = new ApiMakerCommandsPool()
39
39
 
40
40
  return shared.currentApiMakerCommandsPool
41
41
  }
42
42
 
43
- static flush () {
43
+ static flush() {
44
44
  ApiMakerCommandsPool.current().flush()
45
45
  }
46
46
 
47
- constructor () {
47
+ constructor() {
48
48
  this.flushCount = 0
49
49
  this.pool = {}
50
50
  this.poolData = {}
@@ -52,7 +52,7 @@ export default class ApiMakerCommandsPool {
52
52
  this.globalRequestData = {}
53
53
  }
54
54
 
55
- addCommand (data) {
55
+ addCommand(data) {
56
56
  return new Promise((resolve, reject) => {
57
57
  const id = this.currentId
58
58
  this.currentId += 1
@@ -87,11 +87,11 @@ export default class ApiMakerCommandsPool {
87
87
  })
88
88
  }
89
89
 
90
- commandsCount () {
90
+ commandsCount() {
91
91
  return Object.keys(this.pool)
92
92
  }
93
93
 
94
- async sendRequest ({commandSubmitData, url}) {
94
+ async sendRequest({commandSubmitData, url}) {
95
95
  let response
96
96
 
97
97
  for (let i = 0; i < 3; i++) {
@@ -113,7 +113,7 @@ export default class ApiMakerCommandsPool {
113
113
  throw new Error("Couldnt successfully execute request")
114
114
  }
115
115
 
116
- async flush () {
116
+ async flush() {
117
117
  if (this.commandsCount() == 0) {
118
118
  return
119
119
  }
@@ -166,7 +166,7 @@ export default class ApiMakerCommandsPool {
166
166
  }
167
167
  }
168
168
 
169
- handleFailedResponse (commandData, commandResponseData) {
169
+ handleFailedResponse(commandData, commandResponseData) {
170
170
  let error
171
171
 
172
172
  if (commandResponseData.error_type == "destroy_error") {
@@ -190,13 +190,13 @@ export default class ApiMakerCommandsPool {
190
190
  commandData.reject(error)
191
191
  }
192
192
 
193
- clearTimeout () {
193
+ clearTimeout() {
194
194
  if (this.flushTimeout) {
195
195
  clearTimeout(this.flushTimeout)
196
196
  }
197
197
  }
198
198
 
199
- isActive () {
199
+ isActive() {
200
200
  if (this.commandsCount() > 0) {
201
201
  return true
202
202
  }
@@ -208,7 +208,7 @@ export default class ApiMakerCommandsPool {
208
208
  return false
209
209
  }
210
210
 
211
- setFlushTimeout () {
211
+ setFlushTimeout() {
212
212
  this.clearTimeout()
213
213
  this.flushTimeout = setTimeout(() => this.flush(), 0)
214
214
  }
package/src/logger.mjs CHANGED
@@ -12,7 +12,13 @@ export default class ApiMakerLogger {
12
12
  }
13
13
 
14
14
  debug(message) {
15
- if (this.getDebug()) this.log(message)
15
+ if (this.getDebug()) {
16
+ this.log(message)
17
+ }
18
+ }
19
+
20
+ error(message) {
21
+ console.error(message)
16
22
  }
17
23
 
18
24
  log(message) {
@@ -5,32 +5,68 @@ import Logger from "./logger.mjs"
5
5
  import wakeEvent from "wake-event"
6
6
 
7
7
  const logger = new Logger({name: "ApiMaker / SessionStatusUpdater"})
8
+ const shared = {}
9
+
10
+ // logger.setDebug(true)
8
11
 
9
12
  export default class ApiMakerSessionStatusUpdater {
10
- static current () {
11
- if (!globalThis.apiMakerSessionStatusUpdater)
12
- globalThis.apiMakerSessionStatusUpdater = new ApiMakerSessionStatusUpdater()
13
+ static current(args) {
14
+ if (!shared.apiMakerSessionStatusUpdater) {
15
+ shared.apiMakerSessionStatusUpdater = new ApiMakerSessionStatusUpdater(args)
16
+ }
13
17
 
14
- return globalThis.apiMakerSessionStatusUpdater
18
+ return shared.apiMakerSessionStatusUpdater
15
19
  }
16
20
 
17
- constructor (args = {}) {
21
+ constructor(args = {}) {
18
22
  this.events = {}
19
23
  this.timeout = args.timeout || 600000
24
+ this.useMetaElement = ("useMetaElement" in args) ? args.useMetaElement : true
20
25
 
21
26
  this.connectOnlineEvent()
22
27
  this.connectWakeEvent()
23
28
  }
24
29
 
25
- connectOnlineEvent () {
30
+ connectOnlineEvent() {
26
31
  window.addEventListener("online", this.updateSessionStatus, false)
27
32
  }
28
33
 
29
- connectWakeEvent () {
34
+ connectWakeEvent() {
30
35
  wakeEvent(this.updateSessionStatus)
31
36
  }
32
37
 
33
- async sessionStatus () {
38
+ async getCsrfToken() {
39
+ if (this.csrfToken) {
40
+ logger.debug(`Get CSRF token from set variable: ${this.csrfToken}`)
41
+
42
+ return this.csrfToken
43
+ }
44
+
45
+ if (this.useMetaElement) {
46
+ const csrfTokenElement = document.querySelector("meta[name='csrf-token']")
47
+
48
+ if (csrfTokenElement) {
49
+ logger.debug(() => `Get CSRF token from meta element: ${csrfTokenElement.getAttribute("content")}`)
50
+
51
+ this.csrfToken = csrfTokenElement.getAttribute("content")
52
+
53
+ return this.csrfToken
54
+ }
55
+ }
56
+
57
+ logger.debug("Updating session status because no CSRF token set yet")
58
+ await this.updateSessionStatus()
59
+
60
+ if (this.csrfToken) {
61
+ logger.debug(() => `Returning CSRF token after updating session status: ${this.csrfToken}`)
62
+
63
+ return this.csrfToken
64
+ }
65
+
66
+ throw new Error("CSRF token hasn't been set")
67
+ }
68
+
69
+ sessionStatus() {
34
70
  return new Promise((resolve) => {
35
71
  let requestPath = ""
36
72
 
@@ -48,11 +84,11 @@ export default class ApiMakerSessionStatusUpdater {
48
84
  })
49
85
  }
50
86
 
51
- onSignedOut (callback) {
87
+ onSignedOut(callback) {
52
88
  this.addEvent("onSignedOut", callback)
53
89
  }
54
90
 
55
- startTimeout () {
91
+ startTimeout() {
56
92
  logger.debug("startTimeout")
57
93
 
58
94
  if (this.updateTimeout)
@@ -67,7 +103,7 @@ export default class ApiMakerSessionStatusUpdater {
67
103
  )
68
104
  }
69
105
 
70
- stopTimeout () {
106
+ stopTimeout() {
71
107
  if (this.updateTimeout)
72
108
  clearTimeout(this.updateTimeout)
73
109
  }
@@ -82,25 +118,30 @@ export default class ApiMakerSessionStatusUpdater {
82
118
  this.updateUserSessionsFromResult(result)
83
119
  }
84
120
 
85
- updateMetaElementsFromResult (result) {
121
+ updateMetaElementsFromResult(result) {
86
122
  logger.debug("updateMetaElementsFromResult")
87
- const csrfTokenElement = document.querySelector("meta[name='csrf-token']")
88
123
 
89
- if (csrfTokenElement) {
90
- logger.debug(() => `Changing token from "${csrfTokenElement.getAttribute("content")}" to "${result.csrf_token}"`)
91
- csrfTokenElement.setAttribute("content", result.csrf_token)
92
- } else {
93
- logger.debug("csrf token element couldn't be found")
124
+ this.csrfToken = result.csrf_token
125
+
126
+ if (this.useMetaElement) {
127
+ const csrfTokenElement = document.querySelector("meta[name='csrf-token']")
128
+
129
+ if (csrfTokenElement) {
130
+ logger.debug(() => `Changing token from "${csrfTokenElement.getAttribute("content")}" to "${result.csrf_token}"`)
131
+ csrfTokenElement.setAttribute("content", result.csrf_token)
132
+ } else {
133
+ logger.debug("csrf token element couldn't be found")
134
+ }
94
135
  }
95
136
  }
96
137
 
97
- updateUserSessionsFromResult (result) {
138
+ updateUserSessionsFromResult(result) {
98
139
  for (const scopeName in result.scopes) {
99
140
  this.updateUserSessionScopeFromResult(scopeName, result.scopes[scopeName])
100
141
  }
101
142
  }
102
143
 
103
- updateUserSessionScopeFromResult (scopeName, scope) {
144
+ updateUserSessionScopeFromResult(scopeName, scope) {
104
145
  const deviseIsSignedInMethodName = `is${inflection.camelize(scopeName)}SignedIn`
105
146
 
106
147
  if (!(deviseIsSignedInMethodName in Devise)) {