Disable CapacitorHttp and add plugin to replace axios calls #781

This commit is contained in:
advplyr 2023-09-15 17:35:44 -05:00
parent 27bbe40874
commit 57d1fbfa83
21 changed files with 142 additions and 62 deletions

View file

@ -5,7 +5,7 @@
"bundledWebRuntime": false,
"plugins": {
"CapacitorHttp": {
"enabled": true
"enabled": false
}
}
}

View file

@ -5,7 +5,7 @@
"bundledWebRuntime": false,
"plugins": {
"CapacitorHttp": {
"enabled": true
"enabled": false
}
}
}

View file

@ -139,8 +139,8 @@ export default {
async logout() {
await this.$hapticsImpact()
if (this.user) {
await this.$axios.$post('/logout').catch((error) => {
console.error(error)
await this.$nativeHttp.post('/logout').catch((error) => {
console.error('Failed to logout', error)
})
}

View file

@ -166,7 +166,7 @@ export default {
const sfQueryString = this.currentSFQueryString ? this.currentSFQueryString + '&' : ''
const fullQueryString = `?${sfQueryString}limit=${this.booksPerFetch}&page=${page}&minified=1&include=rssfeed,numEpisodesIncomplete`
const payload = await this.$axios.$get(`/api/libraries/${this.currentLibraryId}/${entityPath}${fullQueryString}`).catch((error) => {
const payload = await this.$nativeHttp.get(`/api/libraries/${this.currentLibraryId}/${entityPath}${fullQueryString}`).catch((error) => {
console.error('failed to fetch books', error)
return null
})

View file

@ -58,24 +58,7 @@ export default {
return this._author.numBooks || 0
}
},
methods: {
async searchAuthor() {
this.searching = true
var response = await this.$axios.$post(`/api/authors/${this.authorId}/match`, { q: this.name }).catch((error) => {
console.error('Failed', error)
return null
})
if (!response) {
this.$toast.error('Author not found')
} else if (response.updated) {
if (response.author.imagePath) this.$toast.success('Author was updated')
else this.$toast.success('Author was updated (no image found)')
} else {
this.$toast.info('No updates were made for Author')
}
this.searching = false
}
},
methods: {},
mounted() {}
}
</script>

View file

@ -77,6 +77,7 @@
<script>
import { Dialog } from '@capacitor/dialog'
import { CapacitorHttp } from '@capacitor/core'
export default {
data() {
@ -217,27 +218,57 @@ export default {
return null
}
},
pingServerAddress(address, customHeaders) {
const options = { timeout: 3000 }
if (customHeaders) {
options.headers = customHeaders
async getRequest(url, headers, connectTimeout = 6000) {
const options = {
url,
headers,
connectTimeout
}
return this.$axios
.$get(`${address}/ping`, options)
.then((data) => data.success)
const response = await CapacitorHttp.get(options)
console.log('[ServerConnectForm] GET request response', response)
if (response.status >= 400) {
throw new Error(response.data)
} else {
return response.data
}
},
async postRequest(url, data, headers, connectTimeout = 6000) {
if (!headers) headers = {}
if (!headers['Content-Type'] && data) {
headers['Content-Type'] = 'application/json'
}
const options = {
url,
headers,
data,
connectTimeout
}
const response = await CapacitorHttp.post(options)
console.log('[ServerConnectForm] POST request response', response)
if (response.status >= 400) {
throw new Error(response.data)
} else {
return response.data
}
},
pingServerAddress(address, customHeaders) {
return this.getRequest(`${address}/ping`, customHeaders)
.then((data) => {
return data.success
})
.catch((error) => {
console.error('Server check failed', error)
console.error('Server ping failed', error)
const errorMsg = error.message || error
this.error = 'Failed to ping server'
if (typeof errorMsg === 'string') {
this.error += ` (${errorMsg})`
}
return false
})
},
requestServerLogin() {
const options = {}
if (this.serverConfig.customHeaders) {
options.headers = this.serverConfig.customHeaders
}
return this.$axios
.$post(`${this.serverConfig.address}/login`, { username: this.serverConfig.username, password: this.password }, options)
return this.postRequest(`${this.serverConfig.address}/login`, { username: this.serverConfig.username, password: this.password }, this.serverConfig.customHeaders, 20000)
.then((data) => {
if (!data.user) {
console.error(data.error)
@ -248,8 +279,11 @@ export default {
})
.catch((error) => {
console.error('Server auth failed', error)
var errorMsg = error.response ? error.response.data || 'Unknown Error' : 'Unknown Error'
this.error = errorMsg
const errorMsg = error.message || error
this.error = 'Failed to login'
if (typeof errorMsg === 'string') {
this.error += ` (${errorMsg})`
}
return false
})
},
@ -330,12 +364,19 @@ export default {
this.error = null
this.processing = true
var authRes = await this.$axios.$post(`${this.serverConfig.address}/api/authorize`, null, { headers: { Authorization: `Bearer ${this.serverConfig.token}` } }).catch((error) => {
console.error('[Server] Server auth failed', error)
var errorMsg = error.response ? error.response.data || 'Unknown Error' : 'Unknown Error'
this.error = errorMsg
const authRes = await this.postRequest(`${this.serverConfig.address}/api/authorize`, null, { Authorization: `Bearer ${this.serverConfig.token}` }).catch((error) => {
console.error('[ServerConnectForm] Server auth failed', error)
const errorMsg = error.message || error
this.error = 'Failed to authorize'
if (typeof errorMsg === 'string') {
this.error += ` (${errorMsg})`
}
return false
})
console.log('[ServerConnectForm] authRes=', authRes)
this.processing = false
return authRes
},

View file

@ -183,7 +183,7 @@ export default {
// Update server item
if (this.serverLibraryItemId) {
this.$axios.$patch(`/api/me/progress/${this.serverLibraryItemId}`, payload).catch((error) => {
this.$nativeHttp.patch(`/api/me/progress/${this.serverLibraryItemId}`, payload).catch((error) => {
console.error('ComicReader.updateProgress failed:', error)
})
}

View file

@ -171,7 +171,7 @@ export default {
// Update server item
if (this.serverLibraryItemId) {
this.$axios.$patch(`/api/me/progress/${this.serverLibraryItemId}`, payload).catch((error) => {
this.$nativeHttp.patch(`/api/me/progress/${this.serverLibraryItemId}`, payload).catch((error) => {
console.error('EpubReader.updateProgress failed:', error)
})
}

View file

@ -146,7 +146,7 @@ export default {
// Update server item
if (this.serverLibraryItemId) {
this.$axios.$patch(`/api/me/progress/${this.serverLibraryItemId}`, payload).catch((error) => {
this.$nativeHttp.patch(`/api/me/progress/${this.serverLibraryItemId}`, payload).catch((error) => {
console.error('PdfReader.updateProgress failed:', error)
})
}

View file

@ -230,7 +230,7 @@ export default {
return this.$toast.error('Podcast does not have an RSS Feed')
}
this.fetchingRSSFeed = true
const payload = await this.$axios.$post(`/api/podcasts/feed`, { rssFeed: this.mediaMetadata.feedUrl }).catch((error) => {
const payload = await this.$nativeHttp.post(`/api/podcasts/feed`, { rssFeed: this.mediaMetadata.feedUrl }).catch((error) => {
console.error('Failed to get feed', error)
this.$toast.error('Failed to get podcast feed')
return null

View file

@ -5,7 +5,7 @@
"bundledWebRuntime": false,
"plugins": {
"CapacitorHttp": {
"enabled": true
"enabled": false
}
}
}

View file

@ -15,6 +15,8 @@
</template>
<script>
import { CapacitorHttp } from '@capacitor/core'
export default {
data() {
return {
@ -97,6 +99,21 @@ export default {
await this.$store.dispatch('user/loadUserSettings')
},
async postRequest(url, data, headers, connectTimeout = 30000) {
const options = {
url,
headers,
data,
connectTimeout
}
const response = await CapacitorHttp.post(options)
console.log('[default] POST request response', response)
if (response.status >= 400) {
throw new Error(response.data)
} else {
return response.data
}
},
async attemptConnection() {
console.warn('[default] attemptConnection')
if (!this.networkConnected) {
@ -126,10 +143,8 @@ export default {
console.log(`[default] Got server config, attempt authorize ${serverConfig.address}`)
const authRes = await this.$axios.$post(`${serverConfig.address}/api/authorize`, null, { headers: { Authorization: `Bearer ${serverConfig.token}` }, timeout: 3000 }).catch((error) => {
console.error('[Server] Server auth failed', error)
const errorMsg = error.response ? error.response.data || 'Unknown Error' : 'Unknown Error'
this.error = errorMsg
const authRes = await this.postRequest(`${serverConfig.address}/api/authorize`, null, { Authorization: `Bearer ${serverConfig.token}` }, 10000).catch((error) => {
console.error('[default] Server auth failed', error)
return false
})
if (!authRes) {

View file

@ -44,6 +44,7 @@ export default {
'@/plugins/localStore.js',
'@/plugins/init.client.js',
'@/plugins/axios.js',
'@/plugins/nativeHttp.js',
'@/plugins/capacitor/index.js',
'@/plugins/capacitor/AbsAudioPlayer.js',
'@/plugins/toast.js',

View file

@ -49,7 +49,7 @@ export default {
async logout() {
await this.$hapticsImpact()
if (this.user) {
await this.$axios.$post('/logout').catch((error) => {
await this.$nativeHttp.post('/logout').catch((error) => {
console.error(error)
})
}

View file

@ -236,7 +236,7 @@ export default {
console.log('[categories] Local shelves set', this.shelves.length, this.lastLocalFetch)
if (isConnectedToServerWithInternet) {
const categories = await this.$axios.$get(`/api/libraries/${this.currentLibraryId}/personalized?minified=1&include=rssfeed,numEpisodesIncomplete`).catch((error) => {
const categories = await this.$nativeHttp.get(`/api/libraries/${this.currentLibraryId}/personalized?minified=1&include=rssfeed,numEpisodesIncomplete`).catch((error) => {
console.error('[categories] Failed to fetch categories', error)
return []
})

View file

@ -29,7 +29,7 @@ export default {
},
methods: {
async addEpisodeToPlaylist(episode) {
const libraryItem = await this.$axios.$get(`/api/items/${episode.libraryItemId}`).catch((error) => {
const libraryItem = await this.$nativeHttp.get(`/api/items/${episode.libraryItemId}`).catch((error) => {
console.error('Failed to get library item', error)
this.$toast.error('Failed to get library item')
return null
@ -42,7 +42,7 @@ export default {
async loadRecentEpisodes(page = 0) {
this.loadedLibraryId = this.currentLibraryId
this.processing = true
const episodePayload = await this.$axios.$get(`/api/libraries/${this.currentLibraryId}/recent-episodes?limit=25&page=${page}`).catch((error) => {
const episodePayload = await this.$nativeHttp.get(`/api/libraries/${this.currentLibraryId}/recent-episodes?limit=25&page=${page}`).catch((error) => {
console.error('Failed to get recent episodes', error)
this.$toast.error('Failed to get recent episodes')
return null

View file

@ -88,7 +88,7 @@ export default {
},
async checkRSSFeed(rssFeed) {
this.processing = true
var payload = await this.$axios.$post(`/api/podcasts/feed`, { rssFeed }).catch((error) => {
var payload = await this.$nativeHttp.post(`/api/podcasts/feed`, { rssFeed }).catch((error) => {
console.error('Failed to get feed', error)
this.$toast.error('Failed to get podcast feed')
return null
@ -103,7 +103,7 @@ export default {
async submitSearch(term) {
this.processing = true
this.termSearched = ''
const results = await this.$axios.$get(`/api/search/podcast?term=${encodeURIComponent(term)}`).catch((error) => {
const results = await this.$nativeHttp.get(`/api/search/podcast?term=${encodeURIComponent(term)}`).catch((error) => {
console.error('Search request failed', error)
return []
})
@ -119,7 +119,7 @@ export default {
return
}
this.processing = true
const payload = await this.$axios.$post(`/api/podcasts/feed`, { rssFeed: podcast.feedUrl }).catch((error) => {
const payload = await this.$nativeHttp.post(`/api/podcasts/feed`, { rssFeed: podcast.feedUrl }).catch((error) => {
console.error('Failed to get feed', error)
this.$toast.error('Failed to get podcast feed')
return null

View file

@ -503,7 +503,7 @@ export default {
const updatePayload = {
isFinished: !this.userIsFinished
}
this.$axios.$patch(`/api/me/progress/${this.libraryItemId}/${this.episode.id}`, updatePayload).catch((error) => {
this.$nativeHttp.patch(`/api/me/progress/${this.libraryItemId}/${this.episode.id}`, updatePayload).catch((error) => {
console.error('Failed', error)
this.$toast.error(`Failed to mark as ${updatePayload.isFinished ? 'Finished' : 'Not Finished'}`)
})

View file

@ -100,7 +100,7 @@ export default {
return
}
this.isFetching = true
const results = await this.$axios.$get(`/api/libraries/${this.currentLibraryId}/search?q=${value}&limit=5`).catch((error) => {
const results = await this.$nativeHttp.get(`/api/libraries/${this.currentLibraryId}/search?q=${value}&limit=5`).catch((error) => {
console.error('Search error', error)
return null
})

View file

@ -99,7 +99,7 @@ export default {
},
methods: {
async init() {
this.listeningStats = await this.$axios.$get(`/api/me/listening-stats`).catch((err) => {
this.listeningStats = await this.$nativeHttp.get(`/api/me/listening-stats`).catch((err) => {
console.error('Failed to load listening sesions', err)
return []
})

40
plugins/nativeHttp.js Normal file
View file

@ -0,0 +1,40 @@
import { CapacitorHttp } from '@capacitor/core'
export default function ({ store }, inject) {
const nativeHttp = {
request(method, _url, data, options = {}) {
let url = _url
const headers = {}
if (!url.startsWith('http') && !url.startsWith('capacitor')) {
const bearerToken = store.getters['user/getToken']
if (bearerToken) {
headers['Authorization'] = `Bearer ${bearerToken}`
} else {
console.warn('[nativeHttp] No Bearer Token for request')
}
const serverUrl = store.getters['user/getServerAddress']
if (serverUrl) {
url = `${serverUrl}${url}`
}
}
console.log(`[nativeHttp] Making ${method} request to ${url}`)
return CapacitorHttp.request({
method,
url,
data,
headers,
...options
}).then(res => res.data)
},
get(url, options = {}) {
return this.request('GET', url, undefined, options)
},
post(url, data, options = {}) {
return this.request('POST', url, data, options)
},
patch(url, data, options = {}) {
return this.request('PATCH', url, data, options)
}
}
inject('nativeHttp', nativeHttp)
}