From 8c91a055f43b0cde3089364ef7ecb2576b235b8b Mon Sep 17 00:00:00 2001 From: Ben Elferink Date: Wed, 29 Sep 2021 12:07:39 +0300 Subject: [PATCH] Added useful helper functions --- client/src/contexts/AuthContext.js | 13 ------------- client/src/functions/get-query.js | 19 +++++++++++++++++++ client/src/functions/get-token-payload.js | 11 +++++++++++ 3 files changed, 30 insertions(+), 13 deletions(-) create mode 100644 client/src/functions/get-query.js create mode 100644 client/src/functions/get-token-payload.js diff --git a/client/src/contexts/AuthContext.js b/client/src/contexts/AuthContext.js index 5f12a92..33b0caa 100644 --- a/client/src/contexts/AuthContext.js +++ b/client/src/contexts/AuthContext.js @@ -66,18 +66,6 @@ export function AuthProvider({children}) { } } - const getTokenPayload = () => { - if (!token) { - console.warn(`Token is ${null}/${undefined}`) - return {} - } - - const informativePart = token.split('.')[1] - const payload = JSON.parse(window.atob(informativePart)) - - return payload - } - // This side effect keeps local storage updated with recent token value, // making sure it can be re-used upon refresh or re-open browser useEffect(() => { @@ -104,7 +92,6 @@ export function AuthProvider({children}) { register, login, logout, - getTokenPayload, }}> {children} diff --git a/client/src/functions/get-query.js b/client/src/functions/get-query.js new file mode 100644 index 0000000..2865f84 --- /dev/null +++ b/client/src/functions/get-query.js @@ -0,0 +1,19 @@ +export default function getQuery(queryStr = '') { + if (queryStr) { + const queryObj = {} + const queryArr = ( + queryStr[0] === '?' ? queryStr.substring(1, queryStr.length) : queryStr + ).split('&') + + queryArr.forEach((str) => { + const [key, val] = str.split('=') + + queryObj[key] = val + }) + + return queryObj + } else { + console.warn('Query string is not defined') + return {} + } +} diff --git a/client/src/functions/get-token-payload.js b/client/src/functions/get-token-payload.js new file mode 100644 index 0000000..3290a61 --- /dev/null +++ b/client/src/functions/get-token-payload.js @@ -0,0 +1,11 @@ +export default function getTokenPayload(token = '') { + if (token) { + const informativePart = token.split('.')[1] + const payload = JSON.parse(window.atob(informativePart)) + + return payload + } else { + console.warn('Token is not defined') + return {} + } +}