Skip to content

Commit 4b32c91

Browse files
author
Adrien Maret
authored
Add support for debug in browser from window object (#704)
Allows to set the window.debugKuzzleSdk variable to true to activate debug mode from the browser. Other changes avoid multiple calls to process.env print directly the object in the browser
1 parent fbe40ab commit 4b32c91

File tree

2 files changed

+17
-12
lines changed

2 files changed

+17
-12
lines changed

doc/7/essentials/debugging/index.md

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,6 @@ export DEBUG=kuzzle-sdk
3636
# Run your program
3737
```
3838

39-
In the Browser, you need to add the `debugKuzzleSdk` search param in the URL.
40-
41-
```
42-
http://my-application.by/devices?debugKuzzleSdk
43-
```
39+
In the Browser, you can:
40+
- add the `debugKuzzleSdk` search param in the URL. (e.g. `http://my-application.by/<path>?debugKuzzleSdk`)
41+
- set the `window.debugKuzzleSdk` variable to `true`

src/utils/debug.js

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,24 @@
1+
let NODE_DEBUG;
2+
13
function shouldDebug () {
24
if (typeof window === 'undefined') {
3-
const debugString = process.env.DEBUG || '';
5+
// Avoid multiple calls to process.env
6+
if (! NODE_DEBUG) {
7+
NODE_DEBUG = (process.env.DEBUG || '').includes('kuzzle-sdk');
8+
}
49

5-
return debugString.includes('kuzzle-sdk');
10+
return NODE_DEBUG;
611
}
712

8-
const url = new URL(window.location);
9-
10-
return url.searchParams.get('debugKuzzleSdk') !== null;
13+
return window.debugKuzzleSdk || new URL(window.location).searchParams.get('debugKuzzleSdk') !== null;
1114
}
1215

1316
/**
1417
* Print debug only if activated
1518
*
16-
* In Node.js, you can set the `DEBUG=kuzzle-sdk` env variable
19+
* In Node.js, you can set the `DEBUG=kuzzle-sdk` env variable.
1720
* In a browser, you can add the `?debugKuzzleSdk` in the URL
21+
* or set `window.debugKuzzleSdk` = true
1822
*/
1923
function debug (message, obj) {
2024
if (! shouldDebug()) {
@@ -25,8 +29,11 @@ function debug (message, obj) {
2529
console.log(message);
2630

2731
if (obj) {
32+
// Browser console can print directly objects
33+
const toPrint = typeof window === 'undefined' ? JSON.stringify(obj) : obj;
34+
2835
// eslint-disable-next-line no-console
29-
console.log(JSON.stringify(obj));
36+
console.log(toPrint);
3037
}
3138
}
3239

0 commit comments

Comments
 (0)