diff options
| author | IT Fixcomart <it@fixcomart.co.id> | 2023-03-01 09:18:52 +0000 |
|---|---|---|
| committer | IT Fixcomart <it@fixcomart.co.id> | 2023-03-01 09:18:52 +0000 |
| commit | a7abbf4ddc70068620e9f44b74dc162ce2e16ee2 (patch) | |
| tree | 74f66253717515d364ce74bd8275015c1f829cbc /src/core/utils | |
| parent | 90e1edab9b6a8ccc09a49fed3addbec2cbc4e4c3 (diff) | |
| parent | a1b9b647a6c4bda1f5db63879639d44543f9557e (diff) | |
Merged in refactor (pull request #1)
Refactor
Diffstat (limited to 'src/core/utils')
| -rw-r--r-- | src/core/utils/address.js | 33 | ||||
| -rw-r--r-- | src/core/utils/apiOdoo.js | 44 | ||||
| -rw-r--r-- | src/core/utils/auth.js | 35 | ||||
| -rw-r--r-- | src/core/utils/cart.js | 48 | ||||
| -rw-r--r-- | src/core/utils/convertToOption.js | 11 | ||||
| -rw-r--r-- | src/core/utils/currencyFormat.js | 12 | ||||
| -rw-r--r-- | src/core/utils/formValidation.js | 107 | ||||
| -rw-r--r-- | src/core/utils/getFileBase64.js | 21 | ||||
| -rw-r--r-- | src/core/utils/greeting.js | 12 | ||||
| -rw-r--r-- | src/core/utils/mailer.js | 6 | ||||
| -rw-r--r-- | src/core/utils/slug.js | 34 | ||||
| -rw-r--r-- | src/core/utils/toTitleCase.js | 15 |
12 files changed, 102 insertions, 276 deletions
diff --git a/src/core/utils/address.js b/src/core/utils/address.js index c4a19af5..c545d34b 100644 --- a/src/core/utils/address.js +++ b/src/core/utils/address.js @@ -1,27 +1,28 @@ const getAddress = () => { - const address = localStorage.getItem('address'); - if (address) return JSON.parse(address); - return {}; + if (typeof window !== 'undefined') { + const address = localStorage.getItem('address') + if (address) return JSON.parse(address) + } + return {} } const setAddress = (address) => { - localStorage.setItem('address', JSON.stringify(address)); - return true; + if (typeof window !== 'undefined') { + localStorage.setItem('address', JSON.stringify(address)) + } + return } const getItemAddress = (key) => { - let address = getAddress(); - return address[key]; + let address = getAddress() + return address[key] } -const createOrUpdateItemAddress = (key, value) => { - let address = getAddress(); - address[key] = value; - setAddress(address); - return true; +const updateItemAddress = (key, value) => { + let address = getAddress() + address[key] = value + setAddress(address) + return } -export { - getItemAddress, - createOrUpdateItemAddress -};
\ No newline at end of file +export { getItemAddress, updateItemAddress } diff --git a/src/core/utils/apiOdoo.js b/src/core/utils/apiOdoo.js deleted file mode 100644 index 4d0adae3..00000000 --- a/src/core/utils/apiOdoo.js +++ /dev/null @@ -1,44 +0,0 @@ -import { getCookie, setCookie } from 'cookies-next'; -import axios from 'axios'; -import { getAuth } from './auth'; - -const renewToken = async () => { - let token = await axios.get(process.env.SELF_HOST + '/api/token'); - setCookie('token', token.data); - return token.data; -}; - -const getToken = async () => { - let token = getCookie('token'); - if (token == undefined) token = await renewToken(); - return token; -}; - -let connectionTry = 0; -const apiOdoo = async (method, url, data = {}, headers = {}) => { - try { - connectionTry++; - let token = await getToken(); - let axiosParameter = { - method, - url: process.env.ODOO_HOST + url, - headers: {'Authorization': token, ...headers} - } - const auth = getAuth(); - - if (auth) axiosParameter.headers['Token'] = auth.token; - if (method.toUpperCase() == 'POST') axiosParameter.headers['Content-Type'] = 'application/x-www-form-urlencoded'; - if (Object.keys(data).length > 0) axiosParameter.data = new URLSearchParams(Object.entries(data)).toString(); - - let res = await axios(axiosParameter); - if (res.data.status.code == 401 && connectionTry < 15) { - await renewToken(); - return apiOdoo(method, url, data, headers); - } - return res.data.result || []; - } catch (error) { - console.log(error) - } -} - -export default apiOdoo;
\ No newline at end of file diff --git a/src/core/utils/auth.js b/src/core/utils/auth.js index 62eba2c0..13e0e79d 100644 --- a/src/core/utils/auth.js +++ b/src/core/utils/auth.js @@ -1,38 +1,21 @@ -import { deleteCookie, getCookie, setCookie } from 'cookies-next'; -import { useEffect, useState } from 'react'; +import { deleteCookie, getCookie, setCookie } from 'cookies-next' const getAuth = () => { - let auth = getCookie('auth'); + let auth = getCookie('auth') if (auth) { - return JSON.parse(auth); + return JSON.parse(auth) } - return false; + return false } const setAuth = (user) => { - setCookie('auth', JSON.stringify(user)); - return true; + setCookie('auth', JSON.stringify(user)) + return true } const deleteAuth = () => { - deleteCookie('auth'); - return true; + deleteCookie('auth') + return true } -const useAuth = () => { - const [auth, setAuth] = useState(null); - - useEffect(() => { - const handleIsAuthenticated = () => setAuth(getAuth()); - handleIsAuthenticated(); - }, []); - - return [auth, setAuth]; -} - -export { - getAuth, - setAuth, - deleteAuth, - useAuth -};
\ No newline at end of file +export { getAuth, setAuth, deleteAuth } diff --git a/src/core/utils/cart.js b/src/core/utils/cart.js index 66efcbf2..fd42ee4e 100644 --- a/src/core/utils/cart.js +++ b/src/core/utils/cart.js @@ -1,36 +1,36 @@ const getCart = () => { - const cart = localStorage.getItem('cart'); - if (cart) return JSON.parse(cart); - return {}; + if (typeof window !== 'undefined') { + const cart = localStorage.getItem('cart') + if (cart) return JSON.parse(cart) + } + return {} } const setCart = (cart) => { - localStorage.setItem('cart', JSON.stringify(cart)); - return true; + if (typeof window !== 'undefined') { + localStorage.setItem('cart', JSON.stringify(cart)) + } + return true } -const getItemCart = (product_id) => { - let cart = getCart(); - return cart[product_id]; +const getItemCart = ({ productId }) => { + let cart = getCart() + return cart[productId] } -const createOrUpdateItemCart = (product_id, quantity, selected = false) => { - let cart = getCart(); - cart[product_id] = { product_id, quantity, selected }; - setCart(cart); - return true; +const updateItemCart = ({ productId, quantity, selected = false }) => { + let cart = getCart() + quantity = parseInt(quantity) + cart[productId] = { productId, quantity, selected } + setCart(cart) + return true } -const deleteItemCart = (product_id) => { - let cart = getCart(); - delete cart[product_id]; - setCart(cart); - return true; +const deleteItemCart = ({ productId }) => { + let cart = getCart() + delete cart[productId] + setCart(cart) + return true } -export { - getCart, - getItemCart, - createOrUpdateItemCart, - deleteItemCart -}
\ No newline at end of file +export { getCart, getItemCart, updateItemCart, deleteItemCart } diff --git a/src/core/utils/convertToOption.js b/src/core/utils/convertToOption.js deleted file mode 100644 index 08fec08f..00000000 --- a/src/core/utils/convertToOption.js +++ /dev/null @@ -1,11 +0,0 @@ -const convertToOption = (data) => { - if (data) { - return { - value: data.id, - label: data.name, - } - } - return null; -}; - -export default convertToOption;
\ No newline at end of file diff --git a/src/core/utils/currencyFormat.js b/src/core/utils/currencyFormat.js index dadeaec6..12b68111 100644 --- a/src/core/utils/currencyFormat.js +++ b/src/core/utils/currencyFormat.js @@ -1,8 +1,10 @@ -export default function currencyFormat(value) { +const currencyFormat = (value) => { const currency = new Intl.NumberFormat('id-ID', { - style: 'currency', + style: 'currency', currency: 'IDR', maximumFractionDigits: 0 - }); - return currency.format(value); -}
\ No newline at end of file + }) + return currency.format(value) +} + +export default currencyFormat diff --git a/src/core/utils/formValidation.js b/src/core/utils/formValidation.js deleted file mode 100644 index 0e83f4cc..00000000 --- a/src/core/utils/formValidation.js +++ /dev/null @@ -1,107 +0,0 @@ -import { useCallback, useEffect, useState } from "react"; - -const validateForm = (data, queries, hasChangedInputs = null) => { - let result = { valid: true, errors: {} }; - - for (const query in queries) { - if (!hasChangedInputs || (hasChangedInputs && hasChangedInputs[query])) { - const value = data[query]; - const rules = queries[query]; - let errors = []; - let label = null; - for (const rule of rules) { - let emailValidationRegex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; - if (rule.startsWith('label:')) { - label = rule.replace('label:', ''); - } else if (rule === 'required' && !value) { - errors.push('tidak boleh kosong'); - } else if (rule === 'email' && !value.match(emailValidationRegex)) { - errors.push('harus format johndoe@example.com'); - } else if (rule.startsWith('maxLength:')) { - let maxLength = parseInt(rule.replace('maxLength:', '')); - if (value && value.length > maxLength) errors.push(`maksimal ${maxLength} karakter`); - } - } - if (errors.length > 0) { - result.errors[query] = (label || query) + ' ' + errors.join(', '); - } - } - } - - if (Object.keys(result.errors).length > 0) { - result.valid = false; - } - - return result; -} - -const useFormValidation = ({ initialFormValue = {}, validationScheme = {} }) => { - const [ formInputs, setFormInputs ] = useState(initialFormValue); - const [ formErrors, setFormErrors ] = useState({}); - const [ formValidation ] = useState(validationScheme); - const [ hasChangedInputs, setHasChangedInputs ] = useState({}); - - const handleFormSubmit = (event, func) => { - if (event) { - event.preventDefault(); - - // Make all input to be has changed mode to revalidate - const changedInputs = {}; - for (const key in formInputs) changedInputs[key] = true; - setHasChangedInputs(changedInputs); - - const { valid, errors } = validateForm(formInputs, formValidation, changedInputs); - setFormErrors(errors); - - if (valid) func(); - } - }; - - const setChangedInput = (name, value = true) => { - setHasChangedInputs((hasChangedInputs) => ({ - ...hasChangedInputs, - [name]: value - })); - }; - - const handleInputChange = (event) => { - setFormInputs((formInputs) => ({ - ...formInputs, - [event.target.name]: event.target.value - })); - setChangedInput(event.target.name); - }; - - const handleSelectChange = useCallback((name, value) => { - setFormInputs((formInputs) => ({ - ...formInputs, - [name]: value - })); - setChangedInput(name); - }, []); - - const handleFormReset = () => { - setFormInputs(initialFormValue); - setFormErrors({}); - setHasChangedInputs({}); - } - - useEffect(() => { - if (formInputs) { - const { errors } = validateForm(formInputs, formValidation, hasChangedInputs); - setFormErrors(errors); - } - }, [ formInputs, formValidation, hasChangedInputs ]) - - return { - handleFormReset, - handleFormSubmit, - handleInputChange, - handleSelectChange, - hasChangedInputs, - formInputs, - formErrors - }; - }; - -export default useFormValidation;
\ No newline at end of file diff --git a/src/core/utils/getFileBase64.js b/src/core/utils/getFileBase64.js index 78013e43..4fa7316b 100644 --- a/src/core/utils/getFileBase64.js +++ b/src/core/utils/getFileBase64.js @@ -1,11 +1,12 @@ -const getFileBase64 = file => new Promise((resolve, reject) => { - let reader = new FileReader(); - reader.readAsBinaryString(file); - reader.onload = () => { - let result = reader.result; - resolve(btoa(result)); - }; - reader.onerror = error => reject(error); -}); +const getFileBase64 = (file) => + new Promise((resolve, reject) => { + let reader = new FileReader() + reader.readAsBinaryString(file) + reader.onload = () => { + let result = reader.result + resolve(btoa(result)) + } + reader.onerror = (error) => reject(error) + }) -export default getFileBase64;
\ No newline at end of file +export default getFileBase64 diff --git a/src/core/utils/greeting.js b/src/core/utils/greeting.js index 7dc19f8f..aaaade7a 100644 --- a/src/core/utils/greeting.js +++ b/src/core/utils/greeting.js @@ -1,9 +1,9 @@ const greeting = () => { - let hours = new Date().getHours(); - if (hours < 11) return 'Selamat Pagi'; - if (hours < 15) return 'Selamat Siang'; - if (hours < 18) return 'Selamat Sore'; - return 'Selamat Malam'; + let hours = new Date().getHours() + if (hours < 11) return 'Selamat Pagi' + if (hours < 15) return 'Selamat Siang' + if (hours < 18) return 'Selamat Sore' + return 'Selamat Malam' } -export default greeting;
\ No newline at end of file +export default greeting diff --git a/src/core/utils/mailer.js b/src/core/utils/mailer.js index 4e7ff7cc..cab66bec 100644 --- a/src/core/utils/mailer.js +++ b/src/core/utils/mailer.js @@ -1,4 +1,4 @@ -const nodemailer = require('nodemailer'); +const nodemailer = require('nodemailer') const mailer = nodemailer.createTransport({ port: process.env.MAIL_PORT, host: process.env.MAIL_HOST, @@ -7,6 +7,6 @@ const mailer = nodemailer.createTransport({ pass: process.env.MAIL_PASS }, secure: true -}); +}) -export default mailer;
\ No newline at end of file +export default mailer diff --git a/src/core/utils/slug.js b/src/core/utils/slug.js index 0a7d30fc..7010008a 100644 --- a/src/core/utils/slug.js +++ b/src/core/utils/slug.js @@ -1,25 +1,27 @@ -import toTitleCase from './toTitleCase'; +import toTitleCase from './toTitleCase' -const createSlug = (name, id) => { - let slug = name?.trim().replace(new RegExp(/[^A-Za-z0-9]/, 'g'), '-').toLowerCase() + '-' + id; - let splitSlug = slug.split('-'); - let filterSlugFromEmptyChar = splitSlug.filter(x => x != ''); - return filterSlugFromEmptyChar.join('-'); +const createSlug = (prefix, name, id) => { + let slug = + name + ?.trim() + .replace(new RegExp(/[^A-Za-z0-9]/, 'g'), '-') + .toLowerCase() + + '-' + + id + let splitSlug = slug.split('-') + let filterSlugFromEmptyChar = splitSlug.filter((x) => x != '') + return prefix + filterSlugFromEmptyChar.join('-') } const getIdFromSlug = (slug) => { - let id = slug.split('-'); - return id[id.length-1]; + let id = slug.split('-') + return id[id.length - 1] } const getNameFromSlug = (slug) => { - let name = slug.split('-'); - name.pop(); - return toTitleCase(name.join(' ')); + let name = slug.split('-') + name.pop() + return toTitleCase(name.join(' ')) } -export { - createSlug, - getIdFromSlug, - getNameFromSlug -};
\ No newline at end of file +export { createSlug, getIdFromSlug, getNameFromSlug } diff --git a/src/core/utils/toTitleCase.js b/src/core/utils/toTitleCase.js index 5cfd70d0..4335824d 100644 --- a/src/core/utils/toTitleCase.js +++ b/src/core/utils/toTitleCase.js @@ -1,8 +1,7 @@ -export default function toTitleCase(str) { - return str.replace( - /\w\S*/g, - function(txt) { - return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); - } - ); -}
\ No newline at end of file +const toTitleCase = (str) => { + return str.replace(/\w\S*/g, function (txt) { + return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase() + }) +} + +export default toTitleCase |
