Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Lf 4671 migrate weather board saga to rtk query #3699

Open
wants to merge 4 commits into
base: integration
Choose a base branch
from

Conversation

gursimran-singh
Copy link
Collaborator

Description

This PR migrates the functionality to RTK query by extending the main API and removes the dependency on saga and slice.

Jira link:https://lite-farm.atlassian.net/browse/LF-4671

Type of change

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update

How Has This Been Tested?

Login with the account and on the home page correct weather is shown.

  • Passes test case
  • UI components visually reviewed on desktop view
  • UI components visually reviewed on mobile view
  • Other (please explain)

Checklist:

  • I have commented my code, particularly in hard-to-understand areas
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes
  • The precommit and linting ran successfully
  • I have added or updated language tags for text that's part of the UI
  • I have added "MISSING" for all new language tags to languages I don't speak
  • I have added the GNU General Public License to all new files

Sorry, something went wrong.

@gursimran-singh gursimran-singh requested review from a team as code owners February 26, 2025 17:54
@gursimran-singh gursimran-singh requested review from Duncan-Brain and kathyavini and removed request for a team February 26, 2025 17:54
Duncan-Brain
Duncan-Brain previously approved these changes Feb 28, 2025
Copy link
Collaborator

@Duncan-Brain Duncan-Brain left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks so much @gursimran-singh I think it looks great to me!

If you are interested in continuing on WeatherBoard we would love to obscure the api call a little more and move it to the backend https://lite-farm.atlassian.net/browse/LF-4281

Copy link
Collaborator

@kathyavini kathyavini left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is so cool Gursimran!!

Thank you for delving into so much uncharted territory and getting us started with the separate files for new endpoints (actually I think we should have started doing this earlier 😅), migrating off of slice + saga (🎉!!) and using RTK Query to interface with an external API. It's great! ☺️

Everything functions well, and my only comments are about how to keep the weatherApi.ts a little bit more parallel to the existing RTK Query endpoints in terms of types and structure. I think a consistent structure will help us a lot with keeping things readable at a glance as you pick up more and more endpoints.

Awesome job -- so exciting to see the great migration underway 😁

