All files / apps/web/src/handlers/user-connection-intentions get-all.ts

100% Statements 12/12
100% Branches 2/2
100% Functions 6/6
100% Lines 12/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80      6x             2x 2x     2x     2x     2x           2x                               2x                   4x 2x                     2x             4x                
import type { PeerId, UserId } from "~db/ids";
import { authProcedure } from "~web/handlers/trpc";
 
export const procedure = authProcedure
	.meta({
		title: "Get all  user connection intentions",
		description:
			"Returns all inbound and outbound  user connection intentions for the current  user.",
	})
	.query(async ({ ctx }) => {
		const { database } = ctx;
		const relatedIntentions = await database
			.selectFrom("peers")
			.innerJoin("users as sourceUsers", (qb) =>
				qb.onRef("peers.ownerUserId", "=", "sourceUsers.id"),
			)
			.innerJoin("users as targetUsers", (qb) =>
				qb.onRef("peers.connectedUserId", "=", "targetUsers.id"),
			)
			.leftJoin("peers as reciprocalPeers", (qb) =>
				qb
					.onRef("reciprocalPeers.ownerUserId", "=", "peers.connectedUserId")
					.onRef("reciprocalPeers.connectedUserId", "=", "peers.ownerUserId"),
			)
			.where("reciprocalPeers.id", "is", null)
			.where((eb) =>
				eb.or([
					eb("peers.ownerUserId", "=", ctx.auth.userId),
					eb("peers.connectedUserId", "=", ctx.auth.userId),
				]),
			)
			.select([
				"peers.ownerUserId as userId",
				"targetUsers.id as targetUserId",
				"peers.id as peerId",
				"peers.name",
				"sourceUsers.email as sourceUserEmail",
				"targetUsers.email as targetUserEmail",
			])
			.orderBy("peers.updatedAt", "desc")
			.orderBy("peers.id")
			.execute();
		return relatedIntentions.reduce<{
			inbound: {
				user: { id: UserId; email: string };
			}[];
			outbound: {
				user: { id: UserId; email: string };
				peer: { id: PeerId; name: string };
			}[];
		}>(
			(acc, intention) => {
				if (intention.userId === ctx.auth.userId) {
					acc.outbound.push({
						user: {
							id: intention.targetUserId,
							email: intention.targetUserEmail,
						},
						peer: {
							id: intention.peerId,
							name: intention.name,
						},
					});
				} else {
					acc.inbound.push({
						user: {
							id: intention.userId,
							email: intention.sourceUserEmail,
						},
					});
				}
				return acc;
			},
			{
				outbound: [],
				inbound: [],
			},
		);
	});