index.jsx 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. import { baseUrl } from './baseUrl';
  2. import { h, createContext } from 'preact';
  3. import { MqttProvider } from './mqtt';
  4. import produce from 'immer';
  5. import { useContext, useEffect, useReducer } from 'preact/hooks';
  6. export const FetchStatus = {
  7. NONE: 'none',
  8. LOADING: 'loading',
  9. LOADED: 'loaded',
  10. ERROR: 'error',
  11. };
  12. const initialState = Object.freeze({
  13. host: baseUrl,
  14. queries: {},
  15. });
  16. const Api = createContext(initialState);
  17. function reducer(state, { type, payload, meta }) {
  18. switch (type) {
  19. case 'REQUEST': {
  20. const { url, fetchId } = payload;
  21. const data = state.queries[url]?.data || null;
  22. return produce(state, (draftState) => {
  23. draftState.queries[url] = { status: FetchStatus.LOADING, data, fetchId };
  24. });
  25. }
  26. case 'RESPONSE': {
  27. const { url, ok, data, fetchId } = payload;
  28. return produce(state, (draftState) => {
  29. draftState.queries[url] = { status: ok ? FetchStatus.LOADED : FetchStatus.ERROR, data, fetchId };
  30. });
  31. }
  32. default:
  33. return state;
  34. }
  35. }
  36. export function ApiProvider({ children }) {
  37. const [state, dispatch] = useReducer(reducer, initialState);
  38. return (
  39. <Api.Provider value={{ state, dispatch }}>
  40. <MqttWithConfig>{children}</MqttWithConfig>
  41. </Api.Provider>
  42. );
  43. }
  44. function MqttWithConfig({ children }) {
  45. const { data, status } = useConfig();
  46. return status === FetchStatus.LOADED ? <MqttProvider config={data}>{children}</MqttProvider> : children;
  47. }
  48. function shouldFetch(state, url, fetchId = null) {
  49. if ((fetchId && url in state.queries && state.queries[url].fetchId !== fetchId) || !(url in state.queries)) {
  50. return true;
  51. }
  52. const { status } = state.queries[url];
  53. return status !== FetchStatus.LOADING && status !== FetchStatus.LOADED;
  54. }
  55. export function useFetch(url, fetchId) {
  56. const { state, dispatch } = useContext(Api);
  57. useEffect(() => {
  58. if (!shouldFetch(state, url, fetchId)) {
  59. return;
  60. }
  61. async function fetchData() {
  62. await dispatch({ type: 'REQUEST', payload: { url, fetchId } });
  63. const response = await fetch(`${state.host}${url}`);
  64. try {
  65. const data = await response.json();
  66. await dispatch({ type: 'RESPONSE', payload: { url, ok: response.ok, data, fetchId } });
  67. } catch (e) {
  68. await dispatch({ type: 'RESPONSE', payload: { url, ok: false, data: null, fetchId } });
  69. }
  70. }
  71. fetchData();
  72. }, [url, fetchId, state, dispatch]);
  73. if (!(url in state.queries)) {
  74. return { data: null, status: FetchStatus.NONE };
  75. }
  76. const data = state.queries[url].data || null;
  77. const status = state.queries[url].status;
  78. return { data, status };
  79. }
  80. export function useApiHost() {
  81. const { state } = useContext(Api);
  82. return state.host;
  83. }
  84. export function useEvents(searchParams, fetchId) {
  85. const url = `/api/events${searchParams ? `?${searchParams.toString()}` : ''}`;
  86. return useFetch(url, fetchId);
  87. }
  88. export function useEvent(eventId, fetchId) {
  89. const url = `/api/events/${eventId}`;
  90. return useFetch(url, fetchId);
  91. }
  92. export function useConfig(searchParams, fetchId) {
  93. const url = `/api/config${searchParams ? `?${searchParams.toString()}` : ''}`;
  94. return useFetch(url, fetchId);
  95. }
  96. export function useStats(searchParams, fetchId) {
  97. const url = `/api/stats${searchParams ? `?${searchParams.toString()}` : ''}`;
  98. return useFetch(url, fetchId);
  99. }