First Committ
This commit is contained in:
16
src/store/Api/ApiRoutes.ts
Executable file
16
src/store/Api/ApiRoutes.ts
Executable file
@@ -0,0 +1,16 @@
|
||||
const ServerRoutes = {
|
||||
LOGIN: 'login_check',
|
||||
TOKEN_REFRESH: 'token/refresh',
|
||||
SIGNUP: 'register/',
|
||||
MOVING_LIST: 'announcements',
|
||||
MOVING_DETAIL: 'announcement/',
|
||||
MOVING_CREATE: 'announcement',
|
||||
MOVING_USER_INFOS: 'user/verify',
|
||||
PARTICIPATION_CREATE: 'participations',
|
||||
CREATE_NOTE: 'note_user',
|
||||
MOVERS_LIST: 'movers',
|
||||
NEW_MOVER: 'mover',
|
||||
USERS: 'users',
|
||||
}
|
||||
|
||||
export default ServerRoutes
|
||||
142
src/store/Api/ApiTypes.ts
Executable file
142
src/store/Api/ApiTypes.ts
Executable file
@@ -0,0 +1,142 @@
|
||||
// import { NotificationsStore, LoginStore } from '@store'
|
||||
|
||||
export class AxiosSuccess {
|
||||
public success: any = true
|
||||
|
||||
public status: number
|
||||
|
||||
public data: any
|
||||
|
||||
constructor(data: any, status: number) {
|
||||
this.data = data
|
||||
this.status = status
|
||||
}
|
||||
}
|
||||
|
||||
export class AxiosError {
|
||||
public success: boolean = false
|
||||
|
||||
public status: number = 0
|
||||
|
||||
public data: any
|
||||
|
||||
public code: any = 0
|
||||
|
||||
public msgerr: string = ''
|
||||
|
||||
constructor(status: number, data?: any, code?: any, msgerr: string = '') {
|
||||
this.status = status
|
||||
this.data = data
|
||||
this.code = code
|
||||
this.msgerr = msgerr
|
||||
if (status !== 401) {
|
||||
// if (status == 0) message = 'Vérifiez votre connexion Internet';
|
||||
// NotificationsStore.actions.addNotification({ type: 'warning', message: message })
|
||||
} else if (data.error && data.error.message !== 'Bad credentials') {
|
||||
// LoginStore.actions.disconnectRequest()
|
||||
}
|
||||
}
|
||||
|
||||
public getMsgError() {
|
||||
if (this.data && this.data.error) return this.data.error.message
|
||||
|
||||
return this.msgerr
|
||||
}
|
||||
|
||||
public getMsg() {
|
||||
try {
|
||||
if (this.code === 0) {
|
||||
if (this.data.code) {
|
||||
return this.data.msg
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
return ''
|
||||
}
|
||||
|
||||
return ''
|
||||
}
|
||||
|
||||
public getCode() {
|
||||
if (this.code === 0) {
|
||||
if (this.data.code) {
|
||||
return this.data.code
|
||||
}
|
||||
}
|
||||
|
||||
return this.code
|
||||
}
|
||||
}
|
||||
|
||||
// export class ApiResponse {
|
||||
// public success: boolean = true;
|
||||
// public message?: string;
|
||||
// public data?: any;
|
||||
// public type: string;
|
||||
// constructor(fields: {message?: string, data?: any, type: any, success: boolean}) {
|
||||
// this.message = fields.message;
|
||||
// this.type = fields.type;
|
||||
// this.data = fields.data ? fields.data : {};
|
||||
// this.success = fields.success;
|
||||
// }
|
||||
|
||||
// yes() {
|
||||
// return Promise.resolve(this);
|
||||
// }
|
||||
// }
|
||||
|
||||
export interface IApiResponse {
|
||||
success: boolean
|
||||
message?: string
|
||||
data?: any
|
||||
type: string
|
||||
}
|
||||
|
||||
export class ApiResponse {
|
||||
public data?: any
|
||||
|
||||
public message?: any
|
||||
|
||||
constructor(fields: { message?: string, data?: any, type: any, success: boolean }) {
|
||||
const returnData: any = {}
|
||||
returnData.message = fields.message
|
||||
returnData.type = fields.type
|
||||
returnData.data = fields.data != null ? fields.data : {}
|
||||
returnData.success = fields.success
|
||||
if (fields.success) return <any>Promise.resolve(returnData)
|
||||
return <any>Promise.reject(returnData)
|
||||
}
|
||||
}
|
||||
|
||||
export class ApiSuccess extends ApiResponse {
|
||||
constructor(fields: { message?: string, data?: any } = {}) {
|
||||
super({
|
||||
success: true,
|
||||
type: 'success',
|
||||
message: fields.message,
|
||||
data: fields.data,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export class ApiError extends ApiResponse {
|
||||
constructor(fields: { message?: string, data?: any } = {}) {
|
||||
super({
|
||||
success: false,
|
||||
type: 'error',
|
||||
message: fields.message,
|
||||
data: fields.data,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export class ApiWarning extends ApiResponse {
|
||||
constructor(fields: { message?: string, data?: any } = {}) {
|
||||
super({
|
||||
success: false,
|
||||
type: 'warning',
|
||||
message: fields.message,
|
||||
data: fields.data,
|
||||
})
|
||||
}
|
||||
}
|
||||
22
src/store/Api/Inst-Pao.ts
Executable file
22
src/store/Api/Inst-Pao.ts
Executable file
@@ -0,0 +1,22 @@
|
||||
import axios, {
|
||||
AxiosInstance, AxiosPromise, AxiosResponse, AxiosInterceptorManager,
|
||||
} from 'axios'
|
||||
import Api from '@api'
|
||||
import * as Types from '@src/store/Api/ApiTypes'
|
||||
|
||||
async function sendRequest(url: string, method: string, mydata: any) {
|
||||
if (!process.env.DEBUG) console.log('sendRequest', method, url)
|
||||
|
||||
let request
|
||||
if (method === 'GET') request = Api.get(url, mydata)
|
||||
else if (method === 'POST') request = Api.post(url, mydata)
|
||||
else if (method === 'DELETE') request = Api.Delete(url, mydata)
|
||||
else if (method === 'PUT') request = Api.put(url, mydata)
|
||||
else if (method === 'PATCH') request = Api.patch(url, mydata)
|
||||
|
||||
// @ts-ignore
|
||||
const req: Promise<Types.AxiosSuccess | Types.AxiosError> = request
|
||||
return req
|
||||
}
|
||||
|
||||
export default sendRequest
|
||||
157
src/store/Api/Instance.ts
Executable file
157
src/store/Api/Instance.ts
Executable file
@@ -0,0 +1,157 @@
|
||||
import axios, { AxiosInstance, AxiosResponse } from 'axios'
|
||||
// import LoginModule from '../Modules/Auth/LoginStore'
|
||||
import router from '@router'
|
||||
import { tools } from '@src/store/Modules/tools'
|
||||
import { toolsext } from '@src/store/Modules/toolsext'
|
||||
import { serv_constants } from '@src/store/Modules/serv_constants'
|
||||
import { useGlobalStore } from '@store/globalStore'
|
||||
import { useUserStore } from '@store/UserStore'
|
||||
import * as Types from './ApiTypes'
|
||||
|
||||
export const API_URL = process.env.MONGODB_HOST
|
||||
export const axiosInstance: AxiosInstance = axios.create({
|
||||
baseURL: API_URL,
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
},
|
||||
})
|
||||
|
||||
axiosInstance.interceptors.response.use(
|
||||
|
||||
(response) => {
|
||||
if (process.env.DEBUG === '1') console.log(response)
|
||||
return response
|
||||
},
|
||||
(error) => {
|
||||
const globalStore = useGlobalStore()
|
||||
// console.log('error', error)
|
||||
if (error.response) {
|
||||
if (process.env.DEBUG === '1') console.log('Status = ', error.response.status)
|
||||
console.log('Request Error: ', error.response)
|
||||
if (error.response.status !== 0) {
|
||||
globalStore.setStateConnection('online')
|
||||
} else {
|
||||
globalStore.setStateConnection('offline')
|
||||
}
|
||||
} else {
|
||||
globalStore.setStateConnection('offline')
|
||||
}
|
||||
return Promise.reject(error)
|
||||
},
|
||||
)
|
||||
|
||||
export const addAuthHeaders = () => {
|
||||
// axiosInstance.defaults.headers.Authorization = `Bearer ${LoginModule.userInfos.userToken}`
|
||||
}
|
||||
|
||||
export const removeAuthHeaders = () => {
|
||||
delete axiosInstance.defaults.headers.Authorization
|
||||
}
|
||||
|
||||
async function Request(type: string, path: string, payload: any): Promise<Types.AxiosSuccess | Types.AxiosError | undefined> {
|
||||
let ricevuto = false
|
||||
const userStore = useUserStore()
|
||||
const globalStore = useGlobalStore()
|
||||
try {
|
||||
if (tools.isDebug()) console.log('Axios Request', path, type, tools.notshowPwd(payload))
|
||||
let response: AxiosResponse
|
||||
if (type === 'post' || type === 'put' || type === 'patch') {
|
||||
response = await axiosInstance[type](path, payload, {
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'x-auth': userStore.x_auth_token,
|
||||
},
|
||||
})
|
||||
ricevuto = true
|
||||
// console.log('Request Response: ', response)
|
||||
// console.log(new Types.AxiosSuccess(response.data, response.status))
|
||||
|
||||
const setAuthToken = (path === '/updatepwd')
|
||||
|
||||
// console.log('--------- 0 ')
|
||||
|
||||
if (response && (response.status === 200)) {
|
||||
let x_auth_token = ''
|
||||
try {
|
||||
if (setAuthToken || (path === '/users/login')) {
|
||||
x_auth_token = String(response.headers['x-auth'])
|
||||
|
||||
if (x_auth_token === '') {
|
||||
userStore.setServerCode(toolsext.ERR_AUTHENTICATION)
|
||||
}
|
||||
if (setAuthToken) {
|
||||
userStore.UpdatePwd(x_auth_token)
|
||||
localStorage.setItem(toolsext.localStorage.token, x_auth_token)
|
||||
}
|
||||
|
||||
userStore.setAuth(x_auth_token)
|
||||
localStorage.setItem(toolsext.localStorage.token, x_auth_token)
|
||||
}
|
||||
|
||||
globalStore.setStateConnection(ricevuto ? 'online' : 'offline')
|
||||
userStore.setServerCode(tools.OK)
|
||||
} catch (e) {
|
||||
if (setAuthToken) {
|
||||
userStore.setServerCode(toolsext.ERR_AUTHENTICATION)
|
||||
userStore.setAuth('')
|
||||
}
|
||||
globalStore.setStateConnection(ricevuto ? 'online' : 'offline')
|
||||
return Promise.reject(new Types.AxiosError(serv_constants.RIS_CODE__HTTP_FORBIDDEN_INVALID_TOKEN, null, toolsext.ERR_AUTHENTICATION))
|
||||
}
|
||||
}
|
||||
|
||||
return new Types.AxiosSuccess(response.data, response.status)
|
||||
} if (type === 'get' || type === 'delete') {
|
||||
// @ts-ignore
|
||||
response = await axiosInstance[type](path, {
|
||||
params: payload,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'x-auth': userStore.x_auth_token,
|
||||
},
|
||||
})
|
||||
ricevuto = true
|
||||
return new Types.AxiosSuccess(response.data, response.status)
|
||||
} if (type === 'postFormData') {
|
||||
response = await axiosInstance.post(path, payload, {
|
||||
headers: {
|
||||
'Content-Type': 'multipart/form-data',
|
||||
'x-auth': userStore.x_auth_token,
|
||||
},
|
||||
})
|
||||
ricevuto = true
|
||||
return new Types.AxiosSuccess(response.data, response.status)
|
||||
}
|
||||
} catch (error) {
|
||||
setTimeout(() => {
|
||||
globalStore.connData.uploading_server = (globalStore.connData.uploading_server === 1) ? -1 : globalStore.connData.uploading_server
|
||||
globalStore.connData.downloading_server = (globalStore.connData.downloading_server === 1) ? -1 : globalStore.connData.downloading_server
|
||||
}, 1000)
|
||||
|
||||
if (process.env.DEV) {
|
||||
console.log('ERROR using', path)
|
||||
// console.log('Error received: ', error)
|
||||
// console.log('ricevuto=', ricevuto)
|
||||
console.log('error.response=', error.response)
|
||||
}
|
||||
let mycode = 0
|
||||
if (!ricevuto) {
|
||||
mycode = toolsext.ERR_SERVERFETCH
|
||||
userStore.setServerCode(toolsext.ERR_SERVERFETCH)
|
||||
} else {
|
||||
mycode = toolsext.ERR_GENERICO
|
||||
userStore.setServerCode(toolsext.ERR_GENERICO)
|
||||
}
|
||||
|
||||
if (error.response) {
|
||||
if (error.response.data && error.response.data.code) {
|
||||
mycode = error.response.data.code
|
||||
userStore.setServerCode(mycode)
|
||||
}
|
||||
return Promise.reject(new Types.AxiosError(error.response.status, error.response.data, error.response.data.code))
|
||||
}
|
||||
return Promise.reject(new Types.AxiosError(0, null, mycode, error))
|
||||
}
|
||||
}
|
||||
|
||||
export default Request
|
||||
221
src/store/Api/index.ts
Executable file
221
src/store/Api/index.ts
Executable file
@@ -0,0 +1,221 @@
|
||||
import { useRouter } from 'vue-router'
|
||||
import { useGlobalStore } from '@store/globalStore'
|
||||
import { useUserStore } from '@store/UserStore'
|
||||
|
||||
export * from './ApiTypes'
|
||||
import axios from 'axios'
|
||||
|
||||
export { addAuthHeaders, removeAuthHeaders, API_URL } from './Instance'
|
||||
// import {AlgoliaSearch} from './AlgoliaController'
|
||||
import Paths from '@paths'
|
||||
import { tools } from '@src/store/Modules/tools'
|
||||
import { toolsext } from '@src/store/Modules/toolsext'
|
||||
|
||||
import { serv_constants } from '@src/store/Modules/serv_constants'
|
||||
import router from '@router'
|
||||
import * as Types from '@src/store/Api/ApiTypes'
|
||||
import { costanti } from '@src/store/Modules/costanti'
|
||||
import * as ApiTables from '@src/store/Modules/ApiTables'
|
||||
import sendRequest from './Inst-Pao'
|
||||
import Request from './Instance'
|
||||
import globalroutines from '../../globalroutines/index'
|
||||
|
||||
function ReceiveResponsefromServer(tablesync: string, nametab: string, method: string, risdata: any) {
|
||||
// console.log('ReceiveResponsefromServer', nametab, method, risdata)
|
||||
if (risdata) {
|
||||
// Updated somw data after Server arrived data.
|
||||
if (method === 'PATCH') {
|
||||
if (nametab === 'projects') {
|
||||
if (risdata.projectris) {
|
||||
const copyrec = tools.jsonCopy(risdata.projectris)
|
||||
// +*Todo conv: Projects.updateProject({ objproj: copyrec })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// const algoliaApi = new AlgoliaSearch()
|
||||
export namespace ApiTool {
|
||||
export async function post(path: string, payload?: any) {
|
||||
const globalStore = useGlobalStore()
|
||||
globalStore.connData.downloading_server = 1
|
||||
globalStore.connData.uploading_server = 1
|
||||
return Request('post', path, payload)
|
||||
}
|
||||
|
||||
export async function postFormData(path: string, payload?: any) {
|
||||
const globalStore = useGlobalStore()
|
||||
globalStore.connData.uploading_server = 1
|
||||
globalStore.connData.downloading_server = 1
|
||||
return Request('postFormData', path, payload)
|
||||
}
|
||||
|
||||
export async function get(path: string, payload?: any) {
|
||||
const globalStore = useGlobalStore()
|
||||
globalStore.connData.downloading_server = 1
|
||||
globalStore.connData.uploading_server = 0
|
||||
return Request('get', path, payload)
|
||||
}
|
||||
|
||||
export async function put(path: string, payload?: any) {
|
||||
const globalStore = useGlobalStore()
|
||||
globalStore.connData.uploading_server = 1
|
||||
return Request('put', path, payload)
|
||||
}
|
||||
|
||||
export async function patch(path: string, payload?: any) {
|
||||
const globalStore = useGlobalStore()
|
||||
globalStore.connData.uploading_server = 1
|
||||
return Request('patch', path, payload)
|
||||
}
|
||||
|
||||
export async function Delete(path: string, payload: any) {
|
||||
const globalStore = useGlobalStore()
|
||||
globalStore.connData.uploading_server = 1
|
||||
return Request('delete', path, payload)
|
||||
}
|
||||
|
||||
export async function checkSession({ token, refresh_token }: any) {
|
||||
return axios.post(process.env.API_URL + Paths.TOKEN_REFRESH, {
|
||||
refresh_token,
|
||||
}, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export async function SendReq(url: string, method: string, mydata: any, setAuthToken: boolean = false): Promise<Types.AxiosSuccess | Types.AxiosError> {
|
||||
const mydataout = {
|
||||
...mydata,
|
||||
keyappid: process.env.PAO_APP_ID,
|
||||
idapp: process.env.APP_ID,
|
||||
}
|
||||
|
||||
// console.log('mydata', mydata)
|
||||
|
||||
const userStore = useUserStore()
|
||||
const globalStore = useGlobalStore()
|
||||
const $router = useRouter()
|
||||
|
||||
userStore.setServerCode(tools.EMPTY)
|
||||
userStore.setResStatus(0)
|
||||
return new Promise((resolve, reject) => sendRequest(url, method, mydataout)
|
||||
.then((res) => {
|
||||
// console.log('res', res)
|
||||
|
||||
setTimeout(() => {
|
||||
if (method === 'get') {
|
||||
globalStore.connData.downloading_server = 0
|
||||
} else {
|
||||
globalStore.connData.uploading_server = 0
|
||||
globalStore.connData.downloading_server = 0
|
||||
}
|
||||
}, 1000)
|
||||
|
||||
if (res.status) {
|
||||
userStore.setResStatus(res.status)
|
||||
if (res.status === serv_constants.RIS_CODE__HTTP_FORBIDDEN_INVALID_TOKEN) {
|
||||
// Forbidden
|
||||
// You probably is connectiong with other page...
|
||||
userStore.setServerCode(toolsext.ERR_AUTHENTICATION)
|
||||
userStore.setAuth('')
|
||||
$router.push('/signin')
|
||||
return reject({ code: toolsext.ERR_AUTHENTICATION })
|
||||
}
|
||||
}
|
||||
|
||||
return resolve(res)
|
||||
})
|
||||
.catch((error) => {
|
||||
setTimeout(() => {
|
||||
if (method === 'get') {
|
||||
globalStore.connData.downloading_server = -1
|
||||
} else {
|
||||
globalStore.connData.uploading_server = -1
|
||||
globalStore.connData.downloading_server = -1
|
||||
}
|
||||
}, 1000)
|
||||
|
||||
console.log('error', error)
|
||||
return reject(error)
|
||||
}))
|
||||
}
|
||||
|
||||
export async function syncAlternative(mystrparam: string) {
|
||||
// console.log('[ALTERNATIVE Background syncing', mystrparam)
|
||||
|
||||
const multiparams = mystrparam.split('|')
|
||||
if (multiparams) {
|
||||
if (multiparams.length > 3) {
|
||||
const cmd = multiparams[0]
|
||||
const tablesync = multiparams[1]
|
||||
const nametab = multiparams[2]
|
||||
const method = multiparams[3]
|
||||
// const token = multiparams[3]
|
||||
|
||||
if (cmd === ApiTables.DB.CMD_SYNC) {
|
||||
let errorfromserver = false
|
||||
let lettoqualcosa = false
|
||||
|
||||
// console.log('A1) INIZIO.............................................................')
|
||||
return globalroutines(null, 'readall', tablesync, null)
|
||||
.then((alldata) => {
|
||||
if (alldata === undefined) {
|
||||
console.log('alldata NON DEFINITA')
|
||||
return true
|
||||
}
|
||||
const myrecs = [...alldata]
|
||||
|
||||
const promises = myrecs.map((rec) => {
|
||||
let link = `/${ApiTables.getLinkByTableName(nametab)}`
|
||||
|
||||
if (method !== 'POST') {
|
||||
link += `/${rec._id}`
|
||||
}
|
||||
|
||||
console.log('----------------------- LEGGO QUALCOSA ', link)
|
||||
|
||||
// Insert/Delete/Update table to the server
|
||||
return SendReq(link, method, rec)
|
||||
.then((ris) => {
|
||||
ReceiveResponsefromServer(tablesync, nametab, method, ris.data)
|
||||
lettoqualcosa = true
|
||||
return globalroutines(null, 'delete', tablesync, null, rec._id)
|
||||
})
|
||||
.then(() => {
|
||||
return globalroutines(null, 'delete', 'swmsg', null, mystrparam)
|
||||
}).catch((err) => {
|
||||
if (err.msgerr) {
|
||||
if (err.msgerr.message.includes('Failed to fetch') || err.msgerr.message.includes('Network Error')) {
|
||||
errorfromserver = true
|
||||
}
|
||||
}
|
||||
console.log(' [Alternative] !!!!!!!!!!!!!!! Error while sending data', err, errorfromserver, 'lettoqualcosa', lettoqualcosa)
|
||||
if (!errorfromserver) {
|
||||
return globalroutines(null, 'delete', 'swmsg', null, mystrparam)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
// CALL ALL THE PROMISES
|
||||
return Promise.all(promises).then(() => (errorfromserver && !lettoqualcosa)).catch((err) => (errorfromserver && !lettoqualcosa))
|
||||
}).catch((error) => {
|
||||
console.log('¨¨¨¨¨¨¨¨¨¨¨¨¨¨ errorfromserver:', errorfromserver, error)
|
||||
return (errorfromserver && !lettoqualcosa)
|
||||
})
|
||||
.then((error) => {
|
||||
const mystate = (error || errorfromserver) ? 'offline' : 'online'
|
||||
|
||||
const globalStore = useGlobalStore()
|
||||
globalStore.setStateConnection(mystate)
|
||||
globalStore.saveConfig({ _id: costanti.CONFIG_ID_STATE_CONN, value: mystate })
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
}
|
||||
export default ApiTool
|
||||
Reference in New Issue
Block a user