Initial commit
This commit is contained in:
160
proxy-ui-app/src/helpers/Services/Services.js
Normal file
160
proxy-ui-app/src/helpers/Services/Services.js
Normal file
@@ -0,0 +1,160 @@
|
||||
import {get, post, put, remove} from './apiHelpers.js'
|
||||
import {convertObject, convertList} from './adapter/adapter.js'
|
||||
import { config} from '@store/modules/proxy/StaticData.js';
|
||||
|
||||
const servConfig = {
|
||||
id: "id",
|
||||
created_at: "created_at",
|
||||
updated_at: "updated_at",
|
||||
deleted_at: "deleted_at",
|
||||
name: "name",
|
||||
port: "port",
|
||||
proxy_ip: "proxy_ip",
|
||||
internet_uri: "internet_uri",
|
||||
description: "description",
|
||||
is_online: "is_online",
|
||||
device_ip: "site_ip",
|
||||
}
|
||||
|
||||
class Services {
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {String} apiAddr - path to service
|
||||
* @param {Object} config - oldKey: newKey
|
||||
*/
|
||||
|
||||
constructor(apiAddr, config) {
|
||||
this.apiAddr = apiAddr
|
||||
this.config = config
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @returns {Array<Object>} res.data - all services
|
||||
*/
|
||||
|
||||
async getServices() {
|
||||
const res = await get(`${this.apiAddr}/servers`)
|
||||
return convertList(res.data, {config: this.config})
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {Object} payload - add new service
|
||||
* @returns {Object} newService - added new service
|
||||
*/
|
||||
|
||||
async createService(payload) {
|
||||
let newService = []
|
||||
const updatedPort = parseFloat(payload.port)
|
||||
const updatedService = {...convertObject(payload, {config: servConfig}), port: updatedPort}
|
||||
await post(`${this.apiAddr}/servers`, updatedService).then(res => {
|
||||
newService = convertObject(res.value, {config: this.config})
|
||||
}).catch(err => {
|
||||
console.log('err', err)
|
||||
})
|
||||
return newService
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {Object} payload - edit params in selected service
|
||||
* @returns {Object} resService - updated service with edited params
|
||||
*/
|
||||
|
||||
async updateService(payload) {
|
||||
let resService = []
|
||||
const updatedPort = parseFloat(payload.port)
|
||||
const updatedService = {...convertObject(payload, {config: servConfig}), port: updatedPort}
|
||||
if (payload.id) {
|
||||
await put(`${this.apiAddr}/servers`, updatedService, payload.id).then(res => {
|
||||
resService = convertObject(res.value, {config: this.config})
|
||||
}).catch(err => {
|
||||
console.log('err', err)
|
||||
})
|
||||
}
|
||||
return resService
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {Number} id - id selected service for remove
|
||||
* @returns {Number} deletedServiceId - id removed service
|
||||
*/
|
||||
|
||||
async deleteService(id) {
|
||||
let deletedServiceId = null
|
||||
await remove(`${this.apiAddr}/servers`, id).then((res) => {
|
||||
deletedServiceId = res.id
|
||||
}).catch(err => {
|
||||
console.log('err', err)
|
||||
})
|
||||
return deletedServiceId
|
||||
}
|
||||
}
|
||||
|
||||
export default Services
|
||||
|
||||
/**
|
||||
* Testing class Services
|
||||
*/
|
||||
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
const apiTest = async () => {
|
||||
|
||||
const services = new Services(import.meta.env.VITE_API_ADDR, config)
|
||||
|
||||
// Testing get services
|
||||
console.log('Uploaded services, method getServices - start')
|
||||
const uploadedServices = await services.getServices()
|
||||
console.log('Uploaded services, method getServices - result:', uploadedServices)
|
||||
|
||||
// Testing create service
|
||||
console.log('Added new service, method createService - start')
|
||||
const newService = await services.createService({
|
||||
name: "Test site for testing createService",
|
||||
port: 7777,
|
||||
site_ip: "172.25.78.151",
|
||||
proxy_ip: "172.25.78.151",
|
||||
description: 'Testing createService method',
|
||||
})
|
||||
let updatedServices = [...uploadedServices, newService]
|
||||
console.log('Added new service, method createService - result:', newService)
|
||||
|
||||
// Testing update service
|
||||
console.log('Updated services, method updateService - start')
|
||||
const serviceWithNewParams = {...newService, name: 'Test site for testing updateService', description: 'Testing updateService method', port: 9999}
|
||||
const updatedService = await services.updateService(serviceWithNewParams)
|
||||
updatedServices = [...updatedServices.filter(service => service.id !== newService.id), updatedService]
|
||||
console.log('Updated services, method updateService - result:', updatedService)
|
||||
|
||||
// Testing delete service
|
||||
console.log('Deleted service, method deleteService - start')
|
||||
const deletedServiceId = await services.deleteService(newService.id)
|
||||
console.log('Deleted service, method deleteService, get id from deleted service - result:', deletedServiceId)
|
||||
|
||||
// Testing get services after delete
|
||||
const withoutDeletedService = updatedServices.filter(service => service.id !== newService.id)
|
||||
const updatedServicesAfterDelete = await services.getServices()
|
||||
console.log('Services after all tests:', updatedServicesAfterDelete)
|
||||
|
||||
// Equal results
|
||||
|
||||
const reg = new RegExp (`${updatedServicesAfterDelete.length}`, 'g')
|
||||
const lengthCurrServices = withoutDeletedService.length.toString()
|
||||
|
||||
console.log('reg', reg)
|
||||
|
||||
const isEqual = reg.test(lengthCurrServices)
|
||||
|
||||
console.log('isCountServicesEqual', isEqual)
|
||||
}
|
||||
|
||||
// Запуск теста api - расскомментировать функцию apiTest
|
||||
// apiTest()
|
||||
// тест api end
|
||||
|
||||
/**
|
||||
* Testing class Services end
|
||||
*/
|
||||
42
proxy-ui-app/src/helpers/Services/adapter/adapter.js
Normal file
42
proxy-ui-app/src/helpers/Services/adapter/adapter.js
Normal file
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* Каллбек изменнеия, ожидает что вернется измененный объект
|
||||
*
|
||||
* @callback adapterCallback
|
||||
* @param {Object} modifiedObject - новый объект
|
||||
* @param {Object} originalObject - изначальный объект
|
||||
* @returns {Object} измененный коллбэком объект
|
||||
*/
|
||||
|
||||
/**
|
||||
*
|
||||
* Если у newKey значение отстутсвует - null, '', false, 0, то oldKey удаляется из объекта
|
||||
*
|
||||
* @param {Object} targetObject
|
||||
* @param {Object} params
|
||||
* @param {Object} params.config - oldKey: null // delete oldKey
|
||||
* @param {adapterCallback | undefined} params.callback
|
||||
* @returns {Object}
|
||||
*/
|
||||
const convertObject = (targetObject, {config, callback = (v) => v}) => {
|
||||
let newObject = {}
|
||||
for (const key in config) {
|
||||
newObject[config[key]] = targetObject[key]
|
||||
}
|
||||
return callback(newObject, targetObject)
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Если у newKey значение отстутсвует - null, '', false, 0, то oldKey удаляется из объекта
|
||||
*
|
||||
* @param {Array} targetList
|
||||
* @param {Object} options - oldKey: null // delete oldKey
|
||||
* @param {Object} options.config - oldKey: null // delete oldKey
|
||||
* @param {adapterCallback | undefined} options.callback
|
||||
* @returns {Object}
|
||||
*/
|
||||
const convertList = (targetList, {config, callback = (v) => v}) => {
|
||||
return targetList.map((targetObject) => convertObject(targetObject, {config, callback}))
|
||||
}
|
||||
|
||||
export {convertList, convertObject}
|
||||
39
proxy-ui-app/src/helpers/Services/apiHelpers.js
Normal file
39
proxy-ui-app/src/helpers/Services/apiHelpers.js
Normal file
@@ -0,0 +1,39 @@
|
||||
import axios from "axios";
|
||||
|
||||
const post = async (path, data, onError) => {
|
||||
return await axios.post(path, data)
|
||||
.then(r => r.data)
|
||||
.catch(error => {
|
||||
onError && onError(error)
|
||||
console.error('Error post request:', error)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
const get = async (path) => {
|
||||
return await axios.get(path)
|
||||
.catch(error => {
|
||||
console.error('Error get request:', error)
|
||||
})
|
||||
}
|
||||
|
||||
const put = async (path, data, id, onError) => {
|
||||
return await axios.put(`${path}/${id}`, data)
|
||||
.then(r => r.data)
|
||||
.catch(error => {
|
||||
onError && onError(error)
|
||||
console.error('Error put request:', error)
|
||||
})
|
||||
}
|
||||
|
||||
const remove = async (path, id, onError) => {
|
||||
return await axios.delete(`${path}/${id}`)
|
||||
.then(r => r.data)
|
||||
.catch(error => {
|
||||
onError && onError(error)
|
||||
console.error('Error delete request:', error)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
export {get, post, put, remove}
|
||||
232
proxy-ui-app/src/helpers/server-routes/Routes.js
Normal file
232
proxy-ui-app/src/helpers/server-routes/Routes.js
Normal file
@@ -0,0 +1,232 @@
|
||||
import {get, post, put, remove} from './apiHelpers.js'
|
||||
import {convertList} from './adapter/adapter.js'
|
||||
import {equals, cond} from "ramda";
|
||||
|
||||
/**
|
||||
* Интерфейс роутера
|
||||
* @typedef {Object} Router
|
||||
* @param {Number} id
|
||||
* @param {Number} server_id
|
||||
* @param {String} path
|
||||
* @param {Number} role
|
||||
* @param {String} description
|
||||
* @param {Number} deepness
|
||||
* @param {Number} order
|
||||
* @param {Boolean} is_cb_on
|
||||
* @param {Number} cb_request_limit
|
||||
* @param {Number} cb_min_requests
|
||||
* @param {Number} cb_error_threshold_percentage
|
||||
* @param {Number} cb_interval_duration
|
||||
* @param {Number} cb_open_state_timeout
|
||||
*/
|
||||
|
||||
/**
|
||||
* Интерфейс роутера
|
||||
* @typedef {Object} Action
|
||||
* @property {'remove' | 'create' | 'update' | 'delete'} action
|
||||
*
|
||||
* @typedef {Router & Action} ActionRouter
|
||||
*/
|
||||
|
||||
class Routes {
|
||||
|
||||
/**
|
||||
* Класс управления роутерами
|
||||
* @param {String} apiAddr - path to service
|
||||
* @param {Object | undefined} adapter_config - oldKey: newKey
|
||||
*/
|
||||
constructor(apiAddr, adapter_config = {}) {
|
||||
this.apiAddr = apiAddr
|
||||
this.config = adapter_config
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @returns {Promise<*[]>}
|
||||
*/
|
||||
async getRoutes() {
|
||||
let res = await get(`${this.apiAddr}/routers`)
|
||||
let updatedRoutes = convertList(res.data, {config: this.config})
|
||||
return updatedRoutes
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {Number} id - Сервис id, если id не указан, отображается список всех роутеров
|
||||
* @returns {Promise<*[]>}
|
||||
*/
|
||||
async getRouterById(id) {
|
||||
let res = await get(`${this.apiAddr}/routers/by_server/${id}`)
|
||||
let updatedRoutes = convertList(res.data, {config: this.config})
|
||||
return updatedRoutes
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {Router} routerData
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async createRoute(routerData) {
|
||||
const newRoute = await post(`${this.apiAddr}/routers`, routerData)
|
||||
return newRoute
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {Router} routerData
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async updateRoute(routerData) {
|
||||
const updatedRouterData = {...routerData}
|
||||
delete updatedRouterData.id
|
||||
const newRoute = await put(`${this.apiAddr}/routers/${routerData.id}`, updatedRouterData)
|
||||
return newRoute
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {Number} routerId - Сервис id, если id не указан, отображается список всех роутеров
|
||||
* @returns {Promise<*[]>}
|
||||
*/
|
||||
async removeRoute(routerId) {
|
||||
const removedRoute = await remove(`${this.apiAddr}/routers/${routerId}`)
|
||||
return removedRoute
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {Array<ActionRouter>} routesActions - Группа роутеров для обновления
|
||||
* @returns {Promise<Array<Router>>}
|
||||
*/
|
||||
async updateGroupRoutes(routesActions) {
|
||||
const responses = routesActions.map(async (mutation) => {
|
||||
return cond([
|
||||
[equals('create'), () => this.createRoute(mutation)],
|
||||
[equals('delete'), () => this.removeRoute(mutation.id)],
|
||||
[equals('remove'), () => this.removeRoute(mutation.id)],
|
||||
[equals('update'), () => this.updateRoute(mutation)],
|
||||
])(mutation.action)
|
||||
})
|
||||
|
||||
return Promise.all(responses)
|
||||
}
|
||||
|
||||
/**
|
||||
* Функция запускает список запросов к апишке и логает ответы
|
||||
* @returns {Promise<String>}
|
||||
*/
|
||||
async test() {
|
||||
console.log("_______START TEST_______")
|
||||
|
||||
const allRoutes = await this.getRoutes()
|
||||
console.log("allRoutes", allRoutes)
|
||||
const serverRouter = await this.getRouterById(1)
|
||||
console.log("getRouterById 1", serverRouter)
|
||||
const newRoute = await this.createRoute({
|
||||
"server_id": 1,
|
||||
"path": "/",
|
||||
"role": 1,
|
||||
"description": "tests swagger",
|
||||
"deepness": 6,
|
||||
"order": 0,
|
||||
"is_cb_on": true,
|
||||
"cb_request_limit": 100,
|
||||
"cb_min_requests": 100,
|
||||
"cb_error_threshold_percentage": 0.35,
|
||||
"cb_interval_duration": 2000000,
|
||||
"cb_open_state_timeout": 1000000
|
||||
})
|
||||
console.log("newRoute", newRoute)
|
||||
const updatedRoute = await this.updateRoute({
|
||||
"path": "/updated_path/",
|
||||
"description": "updated_description",
|
||||
"id": newRoute.id
|
||||
})
|
||||
console.log("updatedRoute", updatedRoute)
|
||||
const removedRoute = await this.removeRoute(newRoute.id)
|
||||
console.log("removedRoute", removedRoute)
|
||||
|
||||
const newRoute1 = await this.createRoute({
|
||||
"server_id": 1,
|
||||
"path": "/",
|
||||
"role": 1,
|
||||
"description": "tests swagger",
|
||||
"deepness": 6,
|
||||
"order": 0,
|
||||
"is_cb_on": true,
|
||||
"cb_request_limit": 100,
|
||||
"cb_min_requests": 100,
|
||||
"cb_error_threshold_percentage": 0.35,
|
||||
"cb_interval_duration": 2000000,
|
||||
"cb_open_state_timeout": 1000000
|
||||
})
|
||||
const newRoute2 = await this.createRoute({
|
||||
"server_id": 1,
|
||||
"path": "/",
|
||||
"role": 1,
|
||||
"description": "tests swagger",
|
||||
"deepness": 6,
|
||||
"order": 0,
|
||||
"is_cb_on": true,
|
||||
"cb_request_limit": 100,
|
||||
"cb_min_requests": 100,
|
||||
"cb_error_threshold_percentage": 0.35,
|
||||
"cb_interval_duration": 2000000,
|
||||
"cb_open_state_timeout": 1000000
|
||||
})
|
||||
const newRoute3 = await this.createRoute({
|
||||
"server_id": 1,
|
||||
"path": "/",
|
||||
"role": 1,
|
||||
"description": "tests swagger",
|
||||
"deepness": 6,
|
||||
"order": 0,
|
||||
"is_cb_on": true,
|
||||
"cb_request_limit": 100,
|
||||
"cb_min_requests": 100,
|
||||
"cb_error_threshold_percentage": 0.35,
|
||||
"cb_interval_duration": 2000000,
|
||||
"cb_open_state_timeout": 1000000
|
||||
})
|
||||
|
||||
const actions = [
|
||||
{
|
||||
...newRoute1,
|
||||
action: "update",
|
||||
"path": "/updated_path2/",
|
||||
"description": "updated_description2",
|
||||
}, {
|
||||
...newRoute2,
|
||||
action: "update",
|
||||
"path": "/updated_path3/",
|
||||
"description": "updated_description3",
|
||||
}, {
|
||||
...newRoute3,
|
||||
action: "remove"
|
||||
},
|
||||
{
|
||||
action: "create",
|
||||
"server_id": 1,
|
||||
"path": "/lalalala/lalalal",
|
||||
"role": 1,
|
||||
"description": "new_route_created",
|
||||
"deepness": 6,
|
||||
"order": 0,
|
||||
"is_cb_on": true,
|
||||
"cb_request_limit": 100,
|
||||
"cb_min_requests": 100,
|
||||
"cb_error_threshold_percentage": 0.35,
|
||||
"cb_interval_duration": 2000000,
|
||||
"cb_open_state_timeout": 1000000
|
||||
}
|
||||
]
|
||||
|
||||
const mutationsList = await this.updateGroupRoutes(actions)
|
||||
console.log("mutationsList", mutationsList)
|
||||
console.log("________END TEST________")
|
||||
|
||||
return "ok"
|
||||
}
|
||||
}
|
||||
|
||||
export default Routes
|
||||
43
proxy-ui-app/src/helpers/server-routes/adapter/adapter.js
Normal file
43
proxy-ui-app/src/helpers/server-routes/adapter/adapter.js
Normal file
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* Каллбек изменнеия, ожидает что вернется измененный объект
|
||||
*
|
||||
* @callback adapterCallback
|
||||
* @param {Object} modifiedObject - новый объект
|
||||
* @param {Object} originalObject - изначальный объект
|
||||
* @returns {Object} измененный коллбэком объект
|
||||
*/
|
||||
|
||||
/**
|
||||
*
|
||||
* Если у newKey значение отстутсвует - null, '', false, 0, то oldKey удаляется из объекта
|
||||
*
|
||||
* @param {Object} targetObject
|
||||
* @param {Object} params
|
||||
* @param {Object} params.config - oldKey: null // delete oldKey
|
||||
* @param {adapterCallback | undefined} params.callback
|
||||
* @returns {Object}
|
||||
*/
|
||||
const convertObject = (targetObject, {config, callback = (v) => v}) => {
|
||||
let newObject = {}
|
||||
for (const key in config) {
|
||||
newObject[config[key]] = targetObject[key]
|
||||
}
|
||||
return callback(newObject, targetObject)
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Если у newKey значение отстутсвует - null, '', false, 0, то oldKey удаляется из объекта
|
||||
*
|
||||
* @param {Array} targetList
|
||||
* @param {Object} options - oldKey: null // delete oldKey
|
||||
* @param {Object} options.config - oldKey: null // delete oldKey
|
||||
* @param {adapterCallback | undefined} options.callback
|
||||
* @returns {Object}
|
||||
*/
|
||||
const convertList = (targetList, {config, callback = (v) => v}) => {
|
||||
return targetList.map((targetObject) => convertObject(targetObject, {config, callback}))
|
||||
}
|
||||
|
||||
|
||||
export {convertList, convertObject}
|
||||
38
proxy-ui-app/src/helpers/server-routes/apiHelpers.js
Normal file
38
proxy-ui-app/src/helpers/server-routes/apiHelpers.js
Normal file
@@ -0,0 +1,38 @@
|
||||
import axios from "axios";
|
||||
|
||||
const post = async (path, data, onError) => {
|
||||
return await axios.post(path, data)
|
||||
.then(r => r.data)
|
||||
.catch(error => {
|
||||
onError && onError(error)
|
||||
console.error('Error post request:', error)
|
||||
})
|
||||
}
|
||||
|
||||
const get = async (path) => {
|
||||
return await axios.get(path)
|
||||
.catch(error => {
|
||||
console.error('Error get request:', error)
|
||||
})
|
||||
}
|
||||
|
||||
const put = async (path, data, onError) => {
|
||||
return await axios.put(`${path}`, data)
|
||||
.then(r => r.data)
|
||||
.catch(error => {
|
||||
onError && onError(error)
|
||||
console.error('Error put request:', error)
|
||||
})
|
||||
}
|
||||
|
||||
const remove = async (path, onError) => {
|
||||
return await axios.delete(`${path}`)
|
||||
.then(r => r.data)
|
||||
.catch(error => {
|
||||
onError && onError(error)
|
||||
console.error('Error delete request:', error)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
export {get, post, put, remove}
|
||||
0
proxy-ui-app/src/helpers/server-routes/helpers.js
Normal file
0
proxy-ui-app/src/helpers/server-routes/helpers.js
Normal file
Reference in New Issue
Block a user