social-network
social-network/frontend/utils.mjs
1
import {cognitoLoginUrl, clientId, APIURL} from "./config.mjs";
2
import {timer} from "rxjs";
3
import {appsyncRealtime, persistentSubscription} from "appsync-subscription-observable";
4
5
export const makePaginatedFetcher = (sendQuery, processItem, fieldNames) => (...args) => async (currentPage = undefined, previousPages = []) => {
6
	const [currentItems, nextItems] = await Promise.all([
7
		(async () => {
8
			return {
9
				...currentPage,
10
				[fieldNames.items]: currentPage ? await Promise.all(currentPage[fieldNames.items].map(processItem)) : [],
11
			}
12
		})(),
13
		(async () => {
14
			if (!currentPage || currentPage[fieldNames.nextToken]) {
15
				const nextPage = await sendQuery(currentPage?.[fieldNames.nextToken], previousPages, ...args);
16
				if (nextPage) {
17
					return makePaginatedFetcher(sendQuery, processItem, fieldNames)(...args)(nextPage, [...previousPages, nextPage[fieldNames.items]]);
18
				}
19
			}
20
		})(),
21
	]);
22
	return {
23
		...currentItems,
24
		[fieldNames.items]: [...(currentItems[fieldNames.items] ?? []), ...(nextItems?.[fieldNames.items] ?? [])],
25
		[fieldNames.nextToken]: nextItems ? nextItems[fieldNames.nextToken] : currentItems[fieldNames.nextToken],
26
	}
27
}
28
29
export const sendAppSyncQuery = (getAccessToken) => async (query, variables) => {
30
	const url = new URL(APIURL);
31
	const res = await fetch(APIURL, {
32
		method: "POST",
33
		body: JSON.stringify({
34
			query,
35
			operationName: "MyQuery",
36
			variables,
37
		}),
38
		headers: {
39
			"Content-Type": "application/graphql",
40
			host: url.hostname,
41
			Authorization: await getAccessToken(),
42
		},
43
	});
44
	if (!res.ok) {
45
		throw new Error("Failed");
46
	}
47
	const resJson = await res.json();
48
	if (resJson.errors) {
49
		throw new Error(JSON.stringify(resJson));
50
	}
51
	return resJson.data;
52
};
53
54
export const formatDate = (dateString) => new Intl.DateTimeFormat('en-US', {dateStyle: "medium", timeStyle: "medium"}).format(new Date(dateString));
55
56
export const connection = appsyncRealtime({APIURL, closeDelay: () => timer(6000)});
57
58
export {persistentSubscription, cognitoLoginUrl, clientId, APIURL};
59
60