Skip to content

Commit

Permalink
small refactor to improve code structure of ui code
Browse files Browse the repository at this point in the history
  • Loading branch information
ziegfried committed Jun 17, 2020
1 parent 00090f8 commit 5b320a6
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 65 deletions.
44 changes: 44 additions & 0 deletions src/ui/pages/slack_alerts_setup/api.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { getFormKey, makeUrl } from './utils';

export function loadAlertActionConfig() {
return fetch(
makeUrl('/splunkd/__raw/servicesNS/-/-/alerts/alert_actions/slack?output_mode=json&_=' + Date.now())
)
.then((res) => {
if (!res.ok) {
throw new Error(`Failed to fetch config: HTTP status ${res.status}`);
}
return res.json();
})
.then((data) => {
const d = data.entry[0].content;
return {
webhook_url: d['param.webhook_url'],
from_user: d['param.from_user'],
from_user_icon: d['param.from_user_icon'],
};
});
}

export function updateAlertActionConfig(data) {
return fetch(
makeUrl(`/splunkd/__raw/servicesNS/-/slack_alerts/alerts/alert_actions/slack?output_mode=json`),
{
method: 'POST',
body: [
`param.webhook_url=${encodeURIComponent(data.webhook_url)}`,
`param.from_user=${encodeURIComponent(data.from_user)}`,
`param.from_user_icon=${encodeURIComponent(data.from_user_icon)}`,
].join('&'),
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest',
'X-Splunk-Form-Key': getFormKey(),
},
}
).then((res) => {
if (!res.ok) {
throw new Error(`Failed to save: HTTP status ${res.status}`);
}
});
}
70 changes: 5 additions & 65 deletions src/ui/pages/slack_alerts_setup/config.js
Original file line number Diff line number Diff line change
@@ -1,78 +1,18 @@
import { useState, useEffect, useCallback } from 'react';
import { makeUrl } from './utils';
import Toaster, { makeCreateToast } from '@splunk/react-toast-notifications/Toaster';
import { useCallback, useEffect, useState } from 'react';
import { loadAlertActionConfig, updateAlertActionConfig } from './api';
import { eq, makeUrl } from './utils';

const createToast = makeCreateToast(Toaster);

function getFormKey() {
const prefix = `splunkweb_csrf_token_${window.$C.MRSPARKLE_PORT_NUMBER}=`;
if (document.cookie) {
for (const chunk of document.cookie.split(';')) {
const cookie = String(chunk).trim();
if (cookie.startsWith(prefix)) {
return decodeURIComponent(cookie.slice(prefix.length));
}
}
}
}

export function loadConfig() {
return fetch(
makeUrl('/splunkd/__raw/servicesNS/-/-/alerts/alert_actions/slack?output_mode=json&_=' + Date.now())
)
.then((res) => {
if (!res.ok) {
throw new Error(`Failed to fetch config: HTTP status ${res.status}`);
}
return res.json();
})
.then((data) => {
const d = data.entry[0].content;
return {
webhook_url: d['param.webhook_url'],
from_user: d['param.from_user'],
from_user_icon: d['param.from_user_icon'],
};
});
}

export function updateConfig(data) {
return fetch(
makeUrl(`/splunkd/__raw/servicesNS/-/slack_alerts/alerts/alert_actions/slack?output_mode=json`),
{
method: 'POST',
body: [
`param.webhook_url=${encodeURIComponent(data.webhook_url)}`,
`param.from_user=${encodeURIComponent(data.from_user)}`,
`param.from_user_icon=${encodeURIComponent(data.from_user_icon)}`,
].join('&'),
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest',
'X-Splunk-Form-Key': getFormKey(),
},
}
).then((res) => {
if (!res.ok) {
throw new Error(`Failed to save: HTTP status ${res.status}`);
}
});
}

const eq = (a, b) => {
const ka = Object.keys(a);
const kb = Object.keys(b);
return ka.length === kb.length && ka.every((k) => k in b && a[k] === b[k]);
};

export function useSlackConfig() {
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const [savedData, setSavedData] = useState({});
const [data, setData] = useState({});

useEffect(() => {
loadConfig().then(
loadAlertActionConfig().then(
(cfg) => {
setSavedData(cfg);
setData(cfg);
Expand All @@ -94,7 +34,7 @@ export function useSlackConfig() {

const save = useCallback(() => {
if (!eq(savedData, data)) {
updateConfig(data).then(
updateAlertActionConfig(data).then(
() => {
setSavedData(data);
createToast({
Expand Down
18 changes: 18 additions & 0 deletions src/ui/pages/slack_alerts_setup/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,21 @@ export function makeUrl(path) {
const { LOCALE, MRSPARKLE_ROOT_PATH } = window.$C;
return `${MRSPARKLE_ROOT_PATH || ''}/${LOCALE}${path}`;
}

function getFormKey() {
const prefix = `splunkweb_csrf_token_${window.$C.MRSPARKLE_PORT_NUMBER}=`;
if (document.cookie) {
for (const chunk of document.cookie.split(';')) {
const cookie = String(chunk).trim();
if (cookie.startsWith(prefix)) {
return decodeURIComponent(cookie.slice(prefix.length));
}
}
}
}

const eq = (a, b) => {
const ka = Object.keys(a);
const kb = Object.keys(b);
return ka.length === kb.length && ka.every((k) => k in b && a[k] === b[k]);
};

0 comments on commit 5b320a6

Please sign in to comment.