I was asked to make API call to send data.
On Click in vue, I was firing this event
async facebookDataToSend () {
let campaignID = await this.$store.getters['CurrentInstance/id']
this.$axios.post(process.env.API_BASE_URL + 'faceeBookCampaign', { campaignID: campaignID }, { withCredentials: true })
},
But then, I was told to use API functions which already exsist in some xyz.js file.
My xyz.js file looks like this..
const rest = {
something: axios.create({
baseURL: process.env.API_BASE_URL,
withCredentials: true
}),
setClient: function (client) {
this.something = axios.create({
baseURL: process.env.API_BASE_URL,
withCredentials: true,
params: {
__somethingClient: client
}
})
this.client = client
}
}
Here, I am unable to comprehend how can I use this instance to make an api call So I viewed the code where they have already made the api call and saw something like this
const API = {
url: '/whateverHtml/',
method: 'post',
withCredentials: true,
data: {
'schemaType': 'something-event', // TODO FIXME
'field': 'description', // TODO FIXME
'html': this.model[this.field.key]
}
api.something.request(API).then(result => {
And I wasn't able to comprehend the code. For starters
What is request? I don't see my any method or property inside something
in my rest
variable
second why are they using withCredentials: true
in their API
object when they have already set up the property as true in rest
object]
What are the pro's of using axios.create({
i.e what they are doing than what I initially did this.$axios.post(
request
is a method defined by axios
. Link to docs.
request
allows you to make an HTTP call with any verb you want (POST, GET, DELETE, PUT). Most likely axios calls request
from inside all the other helper methods (get
, post
), but this is an implementation details. One of the advantages of using request
is that you don't have to hardcode the HTTP verb (POST, GET ...) and you can set it at run time depending on your input.
I see 2 reasons why they would set withCredentials
:
setClient
may or may not be called before something
something
to realise that the client is using credentials and you don't need any extra information about how rest
works.I don't think the request for you to use something
boils down to advantages of axios.$post
vs axios.create
. It's probably related more to how to organise your code.
Some advantages of using a separate module vs calling axios
directly
xyz
file to grow in time and your call to faceeBookCampaign
to end up being a method on the rest
variable. It makes more sense to end up using this.client
and not something
but this is up to the devs.(1) I say that id decouples you to some degree because there are semantics that need to be kept so everything works. The returned object needs to have a request method that accepts a config object. The config need to conform to the same structure as the one that axios wants. But, you can always write an adapter for that, so you are actually decoupled from axios.