From 750f212ef1982d6050d4ded05ce1a79181fcf8bc Mon Sep 17 00:00:00 2001 From: ahmetkuslular Date: Fri, 1 Oct 2021 17:20:31 +0300 Subject: [PATCH 01/20] fix: changed components configuration --- src/client/client.js | 9 +++-- src/server.js | 36 +++++++++---------- src/universal/core/route/routeConstants.js | 9 +++-- .../core/route/routesWithComponents.js | 10 ++++-- src/universal/model/Component.js | 13 ++++--- src/universal/partials/Welcome/partials.js | 10 ++++-- src/universal/utils/helper.js | 34 ++++++++++++++++++ 7 files changed, 87 insertions(+), 34 deletions(-) diff --git a/src/client/client.js b/src/client/client.js index e98cf75..68f5240 100644 --- a/src/client/client.js +++ b/src/client/client.js @@ -1,10 +1,15 @@ import 'whatwg-fetch'; import Eev from 'eev'; +const appConfig = require('__APP_CONFIG__'); + +const defaultEventBusName = 'eventBus'; /* eslint-disable-next-line */ -"__V_styles__" +('__V_styles__'); if (!window.HbEventBus) { - window.HbEventBus = new Eev(); + const name = appConfig.eventBusName || defaultEventBusName; + + window[name] = new Eev(); window.voltran_project_version = process.env.APP_BUILD_VERSION || '1.0.0'; } diff --git a/src/server.js b/src/server.js index ed2b6f6..b93ee03 100644 --- a/src/server.js +++ b/src/server.js @@ -2,7 +2,7 @@ import newrelic from './universal/tools/newrelic/newrelic'; import cookieParser from 'cookie-parser'; -import {compose} from 'compose-middleware'; +import { compose } from 'compose-middleware'; import compression from 'compression'; import path from 'path'; import Hiddie from 'hiddie'; @@ -18,9 +18,9 @@ import render from './render'; import registerControllers from './api/controllers'; import renderMultiple from './renderMultiple'; -import {createCacheManagerInstance} from "./universal/core/cache/cacheUtils"; +import { createCacheManagerInstance } from './universal/core/cache/cacheUtils'; -import {HTTP_STATUS_CODES} from './universal/utils/constants'; +import { HTTP_STATUS_CODES } from './universal/utils/constants'; import voltranConfig from '../voltran.config'; @@ -39,7 +39,7 @@ process.on('unhandledRejection', (reason, p) => { process.exit(1); }); -process.on('message', (message) => { +process.on('message', message => { handleProcessMessage(message); }); @@ -52,13 +52,13 @@ Object.keys(fragmentManifest).forEach(index => { fragments.push(name); }); -const handleProcessMessage = (message) => { +const handleProcessMessage = message => { if (message?.msg?.action === 'deleteallcache') { createCacheManagerInstance().removeAll(); } else if (message?.msg?.action === 'deletecache') { createCacheManagerInstance().remove(message?.msg?.key); } -} +}; const handleUrls = async (req, res, next) => { if (req.url === '/' && req.method === 'GET') { @@ -67,33 +67,33 @@ const handleUrls = async (req, res, next) => { res.setHeader('Content-Type', prom.register.contentType); res.end(prom.register.metrics()); } else if (req.url === '/status' && req.method === 'GET') { - res.json({success: true, version: process.env.GO_PIPELINE_LABEL || '1.0.0', fragments}); + res.json({ success: true, version: process.env.GO_PIPELINE_LABEL || '1.0.0', fragments }); } else if ((req.url === '/statusCheck' || req.url === '/statuscheck') && req.method === 'GET') { - res.json({success: true, version: process.env.GO_PIPELINE_LABEL || '1.0.0', fragments}); + res.json({ success: true, version: process.env.GO_PIPELINE_LABEL || '1.0.0', fragments }); } else if (req.url === '/deleteallcache' && req.method === 'GET') { process.send({ msg: { - action: 'deleteallcache', + action: 'deleteallcache' }, options: { - forwardAllWorkers: true, - }, + forwardAllWorkers: true + } }); - res.json({success: true}); + res.json({ success: true }); } else if (req.path === '/deletecache' && req.method === 'GET') { if (req?.query?.key) { process.send({ msg: { action: 'deletecache', - key: req?.query?.key, + key: req?.query?.key }, options: { - forwardAllWorkers: true, - }, + forwardAllWorkers: true + } }); - res.json({success: true}); + res.json({ success: true }); } else { - res.json({success: false}); + res.json({ success: false }); } } else { newrelic?.setTransactionName?.(req.path); @@ -142,7 +142,7 @@ const locals = async (req, res, next) => { req.url = xss(req.url); if (req.headers['set-cookie']) { - req.headers['cookie'] = req.headers['cookie'] || req.headers['set-cookie']?.join(); + req.headers.cookie = req.headers.cookie || req.headers['set-cookie']?.join(); delete req.headers['set-cookie']; } diff --git a/src/universal/core/route/routeConstants.js b/src/universal/core/route/routeConstants.js index 6a42197..58d372e 100644 --- a/src/universal/core/route/routeConstants.js +++ b/src/universal/core/route/routeConstants.js @@ -1,12 +1,15 @@ import values from 'lodash/values'; +import { generateComponents } from '../../utils/helper'; -const components = require('__V_COMPONENTS__'); +const componentConfig = require('__V_COMPONENTS__'); + +const components = generateComponents(componentConfig.default); const ROUTE_PATHS = {}; const ROUTE_CONFIGS = {}; -Object.keys(components.default).forEach(path => { - const info = components.default[path]; +Object.keys(components).forEach(path => { + const info = components[path]; ROUTE_PATHS[info.name] = path; ROUTE_CONFIGS[path] = { routeName: info.name, diff --git a/src/universal/core/route/routesWithComponents.js b/src/universal/core/route/routesWithComponents.js index c70e910..ad5afff 100644 --- a/src/universal/core/route/routesWithComponents.js +++ b/src/universal/core/route/routesWithComponents.js @@ -1,9 +1,13 @@ -const components = require('__V_COMPONENTS__'); +import { generateComponents } from '../../utils/helper'; + +const componentConfig = require('__V_COMPONENTS__'); + +const components = generateComponents(componentConfig.default); const routesWithComponents = {}; -Object.keys(components.default).forEach(path => { - const info = components.default[path]; +Object.keys(components).forEach(path => { + const info = components[path]; routesWithComponents[path] = info.fragment; }); diff --git a/src/universal/model/Component.js b/src/universal/model/Component.js index 90ef581..7d20da7 100644 --- a/src/universal/model/Component.js +++ b/src/universal/model/Component.js @@ -1,7 +1,10 @@ import routesWithComponents from '../core/route/routesWithComponents'; -import { createComponentName } from '../utils/helper'; +// eslint-disable-next-line import/named +import { createComponentName, generateComponents } from '../utils/helper'; -const COMPONENTS = require('__V_COMPONENTS__').default; +const componentConfig = require('__V_COMPONENTS__'); + +const components = generateComponents(componentConfig.default); export default class Component { static getComponentName = path => { @@ -11,15 +14,15 @@ export default class Component { static getComponentPath = name => `/${name}`; static getComponentIsMobileFragment = path => { - return COMPONENTS[path].isMobileFragment ? COMPONENTS[path].isMobileFragment : false; + return components[path].isMobileFragment ? components[path].isMobileFragment : false; }; static getComponentIsFullWidth = path => { - return COMPONENTS[path].fullWidth ? COMPONENTS[path].fullWidth : false; + return components[path].fullWidth ? components[path].fullWidth : false; }; static getComponentIsPreviewQuery = path => { - return COMPONENTS[path].isPreviewQuery || true; + return components[path].isPreviewQuery || true; }; static getComponentObjectWithPath = path => routesWithComponents[path]; diff --git a/src/universal/partials/Welcome/partials.js b/src/universal/partials/Welcome/partials.js index db298e6..7f57918 100644 --- a/src/universal/partials/Welcome/partials.js +++ b/src/universal/partials/Welcome/partials.js @@ -1,9 +1,13 @@ -const components = require('__V_COMPONENTS__'); +import { generateComponents } from '../../utils/helper'; + +const componentConfig = require('__V_COMPONENTS__'); + +const components = generateComponents(componentConfig.default); const partials = []; -Object.keys(components.default).forEach(path => { - const info = components.default[path]; +Object.keys(components).forEach(path => { + const info = components[path]; partials.push({ name: info.fragmentName, url: path, diff --git a/src/universal/utils/helper.js b/src/universal/utils/helper.js index 799edaa..8d9332a 100644 --- a/src/universal/utils/helper.js +++ b/src/universal/utils/helper.js @@ -9,6 +9,40 @@ export const createComponentName = routePath => { return routePath.split('/').join(''); }; +const toCamel = (value = '') => { + return value + .replace(/([-_][a-z])/gi, key => + key + .toUpperCase() + .replace('-', ' ') + .replace('_', ' ') + ) + .toLowerCase(); +}; + +export const generateComponents = ({ + paths = {}, + components = [], + defaultConfig = {}, + customConfig = {} +}) => { + let result = {}; + Object.entries(paths).forEach(([key, value]) => { + result = { + ...result, + [value]: { + fragment: components[value], + fragmentName: toCamel(key), + name: key, + status: 'dev', + ...defaultConfig, + ...customConfig[value] + } + }; + }); + return result; +}; + export function guid() { return `${s4()}${s4()}-${s4()}-4${s4().substr(0, 3)}-${s4()}-${s4()}${s4()}${s4()}`.toLowerCase(); } From 36fd1a97d62fde644bd0c6f70d03e752a8c0948f Mon Sep 17 00:00:00 2001 From: ahmetkuslular Date: Mon, 1 Nov 2021 13:19:32 +0300 Subject: [PATCH 02/20] Added Request Dispatcher Layer --- .eslintrc.js | 10 ++- config/string.js | 39 +++++++-- package.json | 4 + src/client/client.js | 9 +-- src/render.js | 11 ++- src/renderMultiple.js | 47 +++++++---- src/universal/components/Preview.js | 7 +- .../RequestDispatcher/RequestDispatcher.js | 63 +++++++++++++++ .../RequestDispatcher.utils.js | 12 +++ .../components/RequestDispatcher/index.js | 1 + src/universal/core/route/components.js | 29 +++++++ src/universal/core/route/dictionary.js | 10 +++ src/universal/core/route/routeConstants.js | 6 +- .../core/route/routesWithComponents.js | 6 +- src/universal/model/Component.js | 19 ++--- src/universal/model/Renderer.js | 19 +++-- src/universal/partials/Welcome/partials.js | 6 +- src/universal/service/RenderService.js | 21 ++++- src/universal/utils/baseRenderHtml.js | 20 ++--- src/universal/utils/helper.js | 20 +++-- webpack.client.config.js | 81 +++++++++---------- 21 files changed, 304 insertions(+), 136 deletions(-) create mode 100644 src/universal/components/RequestDispatcher/RequestDispatcher.js create mode 100644 src/universal/components/RequestDispatcher/RequestDispatcher.utils.js create mode 100644 src/universal/components/RequestDispatcher/index.js create mode 100644 src/universal/core/route/components.js create mode 100644 src/universal/core/route/dictionary.js diff --git a/.eslintrc.js b/.eslintrc.js index e4fcb8b..48e05a8 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -7,7 +7,7 @@ module.exports = { window: true, hepsiBus: true, global: true, - jest: true, + jest: true }, parserOptions: { ecmaFeatures: { @@ -46,7 +46,13 @@ module.exports = { 'no-nested-ternary': 'off', 'no-underscore-dangle': 'off', 'consistent-return': 'off', - 'array-callback-return': 'off' + 'array-callback-return': 'off', + 'no-restricted-syntax': [ + 'error', + 'FunctionExpression', + 'WithStatement', + "BinaryExpression[operator='in']" + ] }, env: { jest: true, diff --git a/config/string.js b/config/string.js index d7e5fed..563dc13 100644 --- a/config/string.js +++ b/config/string.js @@ -7,12 +7,18 @@ const voltranConfig = require('../voltran.config'); const prometheusFile = voltranConfig.monitoring.prometheus; -function replaceString () { - const data = [ - { search: '__V_COMPONENTS__', replace: normalizeUrl(voltranConfig.routing.components), flags: 'g' }, +function replaceString() { + const data = [ + { + search: '__V_COMPONENTS__', + replace: normalizeUrl(voltranConfig.routing.components), + flags: 'g' + }, { search: '__APP_CONFIG__', - replace: normalizeUrl(`${voltranConfig.appConfigFile.output.path}/${voltranConfig.appConfigFile.output.name}.js`), + replace: normalizeUrl( + `${voltranConfig.appConfigFile.output.path}/${voltranConfig.appConfigFile.output.name}.js` + ), flags: 'g' }, { @@ -20,14 +26,31 @@ function replaceString () { replace: normalizeUrl(`${voltranConfig.inputFolder}/assets.json`), flags: 'g' }, - { search: '__V_DICTIONARY__', replace: normalizeUrl(voltranConfig.routing.dictionary), flags: 'g' }, - { search: '@voltran/core', replace: normalizeUrl(path.resolve(__dirname, '../src/index')), flags: 'g' }, + { + search: '__V_DICTIONARY__', + replace: normalizeUrl(voltranConfig.routing.dictionary), + flags: 'g' + }, + { + search: '__V_REQUEST_CONFIGS__', + replace: normalizeUrl(voltranConfig.routing.requestConfigs), + flags: 'g' + }, + { + search: '@voltran/core', + replace: normalizeUrl(path.resolve(__dirname, '../src/index')), + flags: 'g' + }, { search: '"__V_styles__"', replace: getStyles() } ]; - data.push({ search: '__V_PROMETHEUS__', replace: normalizeUrl(prometheusFile ? prometheusFile : '../lib/tools/prom.js'), flags: 'g' }); + data.push({ + search: '__V_PROMETHEUS__', + replace: normalizeUrl(prometheusFile ? prometheusFile : '../lib/tools/prom.js'), + flags: 'g' + }); - return data; + return data; } module.exports = replaceString; diff --git a/package.json b/package.json index 2d53de7..cddb2f1 100644 --- a/package.json +++ b/package.json @@ -132,5 +132,9 @@ "commitLimit": false, "template": "changelog-template.hbs", "package": true + }, + "peerDependencies": { + "react": ">=16.13.0", + "react-dom": ">=16.13.0" } } diff --git a/src/client/client.js b/src/client/client.js index 68f5240..e98cf75 100644 --- a/src/client/client.js +++ b/src/client/client.js @@ -1,15 +1,10 @@ import 'whatwg-fetch'; import Eev from 'eev'; -const appConfig = require('__APP_CONFIG__'); - -const defaultEventBusName = 'eventBus'; /* eslint-disable-next-line */ -('__V_styles__'); +"__V_styles__" if (!window.HbEventBus) { - const name = appConfig.eventBusName || defaultEventBusName; - - window[name] = new Eev(); + window.HbEventBus = new Eev(); window.voltran_project_version = process.env.APP_BUILD_VERSION || '1.0.0'; } diff --git a/src/render.js b/src/render.js index 284548e..43c2def 100644 --- a/src/render.js +++ b/src/render.js @@ -16,8 +16,7 @@ import logger from './universal/utils/logger'; const appConfig = require('__APP_CONFIG__'); -// eslint-disable-next-line consistent-return -export default async (req, res) => { +const render = async (req, res) => { const isWithoutStateValue = isWithoutState(req.query); const pathParts = xss(req.path) .split('/') @@ -63,7 +62,7 @@ export default async (req, res) => { componentName, seoState, isPreviewQuery, - responseOptions, + responseOptions } = renderResponse; const statusCode = responseOptions?.isPartialContent @@ -84,7 +83,9 @@ export default async (req, res) => { if (voltranEnv !== 'prod' && isPreviewQuery) { res.status(statusCode).html(Preview([fullHtml].join('\n'))); } else { - res.status(HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR).html('

Aradığınız sayfa bulunamadı...

'); + res + .status(HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR) + .html('

Aradığınız sayfa bulunamadı...

'); } } } else { @@ -93,3 +94,5 @@ export default async (req, res) => { }); } }; + +export default render; diff --git a/src/renderMultiple.js b/src/renderMultiple.js index 433094d..6f72648 100644 --- a/src/renderMultiple.js +++ b/src/renderMultiple.js @@ -1,15 +1,19 @@ /* eslint-disable no-param-reassign */ +import async from 'async'; import { matchUrlInRouteConfigs } from './universal/core/route/routeUtils'; import Component from './universal/model/Component'; import Renderer from './universal/model/Renderer'; -import async from 'async'; import Preview from './universal/components/Preview'; -import { isPreview, isWithoutHTML } from './universal/service/RenderService'; +import { isRequestDispatcher, isPreview, isWithoutHTML } from './universal/service/RenderService'; import metrics from './metrics'; import { HTTP_STATUS_CODES } from './universal/utils/constants'; import logger from './universal/utils/logger'; -function getRenderer(name, query, cookies, url, path, userAgent) { +function getRenderer(name, req) { + const { query, cookies, url, headers, params } = req; + const path = `/${params?.path || ''}`; + const userAgent = headers['user-agent']; + const componentPath = Component.getComponentPath(name); const routeInfo = matchUrlInRouteConfigs(componentPath); @@ -159,7 +163,7 @@ async function setInitialStates(renderers) { } async function getResponses(renderers) { - return (await Promise.all(renderers.map(renderer => renderer.render()))) + const responses = (await Promise.all(renderers.map(renderer => renderer.render()))) .filter(result => result.value != null) .reduce((obj, item) => { const el = obj; @@ -169,6 +173,8 @@ async function getResponses(renderers) { return el; }, {}); + + return responses; } async function getPreview(responses, requestCount) { @@ -178,21 +184,26 @@ async function getPreview(responses, requestCount) { ); } -// eslint-disable-next-line consistent-return -export default async (req, res) => { - const renderers = req.params.components +const DEFAULT_PARTIALS = ['RequestDispatcher']; + +export const getPartials = req => { + const useRequestDispatcher = isRequestDispatcher(req.query); + + const reqPartials = req.params.components .split(',') .filter((value, index, self) => self.indexOf(value) === index) - .map(name => - getRenderer( - name, - req.query, - req.cookies, - req.url, - `/${req.params.path || ''}`, - req.headers['user-agent'] - ) - ) + .filter(item => !DEFAULT_PARTIALS.includes(item)); + + const partials = [...(useRequestDispatcher ? DEFAULT_PARTIALS : []), ...reqPartials]; + + return partials; +}; + +const renderMultiple = async (req, res) => { + const partials = getPartials(req); + + const renderers = partials + .map(name => getRenderer(name, req)) .filter(renderer => renderer != null); if (!renderers.length) { @@ -227,3 +238,5 @@ export default async (req, res) => { .observe(Date.now() - res.locals.startEpoch); } }; + +export default renderMultiple; diff --git a/src/universal/components/Preview.js b/src/universal/components/Preview.js index 87e7f17..61d9775 100644 --- a/src/universal/components/Preview.js +++ b/src/universal/components/Preview.js @@ -13,7 +13,10 @@ export default (body, title = null) => { Preview${additionalTitle} - + + ${cr( + appConfig.voltranCommonUrl ? `` : '' + )} ${cr( appConfig.showPreviewFrame, ` - ${styleTags} + ${welcomeStyle()} - ${PartialList} + +
+
+ +
+
+
+ ${PartialCards} +
+
+
+ + `; }; diff --git a/src/universal/partials/Welcome/styled.js b/src/universal/partials/Welcome/styled.js deleted file mode 100644 index 0f55d4f..0000000 --- a/src/universal/partials/Welcome/styled.js +++ /dev/null @@ -1,145 +0,0 @@ -import styled from 'styled-components'; - -const STATUS_COLOR = { - live: '#8dc63f', - dev: '#FF6000', - page: '#00abff', - 1: '#9b59b6', - 2: '#c0392b', - 3: '#16a085' -}; - -export const List = styled.ul` - list-style: none; - margin: 0; - padding: 0; - margin-bottom: 20px; -`; - -export const HeaderName = styled.div` - font-size: 36px; - font-weight: bold; - margin: 10px; -`; - -export const ListItem = styled.li` - padding: 20px; - display: inline-block; - vertical-align: top; - height: 120px; - width: 240px; - margin: 10px; - cursor: pointer; - border-radius: 10px; - - position: relative; - background-color: #fff; - box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1); - -webkit-transition: all 0.6s cubic-bezier(0.165, 0.84, 0.44, 1); - transition: all 0.6s cubic-bezier(0.165, 0.84, 0.44, 1); - - :after { - content: ''; - border-radius: 10px; - position: absolute; - z-index: -1; - top: 0; - left: 0; - width: 100%; - height: 100%; - box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1); - opacity: 0; - -webkit-transition: all 0.6s cubic-bezier(0.165, 0.84, 0.44, 1); - transition: all 0.6s cubic-bezier(0.165, 0.84, 0.44, 1); - } - - &:hover { - transform: scale(1.02, 1.02); - :after { - opacity: 1; - } - } - - @media screen and (max-width: 600px) { - display: block; - width: auto; - height: 150px; - margin: 10px auto; - } -`; - -export const Link = styled.a` - text-decoration: none; - color: #49494a; - - &:before { - position: absolute; - z-index: 0; - top: 0; - right: 0; - bottom: 0; - left: 0; - display: block; - content: ''; - } -`; - -export const Name = styled.span` - font-weight: 800; - display: block; - max-width: 80%; - font-size: 16px; - line-height: 18px; -`; - -export const Url = styled.span` - font-size: 11px; - line-height: 16px; - color: #a1a1a4; -`; - -export const Footer = styled.span` - display: block; - position: absolute; - bottom: 0; - left: 0; - right: 0; - width: 100%; - padding: 20px; - border-top: 1px solid ${({ status }) => (status && STATUS_COLOR[status]) || '#eeeeee'}50; - font-size: 13px; -`; - -export const Label = styled.span` - font-size: 13px; - align-items: center; - font-weight: bold; - display: flex; - position: absolute; - right: 20px; - top: 0; - line-height: 40px; - margin: 0 10px; - - @media screen and (max-width: 200px) { - right: auto; - left: 10px; - } - - color: ${({ status }) => (status && STATUS_COLOR[status]) || '#8dc63f'}; -`; - -export const Dot = styled.span` - display: inline-block; - vertical-align: middle; - width: 16px; - height: 16px; - overflow: hidden; - border-radius: 50%; - padding: 0; - text-indent: -9999px; - color: transparent; - line-height: 16px; - margin-left: 10px; - background: ${({ status }) => (status && STATUS_COLOR[status]) || '#8dc63f'}; -`; diff --git a/src/universal/partials/Welcome/welcomeStyle.js b/src/universal/partials/Welcome/welcomeStyle.js new file mode 100644 index 0000000..9b09e2b --- /dev/null +++ b/src/universal/partials/Welcome/welcomeStyle.js @@ -0,0 +1,322 @@ +const welcomeStyle = () => { + return ``; +}; + +export default welcomeStyle; From 660dccd5f7fb7785883b36661e21b96e65bebc8c Mon Sep 17 00:00:00 2001 From: ahmetkuslular Date: Thu, 16 Jun 2022 16:01:01 +0300 Subject: [PATCH 20/20] ADD api service middleware --- src/index.js | 15 +++++++++++++-- .../apiService/apiManager/ClientApiManager.js | 4 ++-- .../apiService/apiManager/ServerApiManager.js | 4 ++-- .../apiManagerCache/ClientApiManagerCache.js | 8 ++++++-- .../apiManagerCache/ServerApiManagerCache.js | 8 ++++++-- src/universal/core/apiService/apiService.js | 5 +++-- .../core/apiService/apiServiceMiddleware.js | 9 +++++++++ src/universal/core/apiService/index.js | 1 + .../core/apiService/utils/createApiClient.js | 15 ++++++--------- .../core/apiService/utils/createCache.js | 4 ++-- 10 files changed, 50 insertions(+), 23 deletions(-) create mode 100644 src/universal/core/apiService/apiServiceMiddleware.js diff --git a/src/index.js b/src/index.js index 734b89d..e0624ba 100644 --- a/src/index.js +++ b/src/index.js @@ -1,7 +1,18 @@ import voltran from './universal/partials/withBaseComponent'; -import apiService, { ClientApiManager, ServerApiManager } from './universal/core/apiService'; +import apiService, { + ClientApiManager, + ServerApiManager, + apiServiceMiddleware +} from './universal/core/apiService'; import requestDispatcher from './universal/utils/requestDispatcher'; import useRequestDispatcher from './universal/hooks/useRequestDispatcher'; export default voltran; -export { ClientApiManager, ServerApiManager, apiService, requestDispatcher, useRequestDispatcher }; +export { + ClientApiManager, + ServerApiManager, + apiService, + apiServiceMiddleware, + requestDispatcher, + useRequestDispatcher +}; diff --git a/src/universal/core/apiService/apiManager/ClientApiManager.js b/src/universal/core/apiService/apiManager/ClientApiManager.js index 14e9c9f..a394a16 100644 --- a/src/universal/core/apiService/apiManager/ClientApiManager.js +++ b/src/universal/core/apiService/apiManager/ClientApiManager.js @@ -1,7 +1,7 @@ import createApiClient from '../utils/createApiClient'; import BaseApiManager from './BaseApiManager'; -export default (entity, serviceConfigs) => { +export default (entity, serviceConfigs, func) => { const baseURL = entity.clientUrl || entity.url || entity.serverUrl || '/'; const config = { ...serviceConfigs, @@ -13,5 +13,5 @@ export default (entity, serviceConfigs) => { ...config }); - return createApiClient(apiManager); + return createApiClient(apiManager, func); }; diff --git a/src/universal/core/apiService/apiManager/ServerApiManager.js b/src/universal/core/apiService/apiManager/ServerApiManager.js index 1126492..e020c22 100644 --- a/src/universal/core/apiService/apiManager/ServerApiManager.js +++ b/src/universal/core/apiService/apiManager/ServerApiManager.js @@ -9,7 +9,7 @@ const BASE_HTTP_AGENT_CONFIG = { rejectUnauthorized: false }; -export default (entity, serviceConfigs) => { +export default (entity, serviceConfigs, func) => { const apiManager = new BaseApiManager({ baseURL: entity.serverUrl || entity.url || entity.clientUrl || '/', ...serviceConfigs, @@ -17,5 +17,5 @@ export default (entity, serviceConfigs) => { httpsAgent: new https.Agent(BASE_HTTP_AGENT_CONFIG) }); - return createApiClient(apiManager); + return createApiClient(apiManager, func); }; diff --git a/src/universal/core/apiService/apiManagerCache/ClientApiManagerCache.js b/src/universal/core/apiService/apiManagerCache/ClientApiManagerCache.js index a92487a..7d4c0a7 100644 --- a/src/universal/core/apiService/apiManagerCache/ClientApiManagerCache.js +++ b/src/universal/core/apiService/apiManagerCache/ClientApiManagerCache.js @@ -4,6 +4,10 @@ import createCache from '../utils/createCache'; const { services, serviceConfigs } = require('__APP_CONFIG__'); -const cache = createCache(ClientApiManager, services, serviceConfigs?.client); +const getCache = func => { + const cache = createCache(ClientApiManager, services, serviceConfigs?.client, func); -export default cache; + return cache; +}; + +export default getCache; diff --git a/src/universal/core/apiService/apiManagerCache/ServerApiManagerCache.js b/src/universal/core/apiService/apiManagerCache/ServerApiManagerCache.js index 11ae446..6c122e9 100644 --- a/src/universal/core/apiService/apiManagerCache/ServerApiManagerCache.js +++ b/src/universal/core/apiService/apiManagerCache/ServerApiManagerCache.js @@ -4,6 +4,10 @@ import createCache from '../utils/createCache'; const { services, serviceConfigs } = require('__APP_CONFIG__'); -const cache = createCache(ServerApiManager, services, serviceConfigs?.server); +const getCache = func => { + const cache = createCache(ServerApiManager, services, serviceConfigs?.server, func); -export default cache; + return cache; +}; + +export default getCache; diff --git a/src/universal/core/apiService/apiService.js b/src/universal/core/apiService/apiService.js index c09c762..a1c8ce4 100644 --- a/src/universal/core/apiService/apiService.js +++ b/src/universal/core/apiService/apiService.js @@ -1,10 +1,11 @@ import { ServerApiManagerCache, ClientApiManagerCache } from './apiManagerCache'; -const getApiService = () => { +const getApiService = func => { const isBrowser = typeof window !== 'undefined'; - return isBrowser ? ClientApiManagerCache : ServerApiManagerCache; + return isBrowser ? ClientApiManagerCache(func) : ServerApiManagerCache(func); }; const apiService = getApiService(); export default apiService; +export { getApiService }; diff --git a/src/universal/core/apiService/apiServiceMiddleware.js b/src/universal/core/apiService/apiServiceMiddleware.js new file mode 100644 index 0000000..025672d --- /dev/null +++ b/src/universal/core/apiService/apiServiceMiddleware.js @@ -0,0 +1,9 @@ +import { getApiService } from './apiService'; + +const apiServiceMiddleware = func => { + const apiService = getApiService(func); + + return apiService; +}; + +export default apiServiceMiddleware; diff --git a/src/universal/core/apiService/index.js b/src/universal/core/apiService/index.js index d689927..820bc5a 100644 --- a/src/universal/core/apiService/index.js +++ b/src/universal/core/apiService/index.js @@ -1,3 +1,4 @@ export { default } from './apiService'; export { default as ClientApiManager } from './apiManagerCache/ClientApiManagerCache'; export { default as ServerApiManager } from './apiManagerCache/ServerApiManagerCache'; +export { default as apiServiceMiddleware } from './apiServiceMiddleware'; diff --git a/src/universal/core/apiService/utils/createApiClient.js b/src/universal/core/apiService/utils/createApiClient.js index cefebd0..74585c0 100644 --- a/src/universal/core/apiService/utils/createApiClient.js +++ b/src/universal/core/apiService/utils/createApiClient.js @@ -1,7 +1,7 @@ import Request from '../../../model/Request'; import { createCacheManagerInstance } from '../../cache/cacheUtils'; -function createApiClient(apiManager) { +function createApiClient(apiManager, middlewareFunc) { const cacheManager = createCacheManagerInstance(); function getSortedParams(nonSortedParams) { @@ -21,17 +21,14 @@ function createApiClient(apiManager) { } function getPayload(url, method, params, configArgument) { - let payload; - if (configArgument) { - payload = { url, method, params, ...configArgument }; - } else { - payload = { url, method, params }; - } - return payload; + return { url, method, params, ...(configArgument && configArgument) }; } function getRequest(method, url, paramsArgument, configArgument, response) { - const params = getSortedParams(paramsArgument); + let params = getSortedParams(paramsArgument); + if (middlewareFunc) { + params = middlewareFunc(params); + } const payload = getPayload(url, method, params, configArgument); const uri = apiManager.api.getUri(payload); diff --git a/src/universal/core/apiService/utils/createCache.js b/src/universal/core/apiService/utils/createCache.js index 2100ead..05f8b26 100644 --- a/src/universal/core/apiService/utils/createCache.js +++ b/src/universal/core/apiService/utils/createCache.js @@ -1,12 +1,12 @@ import freezeServices from './freezeServices'; -const createCache = (ApiManager, services, timeout) => { +const createCache = (ApiManager, services, config, func) => { const cache = {}; const frozenServicesData = freezeServices(services); Object.entries(services).forEach(entity => { const [serviceKey, serviceValues] = entity; - cache[frozenServicesData[serviceKey]] = ApiManager(serviceValues, timeout); + cache[frozenServicesData[serviceKey]] = ApiManager(serviceValues, config, func); }); return cache;