1
votes

I have almost 13 Axios requests in my Vue application. which are almost the same

        axios({
          method: 'post',
          url: `${this.$root.api_url}/v2/cameras/${this.selected.exid}/nvr/snapshots/extract`,
          data: {
            start_date: moment(this.fromDateTime).format(),
            end_date: moment(this.toDateTime).format(),
            schedule: this.schedule,
            interval: this.interval,
            create_mp4: this.create_mp4,
            inject_to_cr: this.inject_to_cr,
            jpegs_to_dropbox: this.jpegs_to_dropbox,
            requester: this.$root.user.email,
            api_key: this.selected.api_key,
            api_id: this.selected.api_id
          }
        }).then(response => {
          if (response.status == 201) {
            this.showSuccessMsg({
              title: "Success",
              message: "Snapshot Extractor has been added (Local)!"
            });

            this.$events.fire('se-added', {})
            this.clearForm()
          } else {
            this.showErrorMsg({
              title: "Error",
              message: "Something went wrong!"
            })
          }
        })

I pass the method, URL and data.. and do a few things in response and in case of error.

How can I reduce that so much code? I have this idea to make an API file for this where, the method will accept, API.get(method, URL, data) and I will have {message, statusCode} in return. and then on the basis of that, I can do other stu7ff.

I tried to follow some documentation online but it didn't work. Is there any suitable way to reduce this code.

Is it even possible to give success and error message as well in API.get or post or delete that it would be very minimal when you send the API request?

2

2 Answers

1
votes

EDIT: so i guess you need something like a class here:

class API {
  static get(url, callback) {
    axios({
      method: "get",
      url: url,
      data: data
    }).then(response => {
      callback(response);
    });
  }
  static post(url, data, callback) {
    axios({
      method: "post",
      url: url,
      data: data
    }).then(response => {
      callback(response);
    });
  }
}

API.post("url", data, response => {
  console.log(response);
});

API.get("url", response => {
  console.log(response);
});
0
votes

I use yamlful You make a .yml file which includes

events:
- method: get
  get: /events/:id

then API calls become

const response = await this.$api.events.get(2)

Furthermore, I inject methods into my context

// api.js
async function populateEvents (app, id) {
  const response = await app.$api.events.get(id)
  return response
}

export default ({ app, store }, inject) => {
  inject('populateEvents', id => populateEvents(app, id))
}

// any_file.vue
this.populateEvents(12)

and in api.js you can generalize your api calls, so if any 2 api calls do the same stuff, you can refactor that repeated code into a separate method