Added Axios and removed fetch...

Axios has CSXF integrated.
This commit is contained in:
Paolo Arena
2019-02-19 02:33:02 +01:00
parent ee6cf47c29
commit ec49343556
15 changed files with 204 additions and 236 deletions

View File

@@ -53,7 +53,10 @@ export default class App extends Vue {
.then((loadstorage) => { .then((loadstorage) => {
if (loadstorage) { if (loadstorage) {
this.$i18n.locale = UserStore.state.lang // Set Lang if (UserStore.state.lang !== null) {
console.log('SETLOCALE :', this.$i18n.locale)
this.$i18n.locale = UserStore.state.lang // Set Lang
}
console.log('lang CARICATO:', this.$i18n.locale) console.log('lang CARICATO:', this.$i18n.locale)
globalroutines(this, 'loadapp', '') globalroutines(this, 'loadapp', '')

View File

@@ -166,7 +166,7 @@
{ label: 'English', icon: 'fa-flag-us', value: 'enUs', image: '../statics/images/gb.png', short: 'EN' }, { label: 'English', icon: 'fa-flag-us', value: 'enUs', image: '../statics/images/gb.png', short: 'EN' },
{ label: 'German', icon: 'fa-flag-de', value: 'de', image: '../statics/images/de.png', short: 'DE' }, { label: 'German', icon: 'fa-flag-de', value: 'de', image: '../statics/images/de.png', short: 'DE' },
{ label: 'Italian', icon: 'fa-facebook', value: 'it', image: '../statics/images/it.png', short: 'IT' }, { label: 'Italian', icon: 'fa-facebook', value: 'it', image: '../statics/images/it.png', short: 'IT' },
{ label: 'Spanish', icon: 'fa-flag-es', value: 'es', image: '../statics/images/es.png', short: 'SP' } { label: 'Spanish', icon: 'fa-flag-es', value: 'esEs', image: '../statics/images/es.png', short: 'ES' }
] ]
get leftDrawerOpen() { get leftDrawerOpen() {
@@ -200,6 +200,7 @@
} }
set lang(lang) { set lang(lang) {
console.log('set lang(' + this.$i18n.locale)
this.$i18n.locale = this.snakeToCamel(lang) this.$i18n.locale = this.snakeToCamel(lang)
// this.$q.notify('IMPOSTA LANG= ' + this.$i18n.locale) // this.$q.notify('IMPOSTA LANG= ' + this.$i18n.locale)
// console.log('IMPOSTA LANG= ' + this.$i18n.locale) // console.log('IMPOSTA LANG= ' + this.$i18n.locale)
@@ -213,6 +214,9 @@
if (mylangtopass === 'enUs') if (mylangtopass === 'enUs')
mylangtopass = 'en-us' mylangtopass = 'en-us'
if (mylangtopass === 'esEs')
mylangtopass = 'es'
// dynamic import, so loading on demand only // dynamic import, so loading on demand only
import(`quasar-framework/i18n/${mylangtopass}`).then(lang => { import(`quasar-framework/i18n/${mylangtopass}`).then(lang => {
this.$q.i18n.set(lang.default) this.$q.i18n.set(lang.default)
@@ -226,6 +230,7 @@
} }
setLangAtt(mylang) { setLangAtt(mylang) {
console.log('MYLL=', mylang)
this.$q.i18n.lang = mylang this.$q.i18n.lang = mylang
} }
@@ -236,10 +241,25 @@
// this.$q.notify('prima: ' + String(my)) // this.$q.notify('prima: ' + String(my))
let mylang = localStorage.getItem(rescodes.localStorage.lang) let mylang = localStorage.getItem(rescodes.localStorage.lang)
if (mylang.toLowerCase() === 'enus') if (mylang === null)
mylang = 'enUs' {
if (mylang.toLowerCase() === 'enuk') if (navigator) {
mylang = 'enUk' mylang = navigator.language
console.log(`LANG2 NAVIGATOR ${mylang}`)
} else {
mylang = this.$q.i18n.lang
}
console.log('IMPOSTA LANGMY', mylang)
}
if (mylang !== null) {
if (mylang.toLowerCase() === 'enus')
mylang = 'enUs'
if ((mylang.toLowerCase() === 'eses') || (mylang.toLowerCase() === 'es-es'))
mylang = 'esEs'
if ((mylang.toLowerCase() === 'enuk') || (mylang.toLowerCase() === 'en-uk'))
mylang = 'enUk'
}
if (!mylang) if (!mylang)
mylang = process.env.LANG_DEFAULT mylang = process.env.LANG_DEFAULT

View File

@@ -79,13 +79,14 @@
/* {route: '/vreg?idlink=aaa', faIcon: 'fa fa-login', materialIcon: 'login', name: 'pages.vreg'},*/ /* {route: '/vreg?idlink=aaa', faIcon: 'fa fa-login', materialIcon: 'login', name: 'pages.vreg'},*/
], ],
show: true, show: true,
}, }
Forms: { // ,
routes: [ // Forms: {
{ route: '/prec', faIcon: 'fa fa-search', materialIcon: 'search', name: 'pages.Test' }, // routes: [
], // { route: '/prec', faIcon: 'fa fa-search', materialIcon: 'search', name: 'pages.Test' },
show: false // ],
}, // show: false
// },
} }
} }