@@ -0,0 +1,67 @@
/*
Copy link
Collaborator

@kathyavini kathyavini Feb 28, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm pretty sure we'd like to keep all the endpoint definitions within store/api/ instead of keeping them near their calling component. But I'll double-check with @antsgar when she returns!

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Currently, as per my understanding, we are using feature-based structure where container/feature has all the logic/functionality contained in them, hence creating separate of concerns. Having all the endpoint within store/api folder reflects service-based approach. Are we planning to have mix of both or migrating to service-based structure? let me know and i will change accordingly.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I personally like the separation of concerns Gursimran uses here... but maybe it is something we should have a quick chat about. I thought we just hadn't got around to it yet haha

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's honestly already a mix of things right now. Some things are more feature based where you have the container file, a hook and a saga in the same place. But then there's a specific hooks folder and a specific stories folder. Even the things currently organized by feature aren't currently very easy to find because there's tons of containers and they're not grouped by modules or areas of the app. I personally feel it's a lot more intuitive and harder to go wrong with a structure where we have specific folders for components, hooks, slices, rather than the feature based approach (although I'm not sure I understand why that would be a service-based approach?). So my vote is for keeping these in a store/api folder in an attempt to move towards that direction

Copy link
Collaborator

@Duncan-Brain Duncan-Brain Mar 5, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry I misread as wanting to keep the endpoints in the same file store/api/index not the same folder. I like store/api folder better too. Just appreciating moving endpoints into a specified file aha

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

From a broader perspective, I understand that in feature based approach, both presentation and business logic reside within the same folder/feature, resembling a form of vertical scaling. On contrast, a service based approach follows horizontal scaling, where the business logic is separated from the presentation/ui logic and placed in the folders categorized by services, such as APIs. I am not advocating one approach over the other, as both of the design patterns have their pros and cons, and more importantly is depends upon where the team interest is leveraging towards.

I know mix of these exists and was just confirming as perviously all the business logic(saga, slice, state management) was contained in the same folder and now we are moving these to separate one. It’s good to have these discussion/talks early on, as they help establish a clear direction for the rest of the migration process. Now I got the clarity and will implement this.

export const weatherApi = api.injectEndpoints({
endpoints: (build) => ({
getWeather: build.query({
queryFn: async (arg) => {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I know it's only called only in a JS file, but since all our API endpoints will be written in TS, it would be great to keep type safety. In this case, the return type can be inferred, but the parameters cannot so at least those could be typed explicitly:

interface WeatherQueryArgs {
  lat: number;
  lon: number;
  measurement: string;
}

BUT to keep consistency with all our other RTK query endpoints and for the clearest documentation, it would actually be ideal if we could keep this format and type both return and params:

getWeather: build.query<WeatherData, WeatherQueryArgs>({

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure, i will implement this.

}

try {
const response = await axios.get(openWeatherUrl.toString());
Copy link
Collaborator

@kathyavini kathyavini Feb 28, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

RTK Query manages its own fetching so it would be cleaner and more like the other endpoints to use query instead of queryFn and you wouldn't need axios or the error handling (try/catch) as that is all built-in (unless there is a particular reason it's necessary to use axios for this endpoint)

query: ({ lat, lon, measurement }) => {
  const apikey = import.meta.env.VITE_WEATHER_API_KEY;
  const params = new URLSearchParams({
    lat: String(lat),
   // ...
  });

  return `https://api.openweathermap.org/data/2.5/weather?${params.toString()}`;
},

We haven't used it yet in app, but I think the best RTK Query pattern for the returned data would then be transformResponse:

transformResponse: (response: any /* optional to type their API response */) => {
 const weatherPayload = {
   humidity: `${response.main?.humidity}%`,
  // ...
 };

 return weatherPayload;

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The only reason was query generates CORS error and { axios } from '../saga' had already figured out. Nevertheless, as we are moving API call to open weather to the backend, this whole thing would be changed. https://lite-farm.atlassian.net/browse/LF-4281

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@gursimran-singh you are getting a CORS error (from openweathermap?) by using query on this endpoint? That's really weird... I tried it with the code above and it worked fine.

True about the backend migration for this endpoint. I was thinking more about the pattern going forward with the RTK migration in general since this is the first of many.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree that we should as far as possible use RTK Query's built in functionality for fetching rather than Axios. I'd imagine that long term once we have migrated all of the frontend to RTK Query we'd be able to get rid of Axios as a dependency altogether

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Screenshot 2025-03-09 at 7 35 14 PM

This is the CORS error i get after using the following code:

getWeather: build.query({
      query: () => 'https://api.openweathermap.org/data/2.5/weather?units=metric&lang=en&lat=52.08089409999999&lon=-106.6206944&appid=332adfb0a45a2d6ac05f65e3106a3890&cnt=1',
      providesTags: ['Weather'],
    }),

As we won't be calling the API directly from the frontend and moving the logic to backend, will see if this error occurs there and get back you if needed.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@gursimran-singh isn't the API key param missing in that request?

Copy link
Collaborator Author

@gursimran-singh gursimran-singh Mar 14, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@antsgar Actually appid param uses the api key in the requestappid=332adfb0a45a2d6ac05f65e3106a3890. This is how it has been formulated.

@kathyavini kathyavini requested a review from antsgar March 4, 2025 17:42
Copy link
Collaborator

@antsgar antsgar left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@gursimran-singh thank you so much for working on this, and for proactively reaching out to get involved in the migration! Made a few comments but this is great work 🙌

Comment on lines +27 to +29
if (currentTime - data?.lastUpdated > two_hours) {
refetch();
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I haven't tried this before so not sure, but it seems it's possible to control the frequency the query is refetched through RTK Query by setting the keepUnusedDataFor parameter -- which can not only be set api-wide but also for a specific endpoint https://redux-toolkit.js.org/rtk-query/api/createApi#keepunuseddatafor-1

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will check this out!!

@@ -0,0 +1,67 @@
/*
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's honestly already a mix of things right now. Some things are more feature based where you have the container file, a hook and a saga in the same place. But then there's a specific hooks folder and a specific stories folder. Even the things currently organized by feature aren't currently very easy to find because there's tons of containers and they're not grouped by modules or areas of the app. I personally feel it's a lot more intuitive and harder to go wrong with a structure where we have specific folders for components, hooks, slices, rather than the feature based approach (although I'm not sure I understand why that would be a service-based approach?). So my vote is for keeping these in a store/api folder in an attempt to move towards that direction

}

try {
const response = await axios.get(openWeatherUrl.toString());
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree that we should as far as possible use RTK Query's built in functionality for fetching rather than Axios. I'd imagine that long term once we have migrated all of the frontend to RTK Query we'd be able to get rid of Axios as a dependency altogether

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

4 participants