1
0
mirror of https://github.com/OpenNebula/one.git synced 2025-03-16 22:50:10 +03:00

F OpenNebula/one#5422: Comment redux boilerplate

This commit is contained in:
Sergio Betanzos 2021-07-11 14:38:25 +02:00
parent 142b37f7ee
commit 38084c1851
No known key found for this signature in database
GPG Key ID: E3E704F097737136
51 changed files with 1255 additions and 536 deletions

View File

@ -17,31 +17,33 @@ import * as React from 'react'
import { string, func, shape, object } from 'prop-types'
import { useForm, Controller } from 'react-hook-form'
import {
TextField,
Grid,
Typography,
FormControlLabel,
Checkbox
} from '@material-ui/core'
import { TextField, Grid, Typography, FormControlLabel, Checkbox } from '@material-ui/core'
import { SubmitButton } from 'client/components/FormControl'
import { RestClient, requestParams } from 'client/utils'
import { RestClient, requestConfig } from 'client/utils'
/**
* @param {object} props - Component props
* @param {Function} props.handleChangeResponse - Change after
* @param {object} props.command - Resource command action
* @param {string} props.command.name - Name of command
* @param {('GET'|'POST'|'DELETE'|'PUT')} props.command.httpMethod - Http method
* @param {object} props.command.params - Parameters for the action
* @returns {React.JSXElementConstructor} Form with command parameters
*/
const ResponseForm = ({
handleChangeResponse,
command: { name, httpMethod, params }
}) => {
const { control, handleSubmit, errors, formState } = useForm()
const onSubmit = dataForm => {
const command = { name, httpMethod, params }
const { url, options: { method, data } } = requestParams(dataForm, command)
const onSubmit = async dataForm => {
const config = requestConfig(dataForm, { name, httpMethod, params })
RestClient[method.toLowerCase()](url, data).then(({ id, ...res }) => {
id === 401 && console.log('ERROR')
id === 200 && handleChangeResponse(JSON.stringify(res, null, '\t'))
})
const { id, ...res } = await RestClient.request(config) ?? {}
id === 401 && console.log('ERROR')
id === 200 && handleChangeResponse(JSON.stringify(res, null, '\t'))
}
return (

View File

@ -23,15 +23,20 @@ import { Tr } from 'client/components/HOC'
import { T } from 'client/constants'
import Commands from 'server/utils/constants/commands'
import testapiStyles from 'client/containers/TestApi/styles'
import testApiStyles from 'client/containers/TestApi/styles'
const TestApi = () => {
const classes = testapiStyles()
/**
* @returns {React.JSXElementConstructor} - Component that allows you
* to fetch, resolve, and interact with OpenNebula API.
*/
function TestApi () {
const classes = testApiStyles()
const [name, setName] = useState('acl.addrule')
const [response, setResponse] = useState('')
const handleChangeCommand = evt => setName(evt?.target?.value)
const handleChangeResponse = res => setResponse(res)
return (
<Container
disableGutters

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
/* eslint-disable jsdoc/require-jsdoc */
import { createAsyncThunk, createAction } from '@reduxjs/toolkit'
import { authService } from 'client/features/Auth/services'

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
/* eslint-disable jsdoc/require-jsdoc */
import { createAsyncThunk, createAction } from '@reduxjs/toolkit'
import { authService } from 'client/features/Auth/services'
@ -26,9 +27,10 @@ export const getSunstoneViews = createAsyncThunk(
async (_, { dispatch }) => {
try {
const views = await authService.getSunstoneViews() ?? {}
// const config = await authService.getSunstoneConfig()
const config = await authService.getSunstoneConfig() ?? {}
return {
config,
views,
view: Object.keys(views)[0]
}

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
/* eslint-disable jsdoc/require-jsdoc */
import { useCallback } from 'react'
import { useDispatch, useSelector, shallowEqual } from 'react-redux'
import { unwrapResult } from '@reduxjs/toolkit'
@ -33,6 +34,18 @@ export const useAuth = () => {
const isLogged = !!jwt && !!userGroups?.length
/**
* Looking for resource view of user authenticated.
*
* @param {string} resourceName - Name of resource: VM, HOST, IMAGE, etc
* @returns {{
* resource_name: string,
* actions: object[],
* filters: object[],
* info-tabs: object[],
* dialogs: object[]
* }} Returns view of resource
*/
const getResourceView = resourceName => views?.[view]
?.find(({ resource_name: name }) => name === resourceName)

View File

@ -17,27 +17,56 @@ import { httpCodes } from 'server/utils/constants'
import { RestClient } from 'client/utils'
export const authService = ({
login: user => RestClient.post('/api/auth', user).then(res => {
/**
* @param {object} data - User credentials
* @param {string} data.user - Username
* @param {string} data.token - Password
* @param {boolean} [data.remember] - Remember session
* @param {string} [data.token2fa] - Token for Two factor authentication
* @returns {object} Response data from request
* @throws Fails when response isn't code 200
*/
login: async data => {
const res = await RestClient.request({ url: '/api/auth', data, method: 'POST' })
if (!res?.id || res?.id !== httpCodes.ok.id) {
if (res?.id === httpCodes.accepted.id) return res
throw res
}
return res?.data
}),
getUser: () => RestClient.get('/api/user/info').then(res => {
},
/**
* @returns {object} Information about user authenticated
* @throws Fails when response isn't code 200
*/
getUser: async () => {
const res = await RestClient.request({ url: '/api/user/info' })
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return res?.data?.USER ?? {}
}),
getSunstoneViews: () => RestClient.get('/api/sunstone/views').then(res => {
},
/**
* @returns {object} Views available for the user authenticated
* @throws Fails when response isn't code 200
*/
getSunstoneViews: async () => {
const res = await RestClient.request({ url: '/api/sunstone/views' })
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return res?.data ?? {}
}),
getSunstoneConfig: () => RestClient.get('/api/user/config').then(res => {
},
/**
* @returns {object} Sunstone configuration
* @throws Fails when response isn't code 200
*/
getSunstoneConfig: async () => {
const res = await RestClient.request({ url: '/api/user/config' })
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return res?.data ?? {}
})
}
})

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
/* eslint-disable jsdoc/require-jsdoc */
import { useDispatch, useSelector } from 'react-redux'
import * as actions from 'client/features/General/actions'

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
/* eslint-disable jsdoc/require-jsdoc */
import { useCallback } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { unwrapResult } from '@reduxjs/toolkit'

View File

@ -16,19 +16,39 @@
import { SERVICE } from 'server/routes/api/oneflow/string-routes'
import { httpCodes } from 'server/utils/constants'
import { RestClient } from 'client/utils'
import { poolRequest } from 'client/features/One/utils'
export const applicationService = ({
getApplication: ({ filter, id }) => RestClient
.get(`/api/${SERVICE}/list/${id}`, { filter })
.then(res => {
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
/**
* Retrieves information for the service.
*
* @param {object} data - Request parameters
* @param {string} data.id - Service id
* @returns {object} Get service identified by id
* @throws Fails when response isn't code 200
*/
getApplication: async ({ id }) => {
const res = await RestClient.request({
url: `/api/${SERVICE}/list/${id}`
})
return res?.data?.DOCUMENT ?? {}
}),
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
getApplications: data => {
const command = { name: `${SERVICE}.list`, params: {} }
return poolRequest(data, command, 'DOCUMENT')
return res?.data?.DOCUMENT ?? {}
},
/**
* Retrieves information for all services.
*
* @returns {object} Get list of services
* @throws Fails when response isn't code 200
*/
getApplications: async () => {
const res = await RestClient.request({
url: `/api/${SERVICE}/list`
})
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return [res?.data?.DOCUMENT_POOL?.DOCUMENT ?? []].flat()
}
})

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
/* eslint-disable jsdoc/require-jsdoc */
import { useCallback } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { unwrapResult } from '@reduxjs/toolkit'

View File

@ -14,52 +14,108 @@
* limitations under the License. *
* ------------------------------------------------------------------------- */
import { SERVICE_TEMPLATE } from 'server/routes/api/oneflow/string-routes'
import { httpCodes } from 'server/utils/constants'
import { httpCodes, defaults } from 'server/utils/constants'
import { RestClient } from 'client/utils'
import { poolRequest } from 'client/features/One/utils'
const { POST, PUT } = defaults?.httpMethod || {}
export const applicationTemplateService = ({
getApplicationTemplate: ({ filter, id }) => RestClient
.get(`/api/${SERVICE_TEMPLATE}/list/${id}`, { filter })
.then(res => {
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
/**
* Retrieves information for the service template.
*
* @param {object} data - Request parameters
* @param {string} data.id - Service template id
* @returns {object} Get service template identified by id
* @throws Fails when response isn't code 200
*/
getApplicationTemplate: ({ id }) => {
const res = RestClient.request({
url: `/api/${SERVICE_TEMPLATE}/list/${id}`
})
return res?.data?.DOCUMENT ?? {}
}),
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
getApplicationsTemplates: data => {
const command = { name: `${SERVICE_TEMPLATE}.list`, params: {} }
return poolRequest(data, command, 'DOCUMENT')
return res?.data?.DOCUMENT ?? {}
},
createApplicationTemplate: ({ data = {} }) => RestClient
.post(`/api/${SERVICE_TEMPLATE}/create`, data)
.then(res => {
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
/**
* @returns {object} Get list of service templates
* @throws Fails when response isn't code 200
*/
getApplicationsTemplates: async () => {
const res = await RestClient.request({
url: `/api/${SERVICE_TEMPLATE}/list`
})
return res?.data?.DOCUMENT ?? {}
}),
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
updateApplicationTemplate: ({ id, data = {} }) => RestClient
.put(`/api/${SERVICE_TEMPLATE}/update/${id}`, data)
.then(res => {
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return [res?.data?.DOCUMENT_POOL?.DOCUMENT ?? []].flat()
},
return res?.data?.DOCUMENT ?? {}
}),
/**
* Retrieves information for all service templates.
*
* @param {object} params - Request parameters
* @param {object} params.data - Data of new application template
* @returns {object} Object of document created
* @throws Fails when response isn't code 200
*/
createApplicationTemplate: async ({ data = {} }) => {
const res = await RestClient.request({
data,
method: POST,
url: `/api/${SERVICE_TEMPLATE}/create`
})
instantiateApplicationTemplate: ({ id, data = {} }) => RestClient
.post(`/api/${SERVICE_TEMPLATE}/action/${id}`, {
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return res?.data?.DOCUMENT ?? {}
},
/**
* Update the service template.
*
* @param {object} params - Request parameters
* @param {object} params.id - Service template id
* @param {object} params.data - Updated data
* @returns {object} Object of document updated
* @throws Fails when response isn't code 200
*/
updateApplicationTemplate: ({ id, data = {} }) => {
const res = RestClient.request({
data,
method: PUT,
url: `/api/${SERVICE_TEMPLATE}/update/${id}`
})
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return res?.data?.DOCUMENT ?? {}
},
/**
* Perform instantiate action on the service template.
*
* @param {object} params - Request parameters
* @param {object} params.id - Service template id
* @param {object} params.data - Additional parameters to be passed inside `params`
* @returns {Response} Response 201
* @throws Fails when response isn't code 200
*/
instantiateApplicationTemplate: ({ id, data = {} }) => {
const res = RestClient.request({
data: {
action: {
perform: 'instantiate',
params: { merge_template: data }
}
}
},
method: PUT,
url: `/api/${SERVICE_TEMPLATE}/action/${id}`
})
.then(res => {
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return res?.data?.DOCUMENT ?? {}
})
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return res?.data ?? {}
}
})

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
/* eslint-disable jsdoc/require-jsdoc */
import { useCallback } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { unwrapResult } from '@reduxjs/toolkit'

View File

@ -15,26 +15,44 @@
* ------------------------------------------------------------------------- */
import { Actions, Commands } from 'server/utils/constants/commands/cluster'
import { httpCodes } from 'server/utils/constants'
import { requestParams, RestClient } from 'client/utils'
import { poolRequest } from 'client/features/One/utils'
import { requestConfig, RestClient } from 'client/utils'
export const clusterService = ({
getCluster: ({ filter, id }) => {
/**
* Retrieves information for the cluster.
*
* @param {object} data - Request parameters
* @param {string} data.id - Cluster id
* @returns {object} Get cluster identified by id
* @throws Fails when response isn't code 200
*/
getCluster: async ({ id }) => {
const name = Actions.CLUSTER_INFO
const { url, options } = requestParams(
{ filter, id },
{ name, ...Commands[name] }
)
const command = { name, ...Commands[name] }
const config = requestConfig({ id }, command)
return RestClient.get(url, options).then(res => {
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
const res = await RestClient.request(config)
return res?.data?.CLUSTER ?? {}
})
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return res?.data?.CLUSTER ?? {}
},
getClusters: data => {
/**
* Retrieves information for all the clusters in the pool.
*
* @returns {Array} List of clusters
* @throws Fails when response isn't code 200
*/
getClusters: async () => {
const name = Actions.CLUSTER_POOL_INFO
const command = { name, ...Commands[name] }
return poolRequest(data, command, 'CLUSTER')
const config = requestConfig(undefined, command)
const res = await RestClient.request(config)
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return [res?.data?.CLUSTER_POOL?.CLUSTER ?? []].flat()
}
})

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
/* eslint-disable jsdoc/require-jsdoc */
import { useCallback } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { unwrapResult } from '@reduxjs/toolkit'

View File

@ -15,26 +15,44 @@
* ------------------------------------------------------------------------- */
import { Actions, Commands } from 'server/utils/constants/commands/datastore'
import { httpCodes } from 'server/utils/constants'
import { requestParams, RestClient } from 'client/utils'
import { poolRequest } from 'client/features/One/utils'
import { requestConfig, RestClient } from 'client/utils'
export const datastoreService = ({
getDatastore: ({ filter, id }) => {
/**
* Retrieves information for the datastore.
*
* @param {object} data - Request parameters
* @param {string} data.id - Datastore id
* @returns {object} Get datastore identified by id
* @throws Fails when response isn't code 200
*/
getDatastore: async ({ id }) => {
const name = Actions.DATASTORE_INFO
const { url, options } = requestParams(
{ filter, id },
{ name, ...Commands[name] }
)
const command = { name, ...Commands[name] }
const config = requestConfig({ id }, command)
return RestClient.get(url, options).then(res => {
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
const res = await RestClient.request(config)
return res?.data?.DATASTORE ?? {}
})
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return res?.data?.DATASTORE ?? {}
},
getDatastores: data => {
/**
* Retrieves information for all datastores in the pool.
*
* @returns {object} Get list of datastores
* @throws Fails when response isn't code 200
*/
getDatastores: async () => {
const name = Actions.DATASTORE_POOL_INFO
const command = { name, ...Commands[name] }
return poolRequest(data, command, 'DATASTORE')
const config = requestConfig(undefined, command)
const res = await RestClient.request(config)
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return [res?.data?.DATASTORE_POOL?.DATASTORE ?? []].flat()
}
})

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
/* eslint-disable jsdoc/require-jsdoc */
import { useCallback } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { unwrapResult } from '@reduxjs/toolkit'

View File

@ -15,26 +15,44 @@
* ------------------------------------------------------------------------- */
import { Actions, Commands } from 'server/utils/constants/commands/group'
import { httpCodes } from 'server/utils/constants'
import { requestParams, RestClient } from 'client/utils'
import { poolRequest } from 'client/features/One/utils'
import { requestConfig, RestClient } from 'client/utils'
export const groupService = ({
getGroup: ({ filter, id }) => {
/**
* Retrieves information for the group.
*
* @param {object} data - Request parameters
* @param {string} data.id - Group id
* @returns {object} Get group identified by id
* @throws Fails when response isn't code 200
*/
getGroup: async ({ id }) => {
const name = Actions.GROUP_INFO
const { url, options } = requestParams(
{ filter, id },
{ name, ...Commands[name] }
)
const command = { name, ...Commands[name] }
const { url, options } = requestConfig({ id }, command)
return RestClient.get(url, options).then(res => {
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
const res = await RestClient.get(url, options)
return res?.data?.GROUP ?? {}
})
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return res?.data?.GROUP ?? {}
},
getGroups: data => {
/**
* Retrieves information for all the groups in the pool.
*
* @returns {object} Get list of groups
* @throws Fails when response isn't code 200
*/
getGroups: async () => {
const name = Actions.GROUP_POOL_INFO
const command = { name, ...Commands[name] }
return poolRequest(data, command, 'GROUP')
const config = requestConfig(undefined, command)
const res = await RestClient.request(config)
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return [res?.data?.GROUP_POOL?.GROUP ?? []].flat()
}
})

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
/* eslint-disable jsdoc/require-jsdoc */
import { useSelector, shallowEqual } from 'react-redux'
export const useOne = () => (

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
/* eslint-disable jsdoc/require-jsdoc */
import { useCallback } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { unwrapResult } from '@reduxjs/toolkit'

View File

@ -15,26 +15,44 @@
* ------------------------------------------------------------------------- */
import { Actions, Commands } from 'server/utils/constants/commands/host'
import { httpCodes } from 'server/utils/constants'
import { requestParams, RestClient } from 'client/utils'
import { poolRequest } from 'client/features/One/utils'
import { requestConfig, RestClient } from 'client/utils'
export const hostService = ({
getHost: ({ filter, id }) => {
/**
* Retrieves information for the host.
*
* @param {object} data - Request parameters
* @param {string} data.id - Host id
* @returns {object} Get host identified by id
* @throws Fails when response isn't code 200
*/
getHost: async ({ id }) => {
const name = Actions.HOST_INFO
const { url, options } = requestParams(
{ filter, id },
{ name, ...Commands[name] }
)
const command = { name, ...Commands[name] }
const config = requestConfig({ id }, command)
return RestClient.get(url, options).then(res => {
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
const res = await RestClient.request(config)
return res?.data?.HOST ?? {}
})
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return res?.data?.HOST ?? {}
},
getHosts: data => {
/**
* Retrieves information for all the hosts in the pool.
*
* @returns {object} Get list of hosts
* @throws Fails when response isn't code 200
*/
getHosts: async () => {
const name = Actions.HOST_POOL_INFO
const command = { name, ...Commands[name] }
return poolRequest(data, command, 'HOST')
const config = requestConfig(undefined, command)
const res = await RestClient.request(config)
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return [res?.data?.HOST_POOL?.HOST ?? []].flat()
}
})

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
/* eslint-disable jsdoc/require-jsdoc */
import { useCallback } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { unwrapResult } from '@reduxjs/toolkit'

View File

@ -15,26 +15,49 @@
* ------------------------------------------------------------------------- */
import { Actions, Commands } from 'server/utils/constants/commands/image'
import { httpCodes } from 'server/utils/constants'
import { requestParams, RestClient } from 'client/utils'
import { poolRequest } from 'client/features/One/utils'
import { requestConfig, RestClient } from 'client/utils'
export const imageService = ({
getImage: ({ filter, id }) => {
/**
* Retrieves information for the image.
*
* @param {object} data - Request parameters
* @param {string} data.id - Image id
* @returns {object} Get image identified by id
* @throws Fails when response isn't code 200
*/
getImage: async ({ id }) => {
const name = Actions.IMAGE_INFO
const { url, options } = requestParams(
{ filter, id },
{ name, ...Commands[name] }
)
const command = { name, ...Commands[name] }
const config = requestConfig({ id }, command)
return RestClient.get(url, options).then(res => {
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
const res = await RestClient.request(config)
return res?.data?.IMAGE ?? {}
})
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return res?.data?.IMAGE ?? {}
},
getImages: data => {
/**
* Retrieves information for all or part of the
* images in the pool.
*
* @param {object} data - Request params
* @param {string} data.filter - Filter flag
* @param {number} data.start - Range start ID
* @param {number} data.end - Range end ID
* @returns {object} Get list of images
* @throws Fails when response isn't code 200
*/
getImages: async ({ filter, start, end }) => {
const name = Actions.IMAGE_POOL_INFO
const command = { name, ...Commands[name] }
return poolRequest(data, command, 'IMAGE')
const config = requestConfig({ filter, start, end }, command)
const res = await RestClient.request(config)
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return [res?.data?.IMAGE_POOL?.IMAGE ?? []].flat()
}
})

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
/* eslint-disable jsdoc/require-jsdoc */
import { useCallback } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { unwrapResult } from '@reduxjs/toolkit'

View File

@ -15,26 +15,44 @@
* ------------------------------------------------------------------------- */
import { Actions, Commands } from 'server/utils/constants/commands/market'
import { httpCodes } from 'server/utils/constants'
import { requestParams, RestClient } from 'client/utils'
import { poolRequest } from 'client/features/One/utils'
import { requestConfig, RestClient } from 'client/utils'
export const marketplaceService = ({
getMarketplace: ({ filter, id }) => {
/**
* Retrieves information for the marketplace.
*
* @param {object} data - Request parameters
* @param {string} data.id - Marketplace id
* @returns {object} Get marketplace identified by id
* @throws Fails when response isn't code 200
*/
getMarketplace: async ({ id }) => {
const name = Actions.MARKET_INFO
const { url, options } = requestParams(
{ filter, id },
{ name, ...Commands[name] }
)
const command = { name, ...Commands[name] }
const config = requestConfig({ id }, command)
return RestClient.get(url, options).then(res => {
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
const res = await RestClient.request(config)
return res?.data?.MARKETPLACE ?? {}
})
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return res?.data?.MARKETPLACE ?? {}
},
getMarketplaces: data => {
/**
* Retrieves information for all marketplaces.
*
* @returns {object} Get list of marketplaces
* @throws Fails when response isn't code 200
*/
getMarketplaces: async () => {
const name = Actions.MARKET_POOL_INFO
const command = { name, ...Commands[name] }
return poolRequest(data, command, 'MARKETPLACE')
const config = requestConfig(undefined, command)
const res = await RestClient.request(config)
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return [res?.data?.MARKETPLACE_POOL?.MARKETPLACE ?? []].flat()
}
})

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
/* eslint-disable jsdoc/require-jsdoc */
import { useCallback } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { unwrapResult } from '@reduxjs/toolkit'

View File

@ -15,26 +15,49 @@
* ------------------------------------------------------------------------- */
import { Actions, Commands } from 'server/utils/constants/commands/marketapp'
import { httpCodes } from 'server/utils/constants'
import { requestParams, RestClient } from 'client/utils'
import { poolRequest } from 'client/features/One/utils'
import { requestConfig, RestClient } from 'client/utils'
export const marketplaceAppService = ({
getMarketplaceApp: ({ filter, id }) => {
/**
* Retrieves information for the marketplace app.
*
* @param {object} data - Request parameters
* @param {string} data.id - Marketplace apps id
* @returns {object} Get marketplace app identified by id
* @throws Fails when response isn't code 200
*/
getMarketplaceApp: async ({ id }) => {
const name = Actions.MARKETAPP_INFO
const { url, options } = requestParams(
{ filter, id },
{ name, ...Commands[name] }
)
const command = { name, ...Commands[name] }
const config = requestConfig({ id }, command)
return RestClient.get(url, options).then(res => {
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
const res = await RestClient.request(config)
return res?.data?.MARKETAPP ?? {}
})
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return res?.data?.MARKETAPP ?? {}
},
getMarketplaceApps: data => {
/**
* Retrieves information for all or part of the
* marketplace apps in the pool.
*
* @param {object} data - Request params
* @param {string} data.filter - Filter flag
* @param {number} data.start - Range start ID
* @param {number} data.end - Range end ID
* @returns {Array} List of marketplace apps
* @throws Fails when response isn't code 200
*/
getMarketplaceApps: async ({ filter, start, end }) => {
const name = Actions.MARKETAPP_POOL_INFO
const command = { name, ...Commands[name] }
return poolRequest(data, command, 'MARKETPLACEAPP')
const config = requestConfig({ filter, start, end }, command)
const res = await RestClient.request(config)
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return [res?.data?.MARKETPLACEAPP_POOL?.MARKETPLACEAPP ?? []].flat()
}
})

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
/* eslint-disable jsdoc/require-jsdoc */
import { useCallback } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { unwrapResult } from '@reduxjs/toolkit'

View File

@ -14,57 +14,123 @@
* limitations under the License. *
* ------------------------------------------------------------------------- */
import { PROVIDER } from 'server/routes/api/provision/string-routes'
import { httpCodes } from 'server/utils/constants'
import { httpCodes, defaults } from 'server/utils/constants'
import { RestClient } from 'client/utils'
import { poolRequest } from 'client/features/One/utils'
const { POST, PUT, DELETE } = defaults?.httpMethod || {}
export const providerService = ({
// --------------------------------------------
// PROVIDERS REQUESTS
// --------------------------------------------
/**
* Retrieves information for the provider.
*
* @param {object} data - Request parameters
* @param {string} data.id - Provider id
* @returns {object} Get provider identified by id
* @throws Fails when response isn't code 200
*/
getProvider: async ({ id }) => {
const res = await RestClient.request({
url: `/api/${PROVIDER}/list/${id}`
})
getProvider: ({ filter, id }) => RestClient
.get(`/api/${PROVIDER}/list/${id}`, { filter })
.then(res => {
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return res?.data?.DOCUMENT ?? {}
}),
getProviders: data => {
const command = { name: `${PROVIDER}.list`, params: {} }
return poolRequest(data, command, 'DOCUMENT')
return res?.data?.DOCUMENT ?? {}
},
getProviderConnection: ({ id }) => RestClient
.get(`/api/${PROVIDER}/connection/${id}`)
.then(res => {
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return res?.data ?? {}
}),
createProvider: ({ data = {} }) => RestClient
.post(`/api/${PROVIDER}/create`, data)
.then(res => {
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return res?.data ?? {}
}),
updateProvider: ({ id, data = {} }) => RestClient
.put(`/api/${PROVIDER}/update/${id}`, data)
.then(res => {
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return res?.data ?? {}
}),
deleteProvider: ({ id }) => RestClient
.delete(`/api/${PROVIDER}/delete/${id}`)
.then(res => {
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return res?.data ?? {}
/**
* Retrieves information for all providers.
*
* @returns {Array} List of providers
* @throws Fails when response isn't code 200
*/
getProviders: async () => {
const res = await RestClient.request({
url: `/api/${PROVIDER}/list`
})
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return [res?.data?.DOCUMENT_POOL?.DOCUMENT ?? []].flat()
},
/**
* Retrieves connection information for the
* provider.
*
* @param {object} data - Request parameters
* @param {string} data.id - Provider id
* @returns {object} Get connection info from the
* provider identified by id
* @throws Fails when response isn't code 200
*/
getProviderConnection: async ({ id }) => {
const res = await RestClient.request({
url: `/api/${PROVIDER}/connection/${id}`
})
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return res?.data ?? {}
},
/**
* Create a provider.
*
* @param {object} params - Request parameters
* @param {object} params.data - Template data
* @returns {object} Object of document created
* @throws Fails when response isn't code 200
*/
createProvider: async ({ data = {} }) => {
const res = await RestClient.request({
data,
method: POST,
url: `/api/${PROVIDER}/create`
})
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return res?.data ?? {}
},
/**
* Update the provider information.
*
* @param {object} params - Request parameters
* @param {object} params.id - Provider id
* @param {object} params.data - Updated data
* @returns {object} Object of document updated
* @throws Fails when response isn't code 200
*/
updateProvider: async ({ id, data = {} }) => {
const res = await RestClient.request({
data,
method: PUT,
url: `/api/${PROVIDER}/update/${id}`
})
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return res?.data ?? {}
},
/**
* Delete the provider.
*
* @param {object} params - Request parameters
* @param {object} params.id - Provider id
* @returns {object} Object of document deleted
* @throws Fails when response isn't code 200
*/
deleteProvider: async ({ id }) => {
const res = await RestClient.request({
method: DELETE,
url: `/api/${PROVIDER}/delete/${id}`
})
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return res?.data ?? {}
}
})

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
/* eslint-disable jsdoc/require-jsdoc */
import { useCallback } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { unwrapResult } from '@reduxjs/toolkit'

View File

@ -14,123 +14,248 @@
* limitations under the License. *
* ------------------------------------------------------------------------- */
import { PROVISION } from 'server/routes/api/provision/string-routes'
import { httpCodes } from 'server/utils/constants'
import { httpCodes, defaults } from 'server/utils/constants'
import { RestClient } from 'client/utils'
import { poolRequest } from 'client/features/One/utils'
const { POST, PUT, DELETE } = defaults?.httpMethod || {}
export const provisionService = ({
// --------------------------------------------
// ALL PROVISION TEMPLATES REQUESTS
// PROVISION TEMPLATE requests
// --------------------------------------------
getProvisionsTemplates: ({ filter }) => RestClient
.get(`/api/${PROVISION}/defaults`, { data: { filter } })
.then(res => {
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
/**
* Retrieves information for all the
* provision templates.
*
* @returns {Array} List of provision templates
* @throws Fails when response isn't code 200
*/
getProvisionsTemplates: async () => {
const res = await RestClient.request({
url: `/api/${PROVISION}/defaults`
})
return res?.data ?? []
}),
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
createProvisionTemplate: ({ data = {} }) =>
Promise.resolve().then(res => res?.data?.DOCUMENT ?? {}),
// --------------------------------------------
// PROVISIONS REQUESTS
// --------------------------------------------
getProvision: ({ filter, id }) => RestClient
.get(`/api/${PROVISION}/list/${id}`, { filter })
.then(res => {
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return res?.data?.DOCUMENT ?? {}
}),
getProvisions: data => {
const command = { name: `${PROVISION}.list`, params: {} }
return poolRequest(data, command, 'DOCUMENT')
return res?.data ?? []
},
createProvision: ({ data = {} }) => RestClient
.post(`/api/${PROVISION}/create`, data)
.then(res => {
if (!res?.id || res?.id !== httpCodes.ok.id) {
if (res?.id === httpCodes.accepted.id) return res?.data
throw res
}
return res?.data
}),
configureProvision: ({ id }) => RestClient
.put(`/api/${PROVISION}/configure/${id}`)
.then(res => {
if (!res?.id || res?.id !== httpCodes.ok.id) {
if (res?.id === httpCodes.accepted.id) return res
throw res
}
return res?.data ?? {}
}),
deleteProvision: ({ id }) => RestClient
.delete(`/api/${PROVISION}/delete/${id}`)
.then(res => {
if (!res?.id || res?.id !== httpCodes.ok.id) {
if (res?.id === httpCodes.accepted.id) return res
throw res
}
return res?.data ?? {}
}),
getProvisionLog: ({ id }) => RestClient
.get(`/api/${PROVISION}/log/${id}`)
.then(res => {
if (!res?.id || res?.id !== httpCodes.ok.id) {
if (res?.id === httpCodes.accepted.id) return res
throw res
}
return res?.data ?? {}
}),
/**
* TODO: Create a provision template.
*
* @returns {Promise} TODO
*/
createProvisionTemplate: () => {
return Promise.resolve().then(res => res?.data?.DOCUMENT ?? {})
},
// --------------------------------------------
// INFRASTRUCTURES REQUESTS
// PROVISION requests
// --------------------------------------------
deleteDatastore: ({ id }) => RestClient
.delete(`/api/${PROVISION}/datastore/${id}`)
.then(res => {
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return res?.data ?? {}
}),
deleteVNetwork: ({ id }) => RestClient
.delete(`/api/${PROVISION}/network/${id}`)
.then(res => {
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return res?.data ?? {}
}),
deleteHost: ({ id }) => RestClient
.delete(`/api/${PROVISION}/host/${id}`)
.then(res => {
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return res?.data ?? {}
}),
configureHost: ({ id }) => RestClient
.put(`/api/${PROVISION}/host/${id}`)
.then(res => {
if (!res?.id || res?.id !== httpCodes.ok.id) {
if (res?.id === httpCodes.accepted.id) return res
throw res
}
return res?.data ?? {}
/**
* Retrieves information for the provision.
*
* @param {object} data - Request parameters
* @param {string} data.id - Provision id
* @returns {object} Get provision identified by id
* @throws Fails when response isn't code 200
*/
getProvision: async ({ id }) => {
const res = await RestClient.request({
url: `/api/${PROVISION}/list/${id}`
})
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return res?.data?.DOCUMENT ?? {}
},
/**
* Retrieves information for all providers.
*
* @returns {Array} List of providers
* @throws Fails when response isn't code 200
*/
getProvisions: async () => {
const res = await RestClient.request({
url: `/api/${PROVISION}/list`
})
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return [res?.data?.DOCUMENT_POOL?.DOCUMENT ?? []].flat()
},
/**
* Create a provision.
*
* @param {object} params - Request parameters
* @param {object} params.data - Form data
* @returns {object} Object of document created
* @throws Fails when response isn't code 200
*/
createProvision: async ({ data = {} }) => {
const res = await RestClient.request({
data,
method: POST,
url: `/api/${PROVISION}/create`
})
if (!res?.id || res?.id !== httpCodes.ok.id) {
if (res?.id === httpCodes.accepted.id) return res?.data
throw res
}
return res?.data
},
/**
* Configure the provision hosts.
*
* @param {object} params - Request parameters
* @param {object} params.id - Provision id
* @returns {object} Object of document updated
* @throws Fails when response isn't code 200
*/
configureProvision: async ({ id }) => {
const res = await RestClient.request({
method: PUT,
url: `/api/${PROVISION}/configure/${id}`
})
if (!res?.id || res?.id !== httpCodes.ok.id) {
if (res?.id === httpCodes.accepted.id) return res
throw res
}
return res?.data ?? {}
},
/**
* Delete the provision and OpenNebula objects.
*
* @param {object} params - Request parameters
* @param {object} params.id - Provider id
* @returns {object} Object of document deleted
* @throws Fails when response isn't code 200
*/
deleteProvision: async ({ id }) => {
const res = await RestClient.request({
method: DELETE,
url: `/api/${PROVISION}/delete/${id}`
})
if (!res?.id || res?.id !== httpCodes.ok.id) {
if (res?.id === httpCodes.accepted.id) return res
throw res
}
return res?.data ?? {}
},
/**
* Retrieves debug log for the provision.
*
* @param {object} data - Request parameters
* @param {string} data.id - Provision id
* @returns {object} Get provision log identified by id
* @throws Fails when response isn't code 200
*/
getProvisionLog: async ({ id }) => {
const res = await RestClient.request({
url: `/api/${PROVISION}/log/${id}`
})
if (!res?.id || res?.id !== httpCodes.ok.id) {
if (res?.id === httpCodes.accepted.id) return res
throw res
}
return res?.data ?? {}
},
// --------------------------------------------
// INFRASTRUCTURE requests
// --------------------------------------------
/**
* Delete the datastore from the provision.
*
* @param {object} params - Request parameters
* @param {object} params.id - Datastore id
* @returns {object} Object of document deleted
* @throws Fails when response isn't code 200
*/
deleteDatastore: async ({ id }) => {
const res = await RestClient.request({
method: DELETE,
url: `/api/${PROVISION}/datastore/${id}`
})
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return res?.data ?? {}
},
/**
* Delete the virtual network from the provision.
*
* @param {object} params - Request parameters
* @param {object} params.id - Virtual network id
* @returns {object} Object of document deleted
* @throws Fails when response isn't code 200
*/
deleteVNetwork: async ({ id }) => {
const res = await RestClient.request({
method: DELETE,
url: `/api/${PROVISION}/network/${id}`
})
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return res?.data ?? {}
},
/**
* Delete the host from the provision.
*
* @param {object} params - Request parameters
* @param {object} params.id - Host id
* @returns {object} Object of document deleted
* @throws Fails when response isn't code 200
*/
deleteHost: async ({ id }) => {
const res = await RestClient.request({
method: DELETE,
url: `/api/${PROVISION}/host/${id}`
})
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return res?.data ?? {}
},
/**
* Configure the provision host.
*
* @param {object} params - Request parameters
* @param {object} params.id - Host id
* @returns {object} Object of document updated
* @throws Fails when response isn't code 200
*/
configureHost: async ({ id }) => {
const res = await RestClient.request({
method: PUT,
url: `/api/${PROVISION}/host/${id}`
})
if (!res?.id || res?.id !== httpCodes.ok.id) {
if (res?.id === httpCodes.accepted.id) return res
throw res
}
return res?.data ?? {}
}
})

View File

@ -22,8 +22,6 @@ import { updateResourceFromFetch } from 'client/features/One/actions'
const getNameListFromType = type => RESOURCES[type.split('/')[0]]
const ATTRIBUTES_EDITABLE = ['NAME', 'STATE', 'LCM_STATE']
const RESOURCES = {
acl: 'acl',
app: 'apps',
@ -129,4 +127,4 @@ const { actions, reducer } = createSlice({
}
})
export { actions, reducer, RESOURCES, ATTRIBUTES_EDITABLE }
export { actions, reducer, RESOURCES }

View File

@ -27,20 +27,81 @@ const COMMANDS = {
delete: 'delete'
}
export const getResourceFromEventState = socketData => {
const { HOOK_OBJECT: name, [name]: value } = socketData?.data?.HOOK_MESSAGE ?? {}
/**
* @param {object} data
* - Event data from socket
* @param {object} data.HOOK_MESSAGE
* - Hook message from OpenNebula API
* @param {'STATE'} data.HOOK_MESSAGE.HOOK_TYPE
* - Type of event API
* @param {('VM'|'HOST'|'IMAGE')} data.HOOK_MESSAGE.HOOK_OBJECT
* - Type name of the resource
* @param {string} data.HOOK_MESSAGE.STATE
* - The state that triggers the hook.
* @param {string} [data.HOOK_MESSAGE.LCM_STATE]
* - The LCM state that triggers the hook (Only for VM hooks)
* @param {string} [data.HOOK_MESSAGE.REMOTE_HOST]
* - If ``yes`` the hook will be executed in the host that triggered
* the hook (for Host hooks) or in the host where the VM is running (for VM hooks).
* Not used for Image hooks.
* @param {string} data.HOOK_MESSAGE.RESOURCE_ID
* - ID of resource
* @param {object} [data.HOOK_MESSAGE.VM]
* - New data of the VM
* @param {object} [data.HOOK_MESSAGE.HOST]
* - New data of the HOST
* @param {object} [data.HOOK_MESSAGE.IMAGE]
* - New data of the IMAGE
* @returns {{name: ('vm'|'host'|'image'), value: object}}
* - Name and new value of resource
*/
export const getResourceFromEventState = data => {
const { HOOK_OBJECT: name, [name]: value } = data?.HOOK_MESSAGE ?? {}
return { name: String(name).toLowerCase(), value }
}
export const getResourceFromEventApi = (eventApi = {}) => {
const { CALL: command = '', CALL_INFO: info = {} } = eventApi?.HOOK_MESSAGE
/**
* API call parameter.
*
* @typedef {object} Parameter
* @property {number} POSITION - Parameter position in the list
* @property {('IN'|'OUT')} TYPE - Parameter type
* @property {string} VALUE - Parameter value as string
*/
/**
* @param {object} data
* - Event data from socket
* @param {object} data.HOOK_MESSAGE
* - Hook message from OpenNebula API
* @param {'API'} data.HOOK_MESSAGE.HOOK_TYPE
* - Type of event API
* @param {string} data.HOOK_MESSAGE.CALL
* - Action name: 'one.resourceName.action'
* @param {object} [data.HOOK_MESSAGE.CALL_INFO]
* - Information about result of action
* @param {(0|1)} data.HOOK_MESSAGE.CALL_INFO.RESULT
* - `1` for success and `0` for error result
* @param {Parameter[]|Parameter} [data.HOOK_MESSAGE.CALL_INFO.PARAMETERS]
* - The list of IN and OUT parameters will match the API call parameters
* @param {object} [data.HOOK_MESSAGE.CALL_INFO.EXTRA]
* - Extra information returned for API Hooks
* @returns {{
* action: string,
* name: string,
* value: object,
* success: boolean,
* output: object
* }} - Resource information from event Api
*/
export const getResourceFromEventApi = (data = {}) => {
const { CALL: command = '', CALL_INFO: info = {} } = data?.HOOK_MESSAGE
const { EXTRA: extra, RESULT: result, PARAMETERS } = info
// command: 'one.resourceName.action'
const [, resourceName, action] = command.split('.')
// success: 1 || error: 0
const success = result === '1'
const value = extra?.[String(resourceName).toUpperCase()]
@ -51,18 +112,15 @@ export const getResourceFromEventApi = (eventApi = {}) => {
const [, { VALUE: output }] = PARAMETERS?.PARAMETER
?.filter(({ TYPE }) => TYPE === 'OUT')
return {
action,
name,
value,
success,
output
}
return { action, name, value, success, output }
}
export const socketEventApi = createAsyncThunk(
/**
* The API hooks are triggered after the execution of an API call.
*/
export const eventApi = createAsyncThunk(
'socket/event-api',
({ data }) => {
({ data } = {}) => {
const { action, name, value, success } = getResourceFromEventApi(data)
// console.log({ action, name, value, success, output })
@ -70,23 +128,29 @@ export const socketEventApi = createAsyncThunk(
return (success && value && action !== COMMANDS.delete) ? { [name]: value } : {}
},
{
condition: payload => payload?.data?.HOOK_MESSAGE?.HOOK_TYPE === 'API'
condition: ({ data } = {}) => data?.HOOK_MESSAGE?.HOOK_TYPE === 'API'
}
)
/**
* Dispatch new resource object when OpenNebula hooks is triggered
* on specific state transition.
*
* Supported values: `HOST`, `VM`, `IMAGE`
*/
export const eventUpdateResourceState = createAsyncThunk(
'socket/event-state',
socketData => {
const { name, value } = getResourceFromEventState(socketData)
({ data } = {}) => {
const { name, value } = getResourceFromEventState(data)
return { type: name, data: value }
},
{
condition: socketData => {
const { name, value } = getResourceFromEventState(socketData)
condition: ({ data } = {}) => {
const { name, value } = getResourceFromEventState(data)
return (
socketData?.data?.HOOK_MESSAGE?.HOOK_TYPE === 'STATE' &&
data?.HOOK_MESSAGE?.HOOK_TYPE === 'STATE' &&
// possible hook objects: VM, IMAGE, HOST
['vm', 'host', 'image'].includes(name) &&
// update the list if event returns resource value
@ -96,7 +160,10 @@ export const eventUpdateResourceState = createAsyncThunk(
}
)
export const socketCreateProvision = createAsyncThunk(
/**
* Dispatch successfully notification when one provision is created
*/
export const onCreateProvision = createAsyncThunk(
'socket/create-provision',
(_, { dispatch }) => {
dispatch(actions.enqueueSnackbar({

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
/* eslint-disable jsdoc/require-jsdoc */
import { useCallback } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { unwrapResult } from '@reduxjs/toolkit'

View File

@ -15,46 +15,84 @@
* ------------------------------------------------------------------------- */
import { Actions, Commands } from 'server/utils/constants/commands/user'
import { httpCodes } from 'server/utils/constants'
import { requestParams, RestClient } from 'client/utils'
import { poolRequest } from 'client/features/One/utils'
import { requestConfig, RestClient } from 'client/utils'
export const userService = ({
getUser: ({ filter, id }) => {
/**
* Retrieves information for the user.
*
* @param {object} data - Request parameters
* @param {string} data.id - User id
* @returns {object} Get user identified by id
* @throws Fails when response isn't code 200
*/
getUser: async ({ id }) => {
const name = Actions.USER_INFO
const { url, options } = requestParams(
{ filter, id },
{ name, ...Commands[name] }
)
const command = { name, ...Commands[name] }
const config = requestConfig({ id }, command)
return RestClient.get(url, options).then(res => {
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
const res = await RestClient.request(config)
return res?.data?.USER ?? {}
})
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return res?.data?.USER ?? {}
},
getUsers: data => {
/**
* Retrieves information for all the users in the pool.
*
* @returns {Array} List of users
* @throws Fails when response isn't code 200
*/
getUsers: async () => {
const name = Actions.USER_POOL_INFO
const command = { name, ...Commands[name] }
return poolRequest(data, command, 'USER')
const config = requestConfig(undefined, command)
const res = await RestClient.request(config)
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return [res?.data?.USER_POOL?.USER ?? []].flat()
},
changeGroup: ({ data }) => {
/**
* Changes the group of the given user.
*
* @param {object} params - Request parameters
* @param {object} params.data - Form data
* @returns {object} Object of document updated
* @throws Fails when response isn't code 200
*/
changeGroup: async ({ data }) => {
const name = Actions.USER_CHGRP
const { url, options } = requestParams(data, { name, ...Commands[name] })
const command = { name, ...Commands[name] }
const config = requestConfig(data, command)
return RestClient.put(url, options.data).then(res => {
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
const res = await RestClient.request(config)
return res?.data ?? {}
})
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return res?.data ?? {}
},
/**
* Replaces the user template contents.
*
* @param {object} params - Request parameters
* @param {object} params.data - Form data
* @returns {object} Object of document updated
* @throws Fails when response isn't code 200
*/
updateUser: ({ data }) => {
const name = Actions.USER_UPDATE
const { url, options } = requestParams(data, { name, ...Commands[name] })
const command = { name, ...Commands[name] }
const config = requestConfig(data, command)
return RestClient.put(url, options.data).then(res => {
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
const res = RestClient.request(config)
return res?.data ?? {}
})
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return res?.data ?? {}
}
})

View File

@ -13,15 +13,21 @@
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
import { createAsyncThunk } from '@reduxjs/toolkit'
import { createAsyncThunk, AsyncThunkAction } from '@reduxjs/toolkit'
import { logout } from 'client/features/Auth/actions'
import { ATTRIBUTES_EDITABLE } from 'client/features/One/slice'
import { requestParams, RestClient } from 'client/utils'
import { T } from 'client/constants'
import { httpCodes } from 'server/utils/constants'
const ATTRIBUTES_EDITABLE = ['NAME', 'STATE', 'LCM_STATE']
/**
* @param {string} type - Name of redux action
* @param {Promise} service - Request from service
* @param {Function} [wrapResult] - Function to wrapping the response
* @returns {AsyncThunkAction} Asynchronous redux action
*/
export const createAction = (type, service, wrapResult) =>
createAsyncThunk(type, async (payload, { dispatch, getState, rejectWithValue }) => {
try {
@ -32,7 +38,7 @@ export const createAction = (type, service, wrapResult) =>
filter: filterPool
})
return wrapResult ? wrapResult(response, one) : response
return wrapResult?.(response, one) ?? response
} catch (error) {
const { message, data, status, statusText } = error
@ -44,20 +50,9 @@ export const createAction = (type, service, wrapResult) =>
condition: (_, { getState }) => !getState().one.requests[type]
})
export const poolRequest = async (data = {}, command, element) => {
const { filter, end, start } = data
const { url, options } = requestParams({ filter, end, start }, command)
const response = await RestClient.get(url, { ...options })
if (!response?.id || response?.id !== httpCodes.ok.id) throw response
return [response?.data?.[`${element}_POOL`]?.[element] ?? []].flat()
}
/**
* @param {Object} currentList Current list of resources from redux
* @param {Object} value OpenNebula resource
* @param {object} currentList - Current list of resources from redux
* @param {object} value - OpenNebula resource
* @returns {Array} Returns a new list with the attributes editable modified
*/
export const updateResourceList = (currentList, value) => {

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
/* eslint-disable jsdoc/require-jsdoc */
import { useCallback } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { unwrapResult } from '@reduxjs/toolkit'

View File

@ -15,49 +15,114 @@
* ------------------------------------------------------------------------- */
import { Actions, Commands } from 'server/utils/constants/commands/vm'
import { httpCodes } from 'server/utils/constants'
import { requestParams, RestClient } from 'client/utils'
import { poolRequest } from 'client/features/One/utils'
import { requestConfig, RestClient } from 'client/utils'
export const vmService = ({
getVm: async ({ filter, id }) => {
/**
* Retrieves information for the virtual machine.
*
* @param {object} data - Request parameters
* @param {string} data.id - User id
* @returns {object} Get user identified by id
* @throws Fails when response isn't code 200
*/
getVm: async ({ id }) => {
const name = Actions.VM_INFO
const { url, options } = requestParams(
{ filter, id },
{ name, ...Commands[name] }
)
const command = { name, ...Commands[name] }
const config = requestConfig({ id }, command)
const res = await RestClient.get(url, options)
const res = await RestClient.request(config)
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return res?.data?.VM ?? {}
},
getVms: data => {
/**
* Retrieves information for all or part of
* the VMs in the pool.
*
* @param {object} data - Request params
* @param {string} data.filter - Filter flag
* @param {number} data.start - Range start ID
* @param {number} data.end - Range end ID
* @returns {Array} List of VMs
* @throws Fails when response isn't code 200
*/
getVms: async ({ filter, start, end }) => {
const name = Actions.VM_POOL_INFO
const command = { name, ...Commands[name] }
return poolRequest(data, command, 'VM')
const config = requestConfig({ filter, start, end }, command)
const res = await RestClient.request(config)
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return [res?.data?.VM_POOL?.VM ?? []].flat()
},
/**
* Submits an action to be performed on a virtual machine.
*
* @param {object} params - Request parameters
* @param {string} params.id - Virtual machine id
* @param {(
* 'terminate-hard'|
* 'terminate'|
* 'undeploy-hard'|
* 'undeploy'|
* 'poweroff-hard'|
* 'poweroff'|
* 'reboot-hard'|
* 'reboot'|
* 'hold'|
* 'release'|
* 'stop'|
* 'suspend'|
* 'resume'|
* 'resched'|
* 'unresched'
* )} params.action - The action name to be performed
* @returns {Response} Response
* @throws Fails when response isn't code 200
*/
actionVm: async ({ id, action }) => {
const name = Actions.VM_ACTION
const { url, options } = requestParams(
{ id, action },
{ name, ...Commands[name] }
)
const command = { name, ...Commands[name] }
const config = requestConfig({ id, action }, command)
const res = await RestClient.put(url, options?.data)
const res = await RestClient.request(config)
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return res?.data?.VM ?? {}
},
/**
* Changes the permission bits of a virtual machine.
*
* @param {object} params - Request parameters
* @param {string} params.id - Virtual machine id
* @param {{
* ownerUse: number,
* ownerManage: number,
* ownerAdmin: number,
* groupUse: number,
* groupManage: number,
* groupAdmin: number,
* otherUse: number,
* otherManage: number,
* otherAdmin: number
* }} params.data - Permissions data
* @returns {Response} Response
* @throws Fails when response isn't code 200
*/
changePermissions: async ({ id, data }) => {
const name = Actions.VM_CHMOD
const { url, options } = requestParams(
{ id, ...data },
{ name, ...Commands[name] }
)
const command = { name, ...Commands[name] }
const config = requestConfig({ id, data }, command)
const res = await RestClient.put(url, options?.data)
const res = await RestClient.request(config)
if (!res?.id || res?.id !== httpCodes.ok.id) throw res?.data

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
/* eslint-disable jsdoc/require-jsdoc */
import { useCallback } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { unwrapResult } from '@reduxjs/toolkit'

View File

@ -15,26 +15,49 @@
* ------------------------------------------------------------------------- */
import { Actions, Commands } from 'server/utils/constants/commands/template'
import { httpCodes } from 'server/utils/constants'
import { requestParams, RestClient } from 'client/utils'
import { poolRequest } from 'client/features/One/utils'
import { requestConfig, RestClient } from 'client/utils'
export const vmTemplateService = ({
getVmTemplate: ({ filter, id }) => {
/**
* Retrieves information for the vm template.
*
* @param {object} data - Request parameters
* @param {string} data.id - Template id
* @returns {object} Get template identified by id
* @throws Fails when response isn't code 200
*/
getVmTemplate: async ({ id }) => {
const name = Actions.TEMPLATE_INFO
const { url, options } = requestParams(
{ filter, id },
{ name, ...Commands[name] }
)
const command = { name, ...Commands[name] }
const config = requestConfig({ id }, command)
return RestClient.get(url, options).then(res => {
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
const res = await RestClient.request(config)
return res?.data?.VMTEMPLATE ?? {}
})
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return res?.data?.VMTEMPLATE ?? {}
},
getVmTemplates: data => {
/**
* Retrieves information for all or part of
* the virtual machine templates in the pool.
*
* @param {object} data - Request params
* @param {string} data.filter - Filter flag
* @param {number} data.start - Range start ID
* @param {number} data.end - Range end ID
* @returns {Array} List of marketplace apps
* @throws Fails when response isn't code 200
*/
getVmTemplates: async ({ filter, start, end }) => {
const name = Actions.TEMPLATE_POOL_INFO
const command = { name, ...Commands[name] }
return poolRequest(data, command, 'VMTEMPLATE')
const config = requestConfig({ filter, start, end }, command)
const res = await RestClient.request(config)
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return [res?.data?.VMTEMPLATE_POOL?.VMTEMPLATE ?? []].flat()
}
})

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
/* eslint-disable jsdoc/require-jsdoc */
import { useCallback } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { unwrapResult } from '@reduxjs/toolkit'

View File

@ -15,26 +15,49 @@
* ------------------------------------------------------------------------- */
import { Actions, Commands } from 'server/utils/constants/commands/vn'
import { httpCodes } from 'server/utils/constants'
import { requestParams, RestClient } from 'client/utils'
import { poolRequest } from 'client/features/One/utils'
import { requestConfig, RestClient } from 'client/utils'
export const vNetworkService = ({
getVNetwork: ({ filter, id }) => {
/**
* Retrieves information for the virtual network.
*
* @param {object} data - Request parameters
* @param {string} data.id - Virtual network id
* @returns {object} Get virtual network identified by id
* @throws Fails when response isn't code 200
*/
getVNetwork: async ({ id }) => {
const name = Actions.VN_INFO
const { url, options } = requestParams(
{ filter, id },
{ name, ...Commands[name] }
)
const command = { name, ...Commands[name] }
const config = requestConfig({ id }, command)
return RestClient.get(url, options).then(res => {
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
const res = await RestClient.request(config)
return res?.data?.VNET ?? {}
})
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return res?.data?.VNET ?? {}
},
getVNetworks: data => {
/**
* Retrieves information for all or part of the
* virtual networks in the pool.
*
* @param {object} data - Request params
* @param {string} data.filter - Filter flag
* @param {number} data.start - Range start ID
* @param {number} data.end - Range end ID
* @returns {Array} List of virtual networks
* @throws Fails when response isn't code 200
*/
getVNetworks: async ({ filter, start, end }) => {
const name = Actions.VN_POOL_INFO
const command = { name, ...Commands[name] }
return poolRequest(data, command, 'VNET')
const config = requestConfig({ filter, start, end }, command)
const res = await RestClient.request(config)
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return [res?.data?.VNET_POOL?.VNET ?? []].flat()
}
})

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
/* eslint-disable jsdoc/require-jsdoc */
import { useCallback } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { unwrapResult } from '@reduxjs/toolkit'

View File

@ -15,26 +15,49 @@
* ------------------------------------------------------------------------- */
import { Actions, Commands } from 'server/utils/constants/commands/vntemplate'
import { httpCodes } from 'server/utils/constants'
import { requestParams, RestClient } from 'client/utils'
import { poolRequest } from 'client/features/One/utils'
import { requestConfig, RestClient } from 'client/utils'
export const vNetworkTemplateService = ({
getVNetworkTemplate: ({ filter, id }) => {
/**
* Retrieves information for the virtual network template.
*
* @param {object} data - Request parameters
* @param {string} data.id - Virtual Network Template id
* @returns {object} Get virtual network template identified by id
* @throws Fails when response isn't code 200
*/
getVNetworkTemplate: async ({ id }) => {
const name = Actions.VNTEMPLATE_INFO
const { url, options } = requestParams(
{ filter, id },
{ name, ...Commands[name] }
)
const command = { name, ...Commands[name] }
const config = requestConfig({ id }, command)
return RestClient.get(url, options).then(res => {
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
const res = await RestClient.request(config)
return res?.data?.VNTEMPLATE ?? {}
})
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return res?.data?.VNTEMPLATE ?? {}
},
getVNetworkTemplates: data => {
/**
* Retrieves information for all or part of th
* virtual network templates in the pool.
*
* @param {object} data - Request params
* @param {string} data.filter - Filter flag
* @param {number} data.start - Range start ID
* @param {number} data.end - Range end ID
* @returns {Array} List of virtual network templates
* @throws Fails when response isn't code 200
*/
getVNetworkTemplates: async ({ filter, start, end }) => {
const name = Actions.VNTEMPLATE_POOL_INFO
const command = { name, ...Commands[name] }
return poolRequest(data, command, 'VNTEMPLATE')
const config = requestConfig({ filter, start, end }, command)
const res = await RestClient.request(config)
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return [res?.data?.VNTEMPLATE_POOL?.VNTEMPLATE ?? []].flat()
}
})

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
/* eslint-disable jsdoc/require-jsdoc */
import { useCallback } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { unwrapResult } from '@reduxjs/toolkit'

View File

@ -15,26 +15,49 @@
* ------------------------------------------------------------------------- */
import { Actions, Commands } from 'server/utils/constants/commands/vrouter'
import { httpCodes } from 'server/utils/constants'
import { requestParams, RestClient } from 'client/utils'
import { poolRequest } from 'client/features/One/utils'
import { requestConfig, RestClient } from 'client/utils'
export const vRouterService = ({
getVRouter: ({ filter, id }) => {
/**
* Retrieves information for the virtual router.
*
* @param {object} data - Request parameters
* @param {string} data.id - Virtual router id
* @returns {object} Get virtual router identified by id
* @throws Fails when response isn't code 200
*/
getVRouter: async ({ id }) => {
const name = Actions.VROUTER_INFO
const { url, options } = requestParams(
{ filter, id },
{ name, ...Commands[name] }
)
const command = { name, ...Commands[name] }
const config = requestConfig({ id }, command)
return RestClient.get(url, options).then(res => {
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
const res = await RestClient.request(config)
return res?.data?.VROUTER ?? {}
})
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return res?.data?.VROUTER ?? {}
},
getVRouters: data => {
/**
* Retrieves information for all or part of the
* virtual routers in the pool.
*
* @param {object} data - Request params
* @param {string} data.filter - Filter flag
* @param {number} data.start - Range start ID
* @param {number} data.end - Range end ID
* @returns {Array} List of virtual routers
* @throws Fails when response isn't code 200
*/
getVRouters: async ({ filter, start, end }) => {
const name = Actions.VROUTER_POOL_INFO
const command = { name, ...Commands[name] }
return poolRequest(data, command, 'VROUTER')
const config = requestConfig({ filter, start, end }, command)
const res = await RestClient.request(config)
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return [res?.data?.VROUTER_POOL?.VROUTER ?? []].flat()
}
})

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
/* eslint-disable jsdoc/require-jsdoc */
import { useCallback } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { unwrapResult } from '@reduxjs/toolkit'

View File

@ -15,26 +15,44 @@
* ------------------------------------------------------------------------- */
import { Actions, Commands } from 'server/utils/constants/commands/zone'
import { httpCodes } from 'server/utils/constants'
import { requestParams, RestClient } from 'client/utils'
import { poolRequest } from 'client/features/One/utils'
import { requestConfig, RestClient } from 'client/utils'
export const zoneService = ({
getZone: ({ filter, id }) => {
/**
* Retrieves information for the zone.
*
* @param {object} data - Request parameters
* @param {string} data.id - Zone id
* @returns {object} Get zone identified by id
* @throws Fails when response isn't code 200
*/
getZone: async ({ id }) => {
const name = Actions.ZONE_INFO
const { url, options } = requestParams(
{ filter, id },
{ name, ...Commands[name] }
)
const command = { name, ...Commands[name] }
const config = requestConfig({ id }, command)
return RestClient.get(url, options).then(res => {
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
const res = await RestClient.request(config)
return res?.data?.ZONE ?? {}
})
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return res?.data?.ZONE ?? {}
},
getZones: data => {
/**
* Retrieves information for all the zones in the pool.
*
* @returns {Array} List of zone
* @throws Fails when response isn't code 200
*/
getZones: async () => {
const name = Actions.ZONE_POOL_INFO
const command = { name, ...Commands[name] }
return poolRequest(data, command, 'ZONE')
const config = requestConfig(undefined, command)
const res = await RestClient.request(config)
if (!res?.id || res?.id !== httpCodes.ok.id) throw res
return [res?.data?.ZONE_POOL?.ZONE ?? []].flat()
}
})

View File

@ -36,15 +36,15 @@ const NIC_ALIAS_IP_ATTRS = [
]
/**
* @param {Array} vms List of virtual machines
* @param {Array} vms - List of virtual machines
* @returns {Array} Clean list of vms with done state
*/
export const filterDoneVms = (vms = []) =>
vms.filter(({ STATE }) => VM_STATES[STATE]?.name !== STATES.DONE)
/**
* @param {Object} vm Virtual machine
* @returns {Object} Last history record from resource
* @param {object} vm - Virtual machine
* @returns {object} Last history record from resource
*/
export const getLastHistory = vm => {
const history = vm?.HISTORY_RECORDS?.HISTORY ?? {}
@ -53,28 +53,27 @@ export const getLastHistory = vm => {
}
/**
* @param {Object} vm Virtual machine
* @returns {String} Resource type: VR, FLOW or VM
* @param {object} vm - Virtual machine
* @returns {string} Resource type: VR, FLOW or VM
*/
export const getType = vm => vm.TEMPLATE?.VROUTER_ID
? 'VR' : vm?.USER_TEMPLATE?.USER_TEMPLATE?.SERVICE_ID ? 'FLOW' : 'VM'
/**
* @param {Object} vm Virtual machine
* @returns {String} Resource hypervisor
* @param {object} vm - Virtual machine
* @returns {string} Resource hypervisor
*/
export const getHypervisor = vm => String(getLastHistory(vm)?.VM_MAD).toLowerCase()
/**
* @param {Object} vm Virtual machine
* @returns {Boolean} If the hypervisor is vCenter
* @param {object} vm - Virtual machine
* @returns {boolean} If the hypervisor is vCenter
*/
export const isVCenter = vm => getHypervisor(vm) === 'vcenter'
/**
* @type {{color: string, name: string, meaning: string}} StateInfo
*
* @param {Object} vm Virtual machine
* @param {object} vm - Virtual machine
* @returns {StateInfo} State information from resource
*/
export const getState = ({ STATE, LCM_STATE } = {}) => {
@ -84,7 +83,7 @@ export const getState = ({ STATE, LCM_STATE } = {}) => {
}
/**
* @param {Object} vm Virtual machine
* @param {object} vm - Virtual machine
* @returns {Array} List of disks from resource
*/
export const getDisks = vm => {
@ -119,8 +118,9 @@ export const getDisks = vm => {
}
/**
* @param {Object} vm Virtual machine
* @param {Boolean} [options.groupAlias] Map ALIAS_IDS attribute with NIC_ALIAS
* @param {object} vm - Virtual machine
* @param {object} [options] - Options
* @param {boolean} [options.groupAlias] - Map ALIAS_IDS attribute with NIC_ALIAS
* @returns {Array} List of nics from resource
*/
export const getNics = (vm, options = {}) => {
@ -145,7 +145,7 @@ export const getNics = (vm, options = {}) => {
}
/**
* @param {Object} vm Virtual machine
* @param {object} vm - Virtual machine
* @returns {Array} List of ips from resource
*/
export const getIps = vm => {
@ -155,7 +155,7 @@ export const getIps = vm => {
}
/**
* @param {Object} vm Virtual machine
* @param {object} vm - Virtual machine
* @returns {{ nics: Array, alias: Array }} Lists of nics and alias from resource
*/
export const splitNicAlias = vm =>

View File

@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
/* eslint-disable jsdoc/require-jsdoc */
import React, { createContext, useEffect, useState } from 'react'
import PropTypes from 'prop-types'
@ -45,7 +46,7 @@ const SocketProvider = ({ children }) => {
setSocket(client)
client.on(SOCKETS.PROVISION, data => {
dispatch(sockets.socketCreateProvision(data))
dispatch(sockets.onCreateProvision(data))
})
return () => {

View File

@ -13,11 +13,12 @@
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
import { JWT_NAME } from 'client/constants'
import { removeStoreData } from 'client/utils'
import { from as resourceFrom } from 'server/utils/constants/defaults'
import { AxiosRequestConfig, Method } from 'axios'
import { defaults } from 'server/utils/constants'
export const getQueries = params =>
const { from: resourceFrom } = defaults
const getQueries = params =>
Object.entries(params)
?.filter(
([, { from, value }]) =>
@ -26,30 +27,38 @@ export const getQueries = params =>
?.map(([name, { value }]) => `${name}=${encodeURI(value)}`)
?.join('&')
export const getResources = params =>
const getResources = params =>
Object.values(params)
?.filter(({ from }) => from === resourceFrom.resource)
?.map(({ value }) => value)
?.join('/')
export const getDataBody = params =>
const getDataBody = params =>
Object.entries(params)
?.filter(([, { from }]) => from === resourceFrom.postBody)
?.reduce((acc, [name, { value }]) => ({ ...acc, [name]: value }), {})
export const requestParams = (data, command) => {
/**
* @param {object} data - Data for the request
* @param {object} command - Command request
* @param {object} command.name - Command name
* @param {Method} command.httpMethod - Method http
* @param {object} command.params - Params to map
* @returns {AxiosRequestConfig} Request configuration
*/
export const requestConfig = (data, command) => {
if (command === undefined) throw new Error('command not exists')
const { name, httpMethod, params } = command
const { name, httpMethod, params = {} } = command
/* Spread 'from' values in current params */
const mappedParams =
Object.entries(params)?.reduce(
(acc, [param, { from }]) => ({
(acc, [paraName, { from }]) => ({
...acc,
[param]: { from, value: data[param] }
[paraName]: { from, value: data[paraName] }
}),
{}
) ?? {}
)
const queries = getQueries(mappedParams)
const resources = getResources(mappedParams)
@ -59,14 +68,7 @@ export const requestParams = (data, command) => {
return {
url: `${url}/${resources}?${queries}`,
options: {
data: body,
method: httpMethod,
authenticate: true,
error: err => {
removeStoreData(JWT_NAME)
return err?.message
}
}
data: body,
method: httpMethod
}
}

View File

@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and *
* limitations under the License. *
* ------------------------------------------------------------------------- */
import axios from 'axios'
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import { httpCodes } from 'server/utils/constants'
import { messageTerminal } from 'server/utils/general'
@ -29,6 +29,10 @@ http.interceptors.request.use(config => {
return {
...config,
headers: {
...config.headers,
'Content-Type': 'application/json'
},
timeout: 45_000,
timeoutErrorMessage: T.Timeout,
withCredentials: true,
@ -61,45 +65,9 @@ http.interceptors.response.use(
)
export const RestClient = {
get: (url, options) => {
const headers = {
credentials: 'include'
}
return http.get(url, { headers, ...options })
},
post: (url, body, options) => {
const headers = {
'Content-Type': 'application/json'
}
if (options && typeof options.headers === 'object') {
Object.assign(headers, options.headers)
}
return http.post(url, body, { headers })
},
put: (url, body, options) => {
const headers = {
'Content-Type': 'application/json'
}
if (options && typeof options.headers === 'object') {
Object.assign(headers, options.headers)
}
return http.put(url, body, { headers })
},
delete: (url, options) => {
const headers = {}
if (options && typeof options.headers === 'object') {
Object.assign(headers, options.headers)
}
return http.delete(url, { headers })
}
/**
* @param {AxiosRequestConfig} options - Request configuration
* @returns {AxiosResponse} Response from server
*/
request: options => http.request(options)
}