View File

@@ -1,10 +1,6 @@
export default { export default {
// apiGraphQL: 'http://localhost:8000/graphql', // apiGraphQL: 'http://localhost:8000/graphql',
i18n: { i18n: {
languages: [
{ code: 'it', name: 'Italiano', active: true },
{ code: 'enUs', name: 'English', active: true }
],
default: 'it', default: 'it',
fallbackTo: 'it' fallbackTo: 'it'
}, },

View File

@@ -7,8 +7,19 @@ export default ({ app, store, Vue }) => {
Vue.use(VueI18n); Vue.use(VueI18n);
// Vue.config.lang = process.env.LANG_DEFAULT; // Vue.config.lang = process.env.LANG_DEFAULT;
let mylang = localStorage.getItem(rescodes.localStorage.lang) let mylang = localStorage.getItem(rescodes.localStorage.lang)
if (mylang === '')
if ((navigator) && (mylang === null)) {
mylang = navigator.language
console.log(`LANG NAVIGATOR ${mylang}`)
}
if (mylang === '') {
mylang = process.env.LANG_DEFAULT; mylang = process.env.LANG_DEFAULT;
}
if (mylang.toLowerCase() === 'es-es')
mylang = 'esEs'
console.log('MYLANG=', mylang)
Vue.config.lang = mylang Vue.config.lang = mylang
// console.log("PLUGINS INIT...."); // console.log("PLUGINS INIT....");

View File

@@ -125,7 +125,7 @@ const messages = {
}, },
connection: 'Connessione', connection: 'Connessione',
}, },
es: { 'esEs': {
dialog: { dialog: {
ok: 'Vale', ok: 'Vale',
yes: 'Sí', yes: 'Sí',

View File

@@ -5,8 +5,9 @@ export class AxiosSuccess {
public status: number public status: number
public data: any public data: any
constructor(data: any) { constructor(data: any, status: number) {
this.data = data this.data = data
this.status = status
} }
} }
@@ -14,10 +15,12 @@ export class AxiosError {
public success: boolean = false public success: boolean = false
public status: number public status: number
public data: any public data: any
public code: any
constructor(status: number, data?: any) { constructor(status: number, data?: any, code?: any) {
this.status = status this.status = status
this.data = data this.data = data
this.code = code
if (status !== 401) { if (status !== 401) {
// if (status == 0) message = 'Vérifiez votre connexion Internet'; // if (status == 0) message = 'Vérifiez votre connexion Internet';
// NotificationsStore.actions.addNotification({ type: 'warning', message: message }) // NotificationsStore.actions.addNotification({ type: 'warning', message: message })

View File

@@ -1,50 +1,25 @@
import axios, { AxiosInstance, AxiosPromise, AxiosResponse, AxiosInterceptorManager } from 'axios' 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, lang: string, mytok: string, method: string, mydata: any) { async function sendRequest(url: string, method: string, mydata: any) {
console.log('sendRequest', method, url, '[', lang, ']') console.log('sendRequest', method, url)
const authHeader = new Headers() let request
authHeader.append('content-Type', 'application/json') if (method === 'GET')
authHeader.append('Accept', 'application/json') request = Api.get(url, mydata)
if (url !== process.env.MONGODB_HOST + '/users/login') { else if (method === 'POST')
authHeader.append('x-auth', mytok) request = Api.post(url, mydata)
// console.log('TOK PASSATO ALLA FETCH:', mytok) else if (method === 'DELETE')
} request = Api.Delete(url, mydata)
// authHeader.append('accept-language', lang) else if (method === 'PUT')
request = Api.put(url, mydata)
let configInit: RequestInit
if (method === 'GET') {
configInit = {
method: method,
cache: 'no-cache',
mode: 'cors',
headers: authHeader
}
} else if (method === 'DELETE') {
configInit = {
method: method,
cache: 'no-cache',
mode: 'cors',
headers: authHeader
}
} else {
configInit = {
method: method,
cache: 'no-cache',
mode: 'cors',
headers: authHeader
}
if (mydata !== null)
configInit.body = JSON.stringify(mydata)
}
const request: Promise<Response> = fetch(url, configInit)
return request
const req: Promise<Types.AxiosSuccess | Types.AxiosError> = request
return req
} }
export default sendRequest export default sendRequest

View File

@@ -3,8 +3,11 @@ import axios, { AxiosInstance, AxiosPromise, AxiosResponse, AxiosInterceptorMana
import router from '@router' import router from '@router'
import {clone} from 'lodash' import {clone} from 'lodash'
import * as Types from './ApiTypes' import * as Types from './ApiTypes'
import { GlobalStore, UserStore } from '@store'
import { rescodes } from '@src/store/Modules/rescodes'
import { serv_constants } from '@src/store/Modules/serv_constants'
export const API_URL = process.env.API_URL export const API_URL = process.env.MONGODB_HOST
export const axiosInstance: AxiosInstance = axios.create({ export const axiosInstance: AxiosInstance = axios.create({
baseURL: API_URL, baseURL: API_URL,
headers: { headers: {
@@ -32,35 +35,83 @@ export const removeAuthHeaders = () => {
delete axiosInstance.defaults.headers.Authorization delete axiosInstance.defaults.headers.Authorization
} }
async function Request(type: string, path: string, payload: any, noAuth?: boolean): Promise<Types.AxiosSuccess | Types.AxiosError> { async function Request(type: string, path: string, payload: any, setAuthToken?: boolean): Promise<Types.AxiosSuccess | Types.AxiosError> {
let ricevuto = false
try { try {
console.log(`Axios Request [${type}]:`, axiosInstance.defaults) console.log(`Axios Request [${type}]:`, axiosInstance.defaults)
let response: AxiosResponse let response: AxiosResponse
if (type === 'post' || type === 'put') { if (type === 'post' || type === 'put') {
response = await axiosInstance[type](path, payload, { response = await axiosInstance[type](path, payload, {
headers: { headers: {
'Content-Type': 'application/json' 'Content-Type': 'application/json',
'x-auth': UserStore.state.x_auth_token
} }
}) })
console.log(new Types.AxiosSuccess(response.data)) ricevuto = true
return new Types.AxiosSuccess(response.data) // console.log(new Types.AxiosSuccess(response.data, response.status))
const setAuthToken = (path === '/updatepwd')
if (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.mutations.setServerCode(rescodes.ERR_AUTHENTICATION)
}
if (setAuthToken) {
UserStore.mutations.UpdatePwd(x_auth_token)
localStorage.setItem(rescodes.localStorage.token, x_auth_token)
}
UserStore.mutations.setAuth(x_auth_token)
localStorage.setItem(rescodes.localStorage.token, x_auth_token)
}
GlobalStore.mutations.setStateConnection(ricevuto ? 'online' : 'offline')
UserStore.mutations.setServerCode(rescodes.OK)
} catch (e) {
if (setAuthToken) {
UserStore.mutations.setServerCode(rescodes.ERR_AUTHENTICATION)
UserStore.mutations.setAuth('')
}
GlobalStore.mutations.setStateConnection(ricevuto ? 'online' : 'offline')
return Promise.reject(new Types.AxiosError(serv_constants.RIS_CODE__HTTP_FORBIDDEN_INVALID_TOKEN, null, rescodes.ERR_AUTHENTICATION))
}
}
return new Types.AxiosSuccess(response.data, response.status)
} else if (type === 'get' || type === 'delete') { } else if (type === 'get' || type === 'delete') {
// @ts-ignore // @ts-ignore
response = await axiosInstance[type](path, { response = await axiosInstance[type](path, {
params: payload, params: payload,
headers: {'Content-Type': 'application/json'} headers: {'Content-Type': 'application/json',
'x-auth': UserStore.state.x_auth_token
}
}) })
return new Types.AxiosSuccess(response.data) return new Types.AxiosSuccess(response.data, response.status)
} else if (type === 'postFormData') { } else if (type === 'postFormData') {
response = await axiosInstance.post(path, payload, { response = await axiosInstance.post(path, payload, {
headers: { headers: {
'Content-Type': 'multipart/form-data' 'Content-Type': 'multipart/form-data',
'x-auth': UserStore.state.x_auth_token
} }
}) })
return new Types.AxiosSuccess(response.data) return new Types.AxiosSuccess(response.data, response.status)
} }
} }
catch (error) { catch (error) {
if (process.env.DEV) {
console.log('ERROR using', path, error, 'ricevuto=', ricevuto)
}
if (!ricevuto) {
UserStore.mutations.setServerCode(rescodes.ERR_SERVERFETCH)
} else {
UserStore.mutations.setServerCode(rescodes.ERR_GENERICO)
}
if (error.response) { if (error.response) {
return Promise.reject(new Types.AxiosError(error.response.status, error.response.data)) return Promise.reject(new Types.AxiosError(error.response.status, error.response.data))
} else { } else {

View File

@@ -13,6 +13,7 @@ import { GlobalStore, UserStore } from '@modules'
import globalroutines from './../../globalroutines/index' import globalroutines from './../../globalroutines/index'
import { serv_constants } from '@src/store/Modules/serv_constants' import { serv_constants } from '@src/store/Modules/serv_constants'
import router from '@router' import router from '@router'
import * as Types from "@src/store/Api/ApiTypes"
// const algoliaApi = new AlgoliaSearch() // const algoliaApi = new AlgoliaSearch()
@@ -47,86 +48,31 @@ export namespace ApiTool {
}) })
} }
export async function SendReq(url: string, method: string, mydata: any, setAuthToken: boolean = false) { export async function SendReq(url: string, method: string, mydata: any, setAuthToken: boolean = false): Promise<Types.AxiosSuccess | Types.AxiosError> {
UserStore.mutations.setServerCode(rescodes.EMPTY) UserStore.mutations.setServerCode(rescodes.EMPTY)
UserStore.mutations.setResStatus(0) UserStore.mutations.setResStatus(0)
return await new Promise(function (resolve, reject) { return await new Promise(function (resolve, reject) {
let ricevuto = false
return sendRequest(url, UserStore.state.lang, UserStore.state.x_auth_token, method, mydata) return sendRequest(url, method, mydata)
.then(resreceived => { .then(res => {
console.log('resreceived', resreceived) console.log('res', res)
ricevuto = true
let res = resreceived.clone()
if (process.env.DEV) {
// console.log('SendReq RES [', res.status, ']', res)
}
UserStore.mutations.setResStatus(res.status) UserStore.mutations.setResStatus(res.status)
if (res.status === 200) { if (res.status === serv_constants.RIS_CODE__HTTP_FORBIDDEN_INVALID_TOKEN) {
let x_auth_token = ''
try {
if (setAuthToken) {
x_auth_token = String(res.headers.get('x-auth'))
if (x_auth_token === '') {
UserStore.mutations.setServerCode(rescodes.ERR_AUTHENTICATION)
}
UserStore.mutations.setAuth(x_auth_token)
if (url === process.env.MONGODB_HOST + '/updatepwd') {
UserStore.mutations.UpdatePwd({ x_auth_token })
localStorage.setItem(rescodes.localStorage.token, x_auth_token)
}
}
UserStore.mutations.setServerCode(rescodes.OK)
} catch (e) {
if (setAuthToken) {
UserStore.mutations.setServerCode(rescodes.ERR_AUTHENTICATION)
UserStore.mutations.setAuth('')
}
GlobalStore.mutations.setStateConnection(ricevuto ? 'online' : 'offline')
return reject({ code: rescodes.ERR_AUTHENTICATION })
}
} else if (res.status === serv_constants.RIS_CODE__HTTP_FORBIDDEN_INVALID_TOKEN) {
// Forbidden // Forbidden
// You probably is connectiong with other page... // You probably is connectiong with other page...
UserStore.mutations.setServerCode(rescodes.ERR_AUTHENTICATION) UserStore.mutations.setServerCode(rescodes.ERR_AUTHENTICATION)
UserStore.mutations.setAuth('') UserStore.mutations.setAuth('')
GlobalStore.mutations.setStateConnection(ricevuto ? 'online' : 'offline')
router.push('/signin') router.push('/signin')
return reject({ code: rescodes.ERR_AUTHENTICATION }) return reject({ code: rescodes.ERR_AUTHENTICATION })
} }
GlobalStore.mutations.setStateConnection(ricevuto ? 'online' : 'offline') return resolve(res)
return res.json()
.then((body) => {
// console.log('BODY RES = ', body)
return resolve({ res, body, status: res.status })
})
.catch(e => {
return resolve({ res, body: {}, status: res.status })
// Array not found...
// UserStore.mutations.setServerCode(rescodes.ERR_GENERICO)
// return reject({ code: rescodes.ERR_GENERICO, status: res.status })
})
}) })
.catch(error => { .catch(error => {
if (process.env.DEV) { console.log('error', error)
console.log('ERROR using', url, error, 'ricevuto=', ricevuto) return reject(error)
}
if (!ricevuto) {
UserStore.mutations.setServerCode(rescodes.ERR_SERVERFETCH)
} else {
UserStore.mutations.setServerCode(rescodes.ERR_GENERICO)
}
GlobalStore.mutations.setStateConnection(ricevuto ? 'online' : 'offline')
return reject({ code: error })
}) })
}) })
} }

View File

@@ -200,10 +200,8 @@ namespace Actions {
}, },
} }
let call = process.env.MONGODB_HOST + '/subscribe' return Api.SendReq('/subscribe', 'POST', myres)
.then(res => {
return Api.SendReq(call, 'POST', myres)
.then(({ res, body }) => {
state.wasAlreadySubscribed = true state.wasAlreadySubscribed = true
state.wasAlreadySubOnDb = true state.wasAlreadySubOnDb = true

View File

@@ -229,30 +229,27 @@ namespace Actions {
if (UserStore.state.userId === '') if (UserStore.state.userId === '')
return false // Login not made return false // Login not made
let call = process.env.MONGODB_HOST + '/todos/' + UserStore.state.userId
state.networkDataReceived = false state.networkDataReceived = false
let ris = await Api.SendReq(call, 'GET', null) let ris = await Api.SendReq('/todos/' + UserStore.state.userId, 'GET', null)
.then(({ res, body, status }) => { .then(res => {
state.networkDataReceived = true state.networkDataReceived = true
// console.log('******* UPDATE TODOS.STATE.TODOS !:', res.todos) // console.log('******* UPDATE TODOS.STATE.TODOS !:', res.todos)
if (body.todos) { if (res.data.todos) {
state.todos = [...body.todos] state.todos = [...res.data.todos]
Todos.mutations.setTodos_changed() Todos.mutations.setTodos_changed()
} }
console.log('********** res', 'state.todos', state.todos, 'checkPending', checkPending) console.log('********** res', 'state.todos', state.todos, 'checkPending', checkPending)
// After Login will store into the indexedDb... // After Login will store into the indexedDb...
return { status } return res
}) })
.catch(error => { .catch(error => {
console.log('error=', error) console.log('error=', error)
UserStore.mutations.setErrorCatch(error) UserStore.mutations.setErrorCatch(error)
return { status } return error
}) })
// console.log('ris : ', ris) // console.log('ris : ', ris)
@@ -315,7 +312,7 @@ namespace Actions {
if (!('serviceWorker' in navigator)) { if (!('serviceWorker' in navigator)) {
console.log('dbInsertSaveTodo', itemtodo, method) console.log('dbInsertSaveTodo', itemtodo, method)
let call = process.env.MONGODB_HOST + '/todos' let call = '/todos'
if (UserStore.state.userId === '') if (UserStore.state.userId === '')
return false // Login not made return false // Login not made
@@ -326,8 +323,8 @@ namespace Actions {
console.log('TODO TO SAVE: ', itemtodo) console.log('TODO TO SAVE: ', itemtodo)
let res = await Api.SendReq(call, method, itemtodo) let res = await Api.SendReq(call, method, itemtodo)
.then(({ res, newItem }) => { .then(res => {
console.log('dbInsertSaveTodo to the Server', newItem) console.log('dbInsertSaveTodo to the Server', res.data)
return (res.status === 200) return (res.status === 200)
}) })
@@ -345,13 +342,11 @@ namespace Actions {
if (!('serviceWorker' in navigator)) { if (!('serviceWorker' in navigator)) {
// console.log('dbDeleteTodo', item) // console.log('dbDeleteTodo', item)
let call = process.env.MONGODB_HOST + '/todos/' + item._id
if (UserStore.state.userId === '') if (UserStore.state.userId === '')
return false // Login not made return false // Login not made
let res = await Api.SendReq(call, 'DELETE', item) let res = await Api.SendReq('/todos/' + item._id, 'DELETE', item)
.then(function ({ res, itemris }) { .then(res => {
console.log('dbDeleteTodo to the Server') console.log('dbDeleteTodo to the Server')
}) })
.catch((error) => { .catch((error) => {

View File

@@ -107,12 +107,12 @@ namespace Mutations {
localStorage.setItem(rescodes.localStorage.lang, state.lang) localStorage.setItem(rescodes.localStorage.lang, state.lang)
} }
function UpdatePwd(state: IUserState, data: IIdToken) { function UpdatePwd(state: IUserState, x_auth_token: string) {
state.x_auth_token = data.x_auth_token state.x_auth_token = x_auth_token
if (!state.tokens) { if (!state.tokens) {
state.tokens = [] state.tokens = []
} }
state.tokens.push({ access: 'auth', token: data.x_auth_token, data_login: new Date() }) state.tokens.push({ access: 'auth', token: x_auth_token, data_login: new Date() })
} }
function setServerCode(state: IUserState, num: number) { function setServerCode(state: IUserState, num: number) {
@@ -208,8 +208,6 @@ namespace Actions {
} }
async function resetpwd(context, paramquery: IUserState) { async function resetpwd(context, paramquery: IUserState) {
let call = process.env.MONGODB_HOST + '/updatepwd'
console.log('CALL ' + call)
let usertosend = { let usertosend = {
keyappid: process.env.PAO_APP_ID, keyappid: process.env.PAO_APP_ID,
@@ -222,9 +220,9 @@ namespace Actions {
Mutations.mutations.setServerCode(rescodes.CALLING) Mutations.mutations.setServerCode(rescodes.CALLING)
return await Api.SendReq(call, 'POST', usertosend, true) return await Api.SendReq('/updatepwd', 'POST', usertosend, true)
.then(({ res, body }) => { .then(res => {
return { code: body.code, msg: body.msg } return { code: res.data.code, msg: res.data.msg }
}) })
.catch((error) => { .catch((error) => {
UserStore.mutations.setErrorCatch(error) UserStore.mutations.setErrorCatch(error)
@@ -235,9 +233,6 @@ namespace Actions {
async function requestpwd(context, paramquery: IUserState) { async function requestpwd(context, paramquery: IUserState) {
let call = process.env.MONGODB_HOST + '/requestnewpwd'
console.log('CALL ' + call)
let usertosend = { let usertosend = {
keyappid: process.env.PAO_APP_ID, keyappid: process.env.PAO_APP_ID,
idapp: process.env.APP_ID, idapp: process.env.APP_ID,
@@ -247,9 +242,9 @@ namespace Actions {
Mutations.mutations.setServerCode(rescodes.CALLING) Mutations.mutations.setServerCode(rescodes.CALLING)
return await Api.SendReq(call, 'POST', usertosend) return await Api.SendReq('/requestnewpwd', 'POST', usertosend)
.then(({ res, body }) => { .then(res => {
return { code: body.code, msg: body.msg } return { code: res.data.code, msg: res.data.msg }
}).catch((error) => { }).catch((error) => {
UserStore.mutations.setErrorCatch(error) UserStore.mutations.setErrorCatch(error)
return UserStore.getters.getServerCode return UserStore.getters.getServerCode
@@ -258,9 +253,6 @@ namespace Actions {
} }
async function vreg(context, paramquery: ILinkReg) { async function vreg(context, paramquery: ILinkReg) {
let call = process.env.MONGODB_HOST + '/vreg'
console.log('CALL ' + call)
let usertosend = { let usertosend = {
keyappid: process.env.PAO_APP_ID, keyappid: process.env.PAO_APP_ID,
idapp: process.env.APP_ID, idapp: process.env.APP_ID,
@@ -270,17 +262,17 @@ namespace Actions {
Mutations.mutations.setServerCode(rescodes.CALLING) Mutations.mutations.setServerCode(rescodes.CALLING)
return await Api.SendReq(call, 'POST', usertosend) return await Api.SendReq('/vreg', 'POST', usertosend)
.then(({ res, body }) => { .then(res => {
// console.log("RITORNO 2 "); // console.log("RITORNO 2 ");
// mutations.setServerCode(myres); // mutations.setServerCode(myres);
if (body.code === serv_constants.RIS_CODE_EMAIL_VERIFIED) { if (res.data.code === serv_constants.RIS_CODE_EMAIL_VERIFIED) {
console.log('VERIFICATO !!') console.log('VERIFICATO !!')
localStorage.setItem(rescodes.localStorage.verified_email, String(true)) localStorage.setItem(rescodes.localStorage.verified_email, String(true))
} else { } else {
console.log('Risultato di vreg: ', body.code) console.log('Risultato di vreg: ', res.data.code)
} }
return { code: body.code, msg: body.msg } return { code: res.data.code, msg: res.data.msg }
}).catch((error) => { }).catch((error) => {
UserStore.mutations.setErrorCatch(error) UserStore.mutations.setErrorCatch(error)
return UserStore.getters.getServerCode return UserStore.getters.getServerCode
@@ -288,8 +280,7 @@ namespace Actions {
} }
async function signup(context, authData: ISignupOptions) { async function signup(context, authData: ISignupOptions) {
let call = process.env.MONGODB_HOST + '/users' console.log('SIGNUP')
console.log('CALL ' + call)
// console.log("PASSW: " + authData.password); // console.log("PASSW: " + authData.password);
@@ -309,21 +300,18 @@ namespace Actions {
console.log(usertosend) console.log(usertosend)
let myres: IResult
Mutations.mutations.setServerCode(rescodes.CALLING) Mutations.mutations.setServerCode(rescodes.CALLING)
return Api.SendReq(call, 'POST', usertosend) return Api.SendReq('/users', 'POST', usertosend)
.then(({ res, body }) => { .then(res => {
myres = res
const newuser = body const newuser = res.data
console.log('newuser', newuser) console.log('newuser', newuser)
Mutations.mutations.setServerCode(myres.status) Mutations.mutations.setServerCode(res.status)
if (myres.status === 200) { if (res.status === 200) {
let userId = newuser._id let userId = newuser._id
let username = authData.username let username = authData.username
if (process.env.DEV) { if (process.env.DEV) {
@@ -363,22 +351,25 @@ namespace Actions {
} }
async function signin(context, authData: ISigninOptions) { async function signin(context, authData: ISigninOptions) {
let call = process.env.MONGODB_HOST + '/users/login' console.log('LOGIN ')
console.log('LOGIN ' + call)
console.log('MYLANG = ' + state.lang) console.log('MYLANG = ' + state.lang)
let sub = null let sub = null
if ('serviceWorker' in navigator) { try {
sub = await navigator.serviceWorker.ready if ('serviceWorker' in navigator) {
.then(function (swreg) { sub = await navigator.serviceWorker.ready
let sub = swreg.pushManager.getSubscription() .then(function (swreg) {
return sub let sub = swreg.pushManager.getSubscription()
}) return sub
.catch(e => { })
sub = null .catch(e => {
}) sub = null
})
}
} catch (e) {
console.log('Err navigator.serviceWorker.ready ... GetSubscription:', e)
} }
const options = { const options = {
@@ -403,48 +394,29 @@ namespace Actions {
let myres: any let myres: any
return Api.SendReq(call, 'POST', usertosend, true) return Api.SendReq('/users/login', 'POST', usertosend, true)
.then(({ res, body }) => { .then(res => {
myres = res myres = res
if (myres.data.code === serv_constants.RIS_CODE_LOGIN_ERR) {
if (body.code === serv_constants.RIS_CODE_LOGIN_ERR) { Mutations.mutations.setServerCode(myres.data.code)
Mutations.mutations.setServerCode(body.code) return myres
return { myres, body }
} }
Mutations.mutations.setServerCode(myres.status)
if (myres.status !== 200) { if (myres.status !== 200) {
return Promise.reject(rescodes.ERR_GENERICO) return Promise.reject(rescodes.ERR_GENERICO)
} }
return { myres, body } return myres
}).then(({ myres, body }) => { }).then(res => {
if (myres.status === serv_constants.RIS_CODE__HTTP_FORBIDDEN_INVALID_TOKEN) { if (res.success) {
if (process.env.DEV) { GlobalStore.mutations.SetwasAlreadySubOnDb(res.data.subsExistonDb)
console.log('CODE = ' + body.code)
}
return body.code
} else if (myres.status !== 200) {
if (process.env.DEV) {
console.log('CODE = ' + body.code)
}
return body.code
}
if (myres.status === 200) { let myuser: IUserState = res.data.usertosend
GlobalStore.mutations.SetwasAlreadySubOnDb(body.subsExistonDb)
let myuser: IUserState = body.usertosend
if (myuser) { if (myuser) {
let userId = myuser.userId let userId = myuser.userId
let username = authData.username let username = authData.username
let verified_email = myuser.verified_email let verified_email = myuser.verified_email
if (process.env.DEV) {
console.log('USERNAME = ' + username, 'IDUSER= ' + userId)
// console.log('state.x_auth_token= ' + state.x_auth_token)
}
Mutations.mutations.authUser({ Mutations.mutations.authUser({
userId, userId,
@@ -501,17 +473,14 @@ namespace Actions {
await GlobalStore.actions.clearDataAfterLogout() await GlobalStore.actions.clearDataAfterLogout()
let call = process.env.MONGODB_HOST + '/users/me/token'
console.log('CALL ' + call)
let usertosend = { let usertosend = {
keyappid: process.env.PAO_APP_ID, keyappid: process.env.PAO_APP_ID,
idapp: process.env.APP_ID idapp: process.env.APP_ID
} }
console.log(usertosend) console.log(usertosend)
const riscall = await Api.SendReq(call, 'DELETE', usertosend) const riscall = await Api.SendReq('/users/me/token', 'DELETE', usertosend)
.then(({ res, body }) => { .then(res => {
console.log(res) console.log(res)
}).then(() => { }).then(() => {
Mutations.mutations.clearAuthData() Mutations.mutations.clearAuthData()

View File

@@ -68,7 +68,7 @@ export const rescodes = {
value: 0, value: 0,
icon: 'expand_more' icon: 'expand_more'
}], }],
'es': [ 'esEs': [
{ {
id: 1, id: 1,
label: 'Alta', label: 'Alta',
@@ -169,7 +169,7 @@ export const rescodes = {
checked: false checked: false
} }
], ],
'es': [ 'esEs': [
{ {
id: 10, id: 10,
label: '', label: '',

View File

@@ -136,7 +136,7 @@ export default class Signin extends Vue {
console.log(this.signin) console.log(this.signin)
UserStore.actions.signin(this.signin) UserStore.actions.signin(this.signin)
.then((riscode) => { .then((riscode) => {
// console.log('riscode=', riscode) console.log('signin FINITO CALL: riscode=', riscode)
if (riscode === rescodes.OK) { if (riscode === rescodes.OK) {
router.push('/signin') router.push('/signin')
} }
@@ -162,7 +162,7 @@ export default class Signin extends Vue {
} }
}) })
.catch(error => { .catch(error => {
console.log('ERROR = ' + error) console.log('ERROR SIGNIN = ' + error)
this.checkErrors(error) this.checkErrors(error)
this.$q.loading.hide() this.$q.loading.hide()