Initial commit

This commit is contained in:
2024-03-05 11:36:21 +03:00
commit bf2f060b94
212 changed files with 100448 additions and 0 deletions

View File

@@ -0,0 +1,96 @@
import {get, post, put, remove} from './apiHelpers.js'
import {convertObject, convertList} from './adapter/adapter.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

View 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}

View 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}

View File

@@ -0,0 +1,28 @@
const devUsersList = [
{
"id": 1,
"first_name": "Leanne",
"last_name": "Graham",
"email": "test@mail.ru",
"role": "admin",
"is_active": true
},
{
"id": 2,
"first_name": "Leanne",
"last_name": "Graham",
"email": "test@mail.ru",
"role": "admin",
"is_active": true
},
{
"id": 3,
"first_name": "Leanne",
"last_name": "Graham",
"email": "test@mail.ru",
"role": "admin",
"is_active": true
},
]
export {devUsersList}

View File

@@ -0,0 +1,206 @@
import {get, post, put, remove} from './apiHelpers.js'
import {convertList} from './adapter/adapter.js'
import {devUsersList} from './StaticData.js'
/**
* Интерфейс пользователя
* @typedef {Object} User
* @param {Number} id
*/
class Users {
/**
* Класс управления роутерами
* @param {String} apiAddr - path to service
* @param {Object | undefined} adapter_config - oldKey: newKey
* @param {Object | undefined} params - Конфиг настроек
* @param {'prod' | 'test'} params.mode - Конфиг настроек
*/
constructor(apiAddr, adapter_config = {}, params = {mode: 'prod'}) {
this.apiAddr = apiAddr
this.config = adapter_config
this.mode = params.mode
}
/**
*
* @param {Object} params - Конфиг настроек
* @param {'prod' | 'dev'} params.mode - Конфиг настроек
* @returns {Promise<*[]> | *[]}
*/
async getUsers(params) {
if (params.mode === "dev") {
return devUsersList
}
let res = await get(`${this.apiAddr}/users`)
let updatedUsers = convertList(res.data, {config: this.config})
return updatedUsers
}
/**
*
* @param {Number} id - Сервис id, если id не указан, отображается список всех роутеров
* @param {'dev' | 'prod'} mode - Сервис id, если id не указан, отображается список всех роутеров
* @returns {Promise<*[]>}
*/
async getUsersBySiteId(id, mode) {
if (mode === "dev") {
return devUsersList
}
let res = await get(`${this.apiAddr}/users/by_server/${id}`)
let updatedUsers = convertList(res.data, {config: this.config})
return updatedUsers
}
/**
*
* @param {User} userData
* @returns {Promise<void>}
*/
async createUser(userData) {
const newUser = await post(`${this.apiAddr}/users`, userData)
return newUser
}
/**
*
* @param {User} userData
* @returns {Promise<void>}
*/
async updateUser(userData) {
const updatedUserData = {...userData}
delete updatedUserData.id
const newUser = await put(`${this.apiAddr}/users/${userData.id}`, updatedUserData)
return newUser
}
/**
*
* @param {Number} userId - Сервис id, если id не указан, отображается список всех роутеров
* @returns {Promise<*[]>}
*/
async removeUser(userId) {
const removedUser = await remove(`${this.apiAddr}/users/${userId}`)
return removedUser
}
/**
* Функция запускает список запросов к апишке и логает ответы
* @returns {Promise<String>}
*/
async test() {
console.log("_______START TEST_______")
const allUsers = await this.getUsers()
console.log("allUsers", allUsers)
const serverUser = await this.getUserById(1)
console.log("getUserById 1", serverUser)
const newUser = await this.createUser({
"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("newUser", newUser)
const updatedUser = await this.updateUser({
"path": "/updated_path/",
"description": "updated_description",
"id": newUser.id
})
console.log("updatedUser", updatedUser)
const removedUser = await this.removeUser(newUser.id)
console.log("removedUser", removedUser)
const newUser1 = await this.createUser({
"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 newUser2 = await this.createUser({
"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 newUser3 = await this.createUser({
"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 = [
{
...newUser1,
action: "update",
"path": "/updated_path2/",
"description": "updated_description2",
}, {
...newUser2,
action: "update",
"path": "/updated_path3/",
"description": "updated_description3",
}, {
...newUser3,
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.updateGroupUsers(actions)
console.log("mutationsList", mutationsList)
console.log("________END TEST________")
return "ok"
}
}
export default Users

View 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}

View File

@@ -0,0 +1,203 @@
import { expect, test } from 'vitest'
import { convertObject, convertList } from './adapter'
test('parse object from api', () => {
const targetObject = {
"id": 1,
"created_at": "2024-02-15T17:24:52.755254148+03:00",
"updated_at": "2024-02-15T17:24:52.755254148+03:00",
"deleted_at": null,
"name": "jsonplaceholder.typicode.com",
"port": 9965,
"proxy_ip": "172.25.78.153",
"site_ip": "172.25.78.36",
"internet_uri": "localhost",
"description": "localhost",
"is_online": true
}
const expectedObject = {
id: 1,
name2: "jsonplaceholder.typicode.com",
port2: 9965,
proxy_ip: "172.25.78.153",
site_ip: "172.25.78.36",
internet_uri: "localhost",
description: "localhost",
is_online: true,
}
const config = {
id: "id",
name: "name2",
port: "port2",
proxy_ip: "proxy_ip",
site_ip: "site_ip",
internet_uri: "internet_uri",
description: "description",
is_online: "is_online",
}
expect(convertObject(targetObject, {config})).toEqual(expectedObject)
})
test('adapt list objects without callback', () => {
const targetObject1 = {
"id": 1,
"created_at": "2024-02-15T17:24:52.755254148+03:00",
"updated_at": "2024-02-15T17:24:52.755254148+03:00",
"deleted_at": null,
"name": "jsonplaceholder.typicode.com",
"port": 9965,
"proxy_ip": "172.25.78.153",
"site_ip": "172.25.78.36",
"internet_uri": "localhost",
"description": "localhost",
"is_online": true
}
const targetObject2 = {
"id": 1,
"created_at": "2024-02-15T17:24:52.755254148+03:00",
"updated_at": "2024-02-15T17:24:52.755254148+03:00",
"deleted_at": null,
"name": "jsonplaceholder.typicode.com",
"port": 9965,
"proxy_ip": "172.25.78.153",
"site_ip": "172.25.78.36",
"internet_uri": "localhost",
"description": "localhost",
"is_online": true
}
const targetObject3 = {
"id": 1,
"created_at": "2024-02-15T17:24:52.755254148+03:00",
"updated_at": "2024-02-15T17:24:52.755254148+03:00",
"deleted_at": null,
"name": "jsonplaceholder.typicode.com",
"port": 9965,
"proxy_ip": "172.25.78.153",
"site_ip": "172.25.78.36",
"internet_uri": "localhost",
"description": "localhost",
"is_online": true
}
const targetList = [targetObject1, targetObject2, targetObject3]
const selfObject1 = {
id: 1,
name2: "jsonplaceholder.typicode.com",
port2: 9965,
proxy_ip: "172.25.78.153",
site_ip: "172.25.78.36",
internet_uri: "localhost",
description: "localhost",
is_online: true,
}
const selfObject2 = {
id: 1,
name2: "jsonplaceholder.typicode.com",
port2: 9965,
proxy_ip: "172.25.78.153",
site_ip: "172.25.78.36",
internet_uri: "localhost",
description: "localhost",
is_online: true,
}
const selfObject3 = {
id: 1,
name2: "jsonplaceholder.typicode.com",
port2: 9965,
proxy_ip: "172.25.78.153",
site_ip: "172.25.78.36",
internet_uri: "localhost",
description: "localhost",
is_online: true,
}
const selfList = [selfObject1, selfObject2, selfObject3]
const config = {
id: "id",
name: "name2",
port: "port2",
proxy_ip: "proxy_ip",
site_ip: "site_ip",
internet_uri: "internet_uri",
description: "description",
is_online: "is_online",
}
expect(convertList(targetList, {config})).toEqual(selfList)
})
test('adapt list objects with callback', () => {
const targetObject1 = {
"id": 1,
"created_at": "2024-02-15T17:24:52.755254148+03:00",
"updated_at": "2024-02-15T17:24:52.755254148+03:00",
"deleted_at": null,
"name": "jsonplaceholder.typicode.com",
"port": 9965,
"proxy_ip": "172.25.78.153",
"site_ip": "172.25.78.36",
"internet_uri": "localhost",
"description": "localhost",
"is_online": true
}
const targetObject2 = {
"id": 1,
"created_at": "2024-02-15T17:24:52.755254148+03:00",
"updated_at": "2024-02-15T17:24:52.755254148+03:00",
"deleted_at": null,
"name": "jsonplaceholder.typicode.com",
"port": 9965,
"proxy_ip": "172.25.78.153",
"site_ip": "172.25.78.36",
"internet_uri": "localhost",
"description": "localhost",
"is_online": false
}
const targetList = [targetObject1, targetObject2]
const expectedObject1 = {
id: 1,
name2: "jsonplaceholder.typicode.com",
port2: 9965,
proxy_ip: "172.25.78.153",
site_ip: "172.25.78.36",
internet_uri: "localhost",
description: "localhost",
state: "active",
}
const expectedObject2 = {
id: 1,
name2: "jsonplaceholder.typicode.com",
port2: 9965,
proxy_ip: "172.25.78.153",
site_ip: "172.25.78.36",
internet_uri: "localhost",
description: "localhost",
state: "disabled",
}
const expectedList = [expectedObject1, expectedObject2]
const config = {
id: "id",
name: "name2",
port: "port2",
proxy_ip: "proxy_ip",
site_ip: "site_ip",
internet_uri: "internet_uri",
description: "description",
}
const callback = (el, {is_online}) => ({...el, state: is_online ? "active": "disabled"})
expect(convertList(targetList, {config, callback})).toEqual(expectedList)
})

View 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}

View 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}

View File

@@ -0,0 +1,203 @@
import { expect, test } from 'vitest'
import { convertObject, convertList } from './adapter'
test('parse object from api', () => {
const targetObject = {
"id": 1,
"created_at": "2024-02-15T17:24:52.755254148+03:00",
"updated_at": "2024-02-15T17:24:52.755254148+03:00",
"deleted_at": null,
"name": "jsonplaceholder.typicode.com",
"port": 9965,
"proxy_ip": "172.25.78.153",
"site_ip": "172.25.78.36",
"internet_uri": "localhost",
"description": "localhost",
"is_online": true
}
const expectedObject = {
id: 1,
name2: "jsonplaceholder.typicode.com",
port2: 9965,
proxy_ip: "172.25.78.153",
site_ip: "172.25.78.36",
internet_uri: "localhost",
description: "localhost",
is_online: true,
}
const config = {
id: "id",
name: "name2",
port: "port2",
proxy_ip: "proxy_ip",
site_ip: "site_ip",
internet_uri: "internet_uri",
description: "description",
is_online: "is_online",
}
expect(convertObject(targetObject, {config})).toEqual(expectedObject)
})
test('adapt list objects without callback', () => {
const targetObject1 = {
"id": 1,
"created_at": "2024-02-15T17:24:52.755254148+03:00",
"updated_at": "2024-02-15T17:24:52.755254148+03:00",
"deleted_at": null,
"name": "jsonplaceholder.typicode.com",
"port": 9965,
"proxy_ip": "172.25.78.153",
"site_ip": "172.25.78.36",
"internet_uri": "localhost",
"description": "localhost",
"is_online": true
}
const targetObject2 = {
"id": 1,
"created_at": "2024-02-15T17:24:52.755254148+03:00",
"updated_at": "2024-02-15T17:24:52.755254148+03:00",
"deleted_at": null,
"name": "jsonplaceholder.typicode.com",
"port": 9965,
"proxy_ip": "172.25.78.153",
"site_ip": "172.25.78.36",
"internet_uri": "localhost",
"description": "localhost",
"is_online": true
}
const targetObject3 = {
"id": 1,
"created_at": "2024-02-15T17:24:52.755254148+03:00",
"updated_at": "2024-02-15T17:24:52.755254148+03:00",
"deleted_at": null,
"name": "jsonplaceholder.typicode.com",
"port": 9965,
"proxy_ip": "172.25.78.153",
"site_ip": "172.25.78.36",
"internet_uri": "localhost",
"description": "localhost",
"is_online": true
}
const targetList = [targetObject1, targetObject2, targetObject3]
const selfObject1 = {
id: 1,
name2: "jsonplaceholder.typicode.com",
port2: 9965,
proxy_ip: "172.25.78.153",
site_ip: "172.25.78.36",
internet_uri: "localhost",
description: "localhost",
is_online: true,
}
const selfObject2 = {
id: 1,
name2: "jsonplaceholder.typicode.com",
port2: 9965,
proxy_ip: "172.25.78.153",
site_ip: "172.25.78.36",
internet_uri: "localhost",
description: "localhost",
is_online: true,
}
const selfObject3 = {
id: 1,
name2: "jsonplaceholder.typicode.com",
port2: 9965,
proxy_ip: "172.25.78.153",
site_ip: "172.25.78.36",
internet_uri: "localhost",
description: "localhost",
is_online: true,
}
const selfList = [selfObject1, selfObject2, selfObject3]
const config = {
id: "id",
name: "name2",
port: "port2",
proxy_ip: "proxy_ip",
site_ip: "site_ip",
internet_uri: "internet_uri",
description: "description",
is_online: "is_online",
}
expect(convertList(targetList, {config})).toEqual(selfList)
})
test('adapt list objects with callback', () => {
const targetObject1 = {
"id": 1,
"created_at": "2024-02-15T17:24:52.755254148+03:00",
"updated_at": "2024-02-15T17:24:52.755254148+03:00",
"deleted_at": null,
"name": "jsonplaceholder.typicode.com",
"port": 9965,
"proxy_ip": "172.25.78.153",
"site_ip": "172.25.78.36",
"internet_uri": "localhost",
"description": "localhost",
"is_online": true
}
const targetObject2 = {
"id": 1,
"created_at": "2024-02-15T17:24:52.755254148+03:00",
"updated_at": "2024-02-15T17:24:52.755254148+03:00",
"deleted_at": null,
"name": "jsonplaceholder.typicode.com",
"port": 9965,
"proxy_ip": "172.25.78.153",
"site_ip": "172.25.78.36",
"internet_uri": "localhost",
"description": "localhost",
"is_online": false
}
const targetList = [targetObject1, targetObject2]
const expectedObject1 = {
id: 1,
name2: "jsonplaceholder.typicode.com",
port2: 9965,
proxy_ip: "172.25.78.153",
site_ip: "172.25.78.36",
internet_uri: "localhost",
description: "localhost",
state: "active",
}
const expectedObject2 = {
id: 1,
name2: "jsonplaceholder.typicode.com",
port2: 9965,
proxy_ip: "172.25.78.153",
site_ip: "172.25.78.36",
internet_uri: "localhost",
description: "localhost",
state: "disabled",
}
const expectedList = [expectedObject1, expectedObject2]
const config = {
id: "id",
name: "name2",
port: "port2",
proxy_ip: "proxy_ip",
site_ip: "site_ip",
internet_uri: "internet_uri",
description: "description",
}
const callback = (el, {is_online}) => ({...el, state: is_online ? "active": "disabled"})
expect(convertList(targetList, {config, callback})).toEqual(expectedList)
})