rails / request.js

MIT License
389 stars 28 forks source link

Enhancing Response Handling in request.js Similar to Rails.ajax #70

Closed mateuszbialowas closed 8 months ago

mateuszbialowas commented 8 months ago

Hello,

I'm currently working with Rails.ajax in a Ruby on Rails application and exploring similar functionalities in the request.js library. I'd like to discuss the possibility of handling responses in request.js in a manner akin to how Rails.ajax does.

Here's an example of response handling with Rails.ajax:

Rails.ajax({
  url: this.url,
  type: "GET",
  accept: "application/json",
  data: `auto=${encodeURIComponent(this.valueTarget.value)}`,
  success: (response) => {
    this.autocomplete.list = response.data;
  },
});

In this approach, I'm using a simple success parameter for handling successful responses. My question is: Is there a way to incorporate a similar response handling mechanism in the request.js library?

Currently, in request.js, I handle responses as follows:

get(this.url, {
    responseKind: "json",
    query: {auto: encodeURIComponent(this.valueTarget.value)},
}).then((response) => {
  if (response.ok) {
    response.json().then((result) => {
      this.autocomplete.list = result.data;
    });
  }
});

Is there a more streamlined or efficient method to handle responses in request.js that is similar to the success callback in Rails.ajax? Any guidance or suggestions would be greatly appreciated.

Thank you for your time and assistance.

marcelolx commented 8 months ago

You can write a simple wrapper around request.js to be similar to Rails.ajax, if that is what you want

// NOTE: I didn't test this code
import { FetchRequest } from './fetch_request'

function get (url, options) {
  const request = new FetchRequest('get', url, options)
  request.perform().then(async (response) => {
    if (response.ok) {
      if (typeof options.success === "function") {
        response.json().then((result) => {
          options.success(result, response.status, response);
        }).catch((error) => { // need to handle that })
      }
    } else {
      if (typeof options.error === "function") {
        response.json().then((result) => {
          options.error(result, response.status, response);
        }).catch((error) => { // need to handle that })
      }
    }

    return typeof options.complete === "function" ? options.complete(response, response.status) : undefined;
  })
}

I think that ideally, we want to keep request.js as similar as possible to the Fetch API, so people can just look up Fetch API docs and know how to do HTTP requests... And for those that want to keep it similar to what Rails.ajax did, they can easily write a wrapper around it

mateuszbialowas commented 8 months ago

@marcelolx Thank you