All files / apps/web/src/handlers/peers suggest.ts

100% Statements 33/33
100% Branches 12/12
100% Functions 14/14
100% Lines 33/33

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 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142                                        6x                                         6x       15x 15x 15x 15x 3x 3x           3x 1x         2x 2x 1x         1x     1x         1x 1x     13x     13x       1x     1x     12x           13x   1x   12x                       13x     13x     29x       6x 14x 14x 15x       6x                
import { TRPCError } from "@trpc/server";
import { sql } from "kysely";
import { z } from "zod";
 
import {
	directionSchema,
	limitSchema,
	offsetSchema,
	queryNoMinSchema,
} from "~app/utils/validation";
import type { PeerId } from "~db/ids";
import { SIMILARTY_THRESHOLD } from "~utils/server/trigram";
import { queueCallFactory } from "~web/handlers/batch";
import type { AuthorizedContext } from "~web/handlers/context";
import { getAccessRole } from "~web/handlers/receipts/utils";
import { authProcedure } from "~web/handlers/trpc";
import { peerIdSchema, receiptIdSchema } from "~web/handlers/validation";
import type { GeneralOutput } from "~web/utils/batch";
import { queueList } from "~web/utils/batch";
 
const inputSchema = z.strictObject({
	input: queryNoMinSchema,
	cursor: offsetSchema,
	limit: limitSchema,
	filterIds: z.array(peerIdSchema).optional(),
	options: z
		.discriminatedUnion("type", [
			z.strictObject({
				type: z.literal("not-connected"),
			}),
			z.strictObject({
				type: z.literal("not-connected-receipt"),
				receiptId: receiptIdSchema,
			}),
		])
		.optional(),
	direction: directionSchema,
});
type Input = z.infer<typeof inputSchema>;
type Output = GeneralOutput<PeerId> & { count: number };
 
const fetchPage = async (
	{ database, auth }: AuthorizedContext,
	input: Input,
) => {
	let filterIds = [...(input.filterIds || []), auth.userId as PeerId];
	const cursor = input.cursor || 0;
	const options = input.options || { type: "all" };
	if (options.type === "not-connected-receipt") {
		const { receiptId } = options;
		const receipt = await database
			.selectFrom("receipts")
			.select(["id", "ownerUserId"])
			.where("id", "=", receiptId)
			.limit(1)
			.executeTakeFirst();
		if (!receipt) {
			throw new TRPCError({
				code: "NOT_FOUND",
				message: `Receipt "${receiptId}" does not exist.`,
			});
		}
		const accessRole = await getAccessRole(database, receipt, auth.userId);
		if (!accessRole) {
			throw new TRPCError({
				code: "FORBIDDEN",
				message: `Not enough rights to view receipt "${receiptId}".`,
			});
		}
		const peerParticipants = await database
			.selectFrom("receiptParticipants")
			.innerJoin("peers", (jb) =>
				jb.onRef("peers.id", "=", "receiptParticipants.peerId"),
			)
			.where("receiptParticipants.receiptId", "=", options.receiptId)
			.select("peers.id")
			.execute();
		filterIds = [
			...new Set([...filterIds, ...peerParticipants.map(({ id }) => id)]),
		];
	}
	const fuzzyMatchedPeersExpression = database
		.selectFrom("peers")
		.$if(filterIds.length !== 0, (qb) =>
			qb.where("peers.id", "not in", filterIds),
		)
		.where("peers.ownerUserId", "=", auth.userId)
		.$if(options.type === "not-connected", (qb) =>
			qb.where("peers.connectedUserId", "is", null),
		)
		.$if(input.input.length < 3, (qb) =>
			qb.where("name", "ilike", `%${input.input}%`),
		)
		.$if(input.input.length >= 3, (qb) =>
			qb.where(
				sql`strict_word_similarity(${input.input}, name)`.$castTo<number>(),
				">=",
				SIMILARTY_THRESHOLD,
			),
		);
	const [fuzzyMatchedPeers, totalCountPeers] = await Promise.all([
		fuzzyMatchedPeersExpression
			.$if(input.input.length < 3, (qb) => qb.orderBy("name"))
			.$if(input.input.length >= 3, (qb) =>
				qb.orderBy(
					sql`word_similarity(${input.input}, name)`.$castTo(),
					"desc",
				),
			)
			.select(["peers.id"])
			// Stable order for peers with the same name
			.orderBy("peers.id")
			.offset(cursor)
			.limit(input.limit)
			.execute(),
		fuzzyMatchedPeersExpression
			.select([(eb) => eb.fn.count<number>("peers.id").as("count")])
			.executeTakeFirstOrThrow(),
	]);
	return {
		count: totalCountPeers.count,
		cursor,
		items: fuzzyMatchedPeers.map(({ id }) => id),
	};
};
 
const queueSuggestPeerList = queueCallFactory<AuthorizedContext, Input, Output>(
	(ctx) => async (inputs) =>
		queueList<Input, PeerId, Output>(inputs, (values) =>
			fetchPage(ctx, values),
		),
);
 
export const procedure = authProcedure
	.meta({
		title: "Suggest peers",
		description:
			"Returns a page of the current  user's peerIds fuzzy-matched by name against a search query.",
	})
	.input(inputSchema)
	.query(queueSuggestPeerList);