index.jsx 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  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 }) {
  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. case 'DELETE': {
  33. const { eventId } = payload;
  34. return produce(state, (draftState) => {
  35. Object.keys(draftState.queries).map((url) => {
  36. draftState.queries[url].deletedId = eventId;
  37. });
  38. });
  39. }
  40. default:
  41. return state;
  42. }
  43. }
  44. export function ApiProvider({ children }) {
  45. const [state, dispatch] = useReducer(reducer, initialState);
  46. return (
  47. <Api.Provider value={{ state, dispatch }}>
  48. <MqttWithConfig>{children}</MqttWithConfig>
  49. </Api.Provider>
  50. );
  51. }
  52. function MqttWithConfig({ children }) {
  53. const { data, status } = useConfig();
  54. return status === FetchStatus.LOADED ? <MqttProvider config={data}>{children}</MqttProvider> : children;
  55. }
  56. function shouldFetch(state, url, fetchId = null) {
  57. if ((fetchId && url in state.queries && state.queries[url].fetchId !== fetchId) || !(url in state.queries)) {
  58. return true;
  59. }
  60. const { status } = state.queries[url];
  61. return status !== FetchStatus.LOADING && status !== FetchStatus.LOADED;
  62. }
  63. export function useFetch(url, fetchId) {
  64. const { state, dispatch } = useContext(Api);
  65. useEffect(() => {
  66. if (!shouldFetch(state, url, fetchId)) {
  67. return;
  68. }
  69. async function fetchData() {
  70. await dispatch({ type: 'REQUEST', payload: { url, fetchId } });
  71. const response = await fetch(`${state.host}${url}`);
  72. try {
  73. const data = await response.json();
  74. await dispatch({ type: 'RESPONSE', payload: { url, ok: response.ok, data, fetchId } });
  75. } catch (e) {
  76. await dispatch({ type: 'RESPONSE', payload: { url, ok: false, data: null, fetchId } });
  77. }
  78. }
  79. fetchData();
  80. }, [url, fetchId, state, dispatch]);
  81. if (!(url in state.queries)) {
  82. return { data: null, status: FetchStatus.NONE };
  83. }
  84. const data = state.queries[url].data || null;
  85. const status = state.queries[url].status;
  86. const deletedId = state.queries[url].deletedId || 0;
  87. return { data, status, deletedId };
  88. }
  89. export function useDelete() {
  90. const { dispatch, state } = useContext(Api);
  91. async function deleteEvent(eventId) {
  92. if (!eventId) return null;
  93. const response = await fetch(`${state.host}/api/events/${eventId}`, { method: 'DELETE' });
  94. await dispatch({ type: 'DELETE', payload: { eventId } });
  95. return await (response.status < 300 ? response.json() : { success: true });
  96. }
  97. return deleteEvent;
  98. }
  99. export function useApiHost() {
  100. const { state } = useContext(Api);
  101. return state.host;
  102. }
  103. export function useEvents(searchParams, fetchId) {
  104. const url = `/api/events${searchParams ? `?${searchParams.toString()}` : ''}`;
  105. return useFetch(url, fetchId);
  106. }
  107. export function useEvent(eventId, fetchId) {
  108. const url = `/api/events/${eventId}`;
  109. return useFetch(url, fetchId);
  110. }
  111. export function useRecording(camera, fetchId) {
  112. const url = `/api/${camera}/recordings`;
  113. return useFetch(url, fetchId);
  114. }
  115. export function useConfig(searchParams, fetchId) {
  116. const url = `/api/config${searchParams ? `?${searchParams.toString()}` : ''}`;
  117. return useFetch(url, fetchId);
  118. }
  119. export function useStats(searchParams, fetchId) {
  120. const url = `/api/stats${searchParams ? `?${searchParams.toString()}` : ''}`;
  121. return useFetch(url, fetchId);
  122. }