@hyper-fetch/firebase 6.0.0 → 7.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,103 +1,105 @@
1
- import { getSocketAdapterBindings } from "@hyper-fetch/sockets";
2
- import { onSnapshot, Firestore, doc, query, collection, disableNetwork, enableNetwork } from "firebase/firestore";
1
+ import { SocketAdapter } from "@hyper-fetch/sockets";
2
+ import {
3
+ collection,
4
+ disableNetwork,
5
+ doc,
6
+ enableNetwork,
7
+ Firestore,
8
+ onSnapshot,
9
+ query,
10
+ QuerySnapshot,
11
+ } from "firebase/firestore";
12
+ import { DocumentSnapshot } from "@firebase/firestore";
3
13
 
4
14
  import { getStatus, isDocOrQuery } from "utils";
5
- import { mapConstraint, getGroupedResultFirestore, getOrderedResultFirestore } from "./utils";
6
- import { FirestoreSocketAdapterType } from "adapter";
15
+ import { getGroupedResultFirestore, getOrderedResultFirestore, mapConstraint } from "./utils";
16
+ import { FirestoreOnSnapshotExtra, FirestoreQueryParams, FirestoreSocketAdapterType } from "adapter";
17
+ import { FirestoreDocOrQuery, FirestoreSnapshotType } from "./firestore.types";
18
+ import { FirestorePermittedMethods } from "../constraints";
7
19
 
8
20
  export const firestoreSockets = (database: Firestore): FirestoreSocketAdapterType => {
9
- return (socket) => {
10
- const {
11
- open,
12
- connecting,
13
- reconnectionAttempts,
14
- listeners,
15
- removeListener,
16
- onConnect,
17
- onReconnect,
18
- onDisconnect,
19
- onListen,
20
- onOpen,
21
- onClose,
22
- onEvent,
23
- onError,
24
- } = getSocketAdapterBindings(socket, { open: true });
21
+ return new SocketAdapter<FirestoreOnSnapshotExtra, undefined, { groupByChangeType?: boolean } & FirestoreQueryParams>(
22
+ {
23
+ name: "firebase-firestore",
24
+ defaultConnected: true,
25
+ },
26
+ ).setConnector(
27
+ ({ socket, onConnect, onReconnect, onDisconnect, onListen, onConnected, onDisconnected, onEvent, onError }) => {
28
+ const connect = async () => {
29
+ const enabled = onConnect();
25
30
 
26
- const connect = () => {
27
- const enabled = onConnect();
31
+ if (enabled) {
32
+ enableNetwork(database);
33
+ onConnected();
34
+ }
35
+ };
28
36
 
29
- if (enabled) {
30
- enableNetwork(database);
31
- onOpen();
32
- }
33
- };
37
+ const disconnect = async () => {
38
+ disableNetwork(database);
39
+ onDisconnect();
40
+ onDisconnected();
41
+ };
34
42
 
35
- const disconnect = () => {
36
- disableNetwork(database);
37
- onDisconnect();
38
- onClose();
39
- };
43
+ const reconnect = () => {
44
+ onReconnect({ disconnect, connect });
45
+ };
40
46
 
41
- const reconnect = () => {
42
- onReconnect(disconnect, connect);
43
- };
47
+ const listen: FirestoreSocketAdapterType["listen"] = (listener, callback) => {
48
+ const fullUrl = socket.url + listener.topic;
49
+ const { options } = listener;
44
50
 
45
- const listen: ReturnType<FirestoreSocketAdapterType>["listen"] = (listener, callback) => {
46
- const fullUrl = socket.url + listener.endpoint;
47
- const { options } = listener;
51
+ let path: any;
52
+ const queryType = isDocOrQuery(fullUrl);
53
+ if (queryType === FirestoreDocOrQuery.DOC) {
54
+ path = doc(database, fullUrl);
55
+ } else {
56
+ const constraints = options?.constraints || [];
57
+ const queryConstraints = constraints.map((constr: FirestorePermittedMethods) => mapConstraint(constr)) || [];
58
+ path = query(collection(database, fullUrl), ...queryConstraints);
59
+ }
60
+ let unsubscribe = () => {};
61
+ let unmount = () => {};
62
+ let clearListeners = () => {};
48
63
 
49
- let path;
50
- const queryType = isDocOrQuery(fullUrl);
51
- if (queryType === "doc") {
52
- path = doc(database, fullUrl);
53
- } else {
54
- const constraints = options?.constraints || [];
55
- const queryConstraints = constraints.map((constr) => mapConstraint(constr)) || [];
56
- path = query(collection(database, fullUrl), ...queryConstraints);
57
- }
58
- let unsubscribe = () => {};
59
- let unmount = () => {};
60
- let clearListeners = () => {};
64
+ unsubscribe = onSnapshot(
65
+ path,
66
+ (snapshot: FirestoreSnapshotType<typeof queryType>) => {
67
+ const getDocData = (s: DocumentSnapshot) => (s.data() ? { ...s.data(), __key: s.id } : null);
68
+ const response =
69
+ queryType === FirestoreDocOrQuery.DOC
70
+ ? getDocData(snapshot as DocumentSnapshot)
71
+ : getOrderedResultFirestore(snapshot as QuerySnapshot);
72
+ const status = getStatus(response);
73
+ const groupedResult =
74
+ options?.groupByChangeType === true ? getGroupedResultFirestore(snapshot as QuerySnapshot) : null;
75
+ const extra = { ref: path, snapshot, groupedResult, status };
76
+ callback({ data: response, extra });
77
+ onEvent({ topic: listener.topic, data: response, extra });
78
+ },
79
+ (error) => {
80
+ onError({ error });
81
+ },
82
+ );
83
+ unmount = onListen({ listener, callback, onUnmount: unsubscribe });
84
+ clearListeners = () => {
85
+ unsubscribe();
86
+ unmount();
87
+ };
61
88
 
62
- unsubscribe = onSnapshot(
63
- path,
64
- (snapshot) => {
65
- const getDocData = (s) => (s.data() ? { ...s.data(), __key: s.id } : null);
66
- const response = queryType === "doc" ? getDocData(snapshot) : getOrderedResultFirestore(snapshot);
67
- const status = getStatus(response);
68
- const groupedResult = options?.groupByChangeType === true ? getGroupedResultFirestore(snapshot) : null;
69
- const extra = { ref: path, snapshot, groupedResult, status };
70
- callback({ data: response, extra });
71
- onEvent(listener.endpoint, response, extra);
72
- },
73
- (error) => {
74
- onError(error);
75
- },
76
- );
77
- unmount = onListen(listener, callback, unsubscribe);
78
- clearListeners = () => {
79
- unsubscribe();
80
- unmount();
89
+ return clearListeners;
81
90
  };
82
91
 
83
- return clearListeners;
84
- };
85
-
86
- const emit = async () => {
87
- throw new Error("Cannot emit from Firestore database socket.");
88
- };
92
+ const emit = async () => {
93
+ throw new Error("Cannot emit from Firestore database socket.");
94
+ };
89
95
 
90
- return {
91
- open,
92
- reconnectionAttempts,
93
- listeners,
94
- connecting,
95
- listen,
96
- removeListener,
97
- emit,
98
- connect,
99
- reconnect,
100
- disconnect,
101
- };
102
- };
96
+ return {
97
+ connect,
98
+ reconnect,
99
+ disconnect,
100
+ listen,
101
+ emit,
102
+ };
103
+ },
104
+ );
103
105
  };
@@ -0,0 +1,11 @@
1
+ import { DocumentSnapshot } from "@firebase/firestore";
2
+ import { QuerySnapshot } from "firebase/firestore";
3
+
4
+ export enum FirestoreDocOrQuery {
5
+ DOC = "doc",
6
+ QUERY = "query",
7
+ }
8
+
9
+ export type FirestoreSnapshotType<T extends FirestoreDocOrQuery> = T extends FirestoreDocOrQuery.DOC
10
+ ? DocumentSnapshot
11
+ : QuerySnapshot;
@@ -1,3 +1,4 @@
1
1
  export * from "./utils";
2
2
  export * from "./firestore.methods";
3
3
  export * from "./firestore.sockets";
4
+ export * from "./firestore.types";
@@ -11,7 +11,7 @@ export const mapConstraint = ({ type, values }: FirestorePermittedMethods) => {
11
11
  }
12
12
  case FirestoreQueryConstraints.ORDER_BY: {
13
13
  const [field, ord] = values;
14
- return orderBy(field, ord as OrderByDirection);
14
+ return orderBy(field as string, ord as OrderByDirection);
15
15
  }
16
16
  case FirestoreQueryConstraints.LIMIT: {
17
17
  const [limitValue] = values;
@@ -1,13 +1,19 @@
1
- export const getOrderedResultFirestore = (snapshot: any) => {
2
- const result = [];
1
+ import { QuerySnapshot, DocumentData } from "@firebase/firestore";
2
+
3
+ export const getOrderedResultFirestore = (snapshot: QuerySnapshot<any>) => {
4
+ const result: (DocumentData & { __key: string })[] = [];
3
5
  snapshot.docs.forEach((d) => {
4
6
  result.push({ ...d.data(), __key: d.id });
5
7
  });
6
- return result.length > 0 ? result : null;
8
+ return result;
7
9
  };
8
10
 
9
- export const getGroupedResultFirestore = (snapshot: any) => {
10
- const groupedResult = { added: [], modified: [], removed: [] };
11
+ export const getGroupedResultFirestore = (snapshot: QuerySnapshot) => {
12
+ const groupedResult: { added: DocumentData[]; modified: DocumentData[]; removed: DocumentData[] } = {
13
+ added: [],
14
+ modified: [],
15
+ removed: [],
16
+ };
11
17
  snapshot.docChanges().forEach((change) => {
12
18
  groupedResult[change.type].push(change.doc.data());
13
19
  });
@@ -1,7 +1,8 @@
1
+ /* eslint-disable max-params */
1
2
  import { Database, get, push, query, ref, remove, set, update } from "firebase/database";
2
- import { RequestInstance } from "@hyper-fetch/core";
3
+ import { getAdapterBindings } from "@hyper-fetch/core";
3
4
 
4
- import { RealtimeDBMethodsUnion } from "adapter/types";
5
+ import { RealtimeDBMethodsUnion, RealtimeDBStatuses } from "adapter/types";
5
6
  import { mapRealtimeConstraint, getOrderedResultRealtime } from "./utils";
6
7
  import { getStatus, isDocOrQuery } from "utils";
7
8
  import {
@@ -11,22 +12,31 @@ import {
11
12
  SharedQueryConstraints,
12
13
  } from "constraints";
13
14
 
14
- export const getRealtimeDbBrowserMethods = <R extends RequestInstance>(
15
- request: R,
16
- database: Database,
17
- url: string,
15
+ type DataType = {
16
+ constraints: PermittedConstraints<RealtimePermittedMethods, RealtimeConstraintsUnion | SharedQueryConstraints>[];
17
+ payload: any;
18
+ options: Record<string, any>;
19
+ };
20
+
21
+ export const getRealtimeDbBrowserMethods = ({
22
+ database,
23
+ url,
18
24
  onSuccess,
19
25
  onError,
20
- resolve,
21
- events: { onResponseStart; onRequestStart; onRequestEnd; onResponseEnd },
22
- ): ((
23
- methodName: RealtimeDBMethodsUnion,
24
- data: {
25
- constraints: PermittedConstraints<RealtimePermittedMethods, RealtimeConstraintsUnion | SharedQueryConstraints>[];
26
- data: any;
27
- options: Record<string, any>;
28
- },
29
- ) => Promise<void>) => {
26
+ onResponseStart,
27
+ onRequestStart,
28
+ onRequestEnd,
29
+ onResponseEnd,
30
+ }: {
31
+ database: Database;
32
+ url: string;
33
+ onSuccess: Awaited<ReturnType<typeof getAdapterBindings>>["onSuccess"];
34
+ onError: Awaited<ReturnType<typeof getAdapterBindings>>["onError"];
35
+ onResponseStart: Awaited<ReturnType<typeof getAdapterBindings>>["onResponseStart"];
36
+ onRequestStart: Awaited<ReturnType<typeof getAdapterBindings>>["onRequestStart"];
37
+ onRequestEnd: Awaited<ReturnType<typeof getAdapterBindings>>["onRequestEnd"];
38
+ onResponseEnd: Awaited<ReturnType<typeof getAdapterBindings>>["onResponseEnd"];
39
+ }): ((methodName: RealtimeDBMethodsUnion, data: DataType) => Promise<void>) => {
30
40
  const [fullUrl] = url.split("?");
31
41
  const path = ref(database, fullUrl);
32
42
  const methods = {
@@ -60,19 +70,26 @@ export const getRealtimeDbBrowserMethods = <R extends RequestInstance>(
60
70
  },
61
71
  };
62
72
 
63
- return async (methodName: RealtimeDBMethodsUnion, data) => {
73
+ return async (methodName: RealtimeDBMethodsUnion, data: DataType) => {
64
74
  try {
65
- events.onRequestStart();
75
+ onRequestStart();
66
76
  const { result, status, extra } = await methods[methodName](data);
67
- events.onRequestEnd();
68
- events.onResponseStart();
69
- onSuccess(result, status, extra, resolve);
70
- events.onResponseEnd();
71
- } catch (e) {
72
- events.onRequestEnd();
73
- events.onResponseStart();
74
- onError(e, "error", {}, resolve);
75
- events.onResponseEnd();
77
+ onRequestEnd();
78
+ onResponseStart();
79
+ onSuccess({ data: result, status: status as RealtimeDBStatuses, extra });
80
+ onResponseEnd();
81
+ } catch (error) {
82
+ onRequestEnd();
83
+ onResponseStart();
84
+ onError({
85
+ error,
86
+ status: "error",
87
+ // TODO - fix this
88
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
89
+ // @ts-ignore
90
+ extra: {},
91
+ });
92
+ onResponseEnd();
76
93
  }
77
94
  };
78
95
  };
@@ -1,96 +1,82 @@
1
- import { getSocketAdapterBindings } from "@hyper-fetch/sockets";
1
+ import { SocketAdapter } from "@hyper-fetch/sockets";
2
2
  import { onValue, query, Database, ref, goOffline, goOnline } from "firebase/database";
3
3
 
4
4
  import { getOrderedResultRealtime, mapRealtimeConstraint } from "./utils";
5
5
  import { getStatus, isDocOrQuery } from "utils";
6
- import { RealtimeSocketAdapterType } from "adapter";
6
+ import { RealtimeDbOnValueMethodExtra, RealtimeDBQueryParams, RealtimeSocketAdapterType } from "adapter";
7
+ import { RealtimePermittedMethods } from "../constraints";
7
8
 
8
9
  export const realtimeSockets = (database: Database): RealtimeSocketAdapterType => {
9
- return (socket) => {
10
- const {
11
- open,
12
- connecting,
13
- reconnectionAttempts,
14
- listeners,
15
- removeListener,
16
- onConnect,
17
- onReconnect,
18
- onDisconnect,
19
- onListen,
20
- onOpen,
21
- onClose,
22
- onEvent,
23
- onError,
24
- } = getSocketAdapterBindings(socket, { open: true });
10
+ return new SocketAdapter<RealtimeDbOnValueMethodExtra, undefined, { onlyOnce?: boolean } & RealtimeDBQueryParams>({
11
+ name: "firebase-realtime",
12
+ defaultConnected: true,
13
+ }).setConnector(
14
+ ({ socket, onConnect, onReconnect, onDisconnect, onListen, onConnected, onDisconnected, onEvent, onError }) => {
15
+ const connect = async () => {
16
+ const enabled = onConnect();
25
17
 
26
- const connect = () => {
27
- const enabled = onConnect();
18
+ if (enabled) {
19
+ goOnline(database);
20
+ onConnected();
21
+ }
22
+ };
28
23
 
29
- if (enabled) {
30
- goOnline(database);
31
- onOpen();
32
- }
33
- };
24
+ const disconnect = async () => {
25
+ goOffline(database);
26
+ onDisconnect();
27
+ onDisconnected();
28
+ };
34
29
 
35
- const disconnect = () => {
36
- goOffline(database);
37
- onDisconnect();
38
- onClose();
39
- };
30
+ const reconnect = () => {
31
+ onReconnect({ disconnect, connect });
32
+ };
40
33
 
41
- const reconnect = () => {
42
- onReconnect(disconnect, connect);
43
- };
34
+ const listen: RealtimeSocketAdapterType["listen"] = (listener, callback) => {
35
+ const fullUrl = socket.url + listener.topic;
36
+ const path = ref(database, fullUrl);
44
37
 
45
- const listen: ReturnType<RealtimeSocketAdapterType>["listen"] = (listener, callback) => {
46
- const fullUrl = socket.url + listener.endpoint;
47
- const path = ref(database, fullUrl);
38
+ const { options } = listener;
39
+ const onlyOnce = options?.onlyOnce || false;
40
+ const params =
41
+ options?.constraints?.map((constraint: RealtimePermittedMethods) => mapRealtimeConstraint(constraint)) || [];
42
+ const queryConstraints = query(path, ...params);
43
+ let unsubscribe = () => {};
44
+ let unmount = () => {};
45
+ let clearListeners = () => {};
46
+ unsubscribe = onValue(
47
+ queryConstraints,
48
+ (snapshot) => {
49
+ const response = isDocOrQuery(fullUrl) === "doc" ? snapshot.val() : getOrderedResultRealtime(snapshot);
50
+ const status = getStatus(response);
51
+ const extra = { ref: path, snapshot, status };
52
+ callback({ data: response, extra });
53
+ onEvent({ topic: listener.topic, data: response, extra });
54
+ },
55
+ (error) => {
56
+ onError({ error });
57
+ },
58
+ { onlyOnce },
59
+ );
60
+ unmount = onListen({ listener, callback, onUnmount: unsubscribe });
61
+ clearListeners = () => {
62
+ unsubscribe();
63
+ unmount();
64
+ };
48
65
 
49
- const { options } = listener;
50
- const onlyOnce = options?.onlyOnce || false;
51
- const params = options?.constraints?.map((constraint) => mapRealtimeConstraint(constraint)) || [];
52
- const queryConstraints = query(path, ...params);
53
- let unsubscribe = () => {};
54
- let unmount = () => {};
55
- let clearListeners = () => {};
56
- unsubscribe = onValue(
57
- queryConstraints,
58
- (snapshot) => {
59
- const response = isDocOrQuery(fullUrl) === "doc" ? snapshot.val() : getOrderedResultRealtime(snapshot);
60
- const status = getStatus(response);
61
- const extra = { ref: path, snapshot, status };
62
- callback({ data: response, extra });
63
- onEvent(listener.endpoint, response, extra);
64
- },
65
- (error) => {
66
- onError(error);
67
- },
68
- { onlyOnce },
69
- );
70
- unmount = onListen(listener, callback, unsubscribe);
71
- clearListeners = () => {
72
- unsubscribe();
73
- unmount();
66
+ return clearListeners;
74
67
  };
75
68
 
76
- return clearListeners;
77
- };
78
-
79
- const emit = async () => {
80
- throw new Error("Cannot emit from Realtime database socket.");
81
- };
69
+ const emit = async () => {
70
+ throw new Error("Cannot emit from Realtime database socket.");
71
+ };
82
72
 
83
- return {
84
- open,
85
- reconnectionAttempts,
86
- listeners,
87
- connecting,
88
- listen,
89
- removeListener,
90
- emit,
91
- connect,
92
- reconnect,
93
- disconnect,
94
- };
95
- };
73
+ return {
74
+ connect,
75
+ reconnect,
76
+ disconnect,
77
+ listen,
78
+ emit,
79
+ };
80
+ },
81
+ );
96
82
  };
@@ -1,5 +1,7 @@
1
- export const getOrderedResultRealtime = (snapshot: any) => {
2
- const res = [];
1
+ import { DataSnapshot } from "@firebase/database";
2
+
3
+ export const getOrderedResultRealtime = (snapshot: DataSnapshot) => {
4
+ const res: any[] = [];
3
5
  snapshot.forEach((child) => {
4
6
  res.push({ ...child.val(), __key: child.key });
5
7
  });
package/src/utils/misc.ts CHANGED
@@ -1,10 +1,12 @@
1
+ import { FirestoreDocOrQuery } from "../firestore/firestore.types";
2
+
1
3
  export const getStatus = (res: any) => {
2
4
  // Deliberate == instead of ===
3
5
  return (Array.isArray(res) && res.length === 0) || res == null ? "emptyResource" : "success";
4
6
  };
5
7
 
6
- export const isDocOrQuery = (fullUrl: string): string => {
8
+ export const isDocOrQuery = (fullUrl: string): FirestoreDocOrQuery => {
7
9
  const withoutSurroundingSlashes = fullUrl.replace(/^\/|\/$/g, "");
8
10
  const pathElements = withoutSurroundingSlashes.split("/").length;
9
- return pathElements % 2 === 0 ? "doc" : "query";
11
+ return pathElements % 2 === 0 ? FirestoreDocOrQuery.DOC : FirestoreDocOrQuery.QUERY;
10
12
  };
package/tsconfig.json CHANGED
@@ -4,5 +4,5 @@
4
4
  "rootDir": ".",
5
5
  "baseUrl": "./src"
6
6
  },
7
- "exclude": ["dist", "jest.config.ts"]
7
+ "exclude": ["node_modules", "dist", "jest.config.ts", "__tests__"]
8
8
  }