All files / packages/mutations/src/cache/user get.ts

65.21% Statements 15/23
100% Branches 0/0
53.33% Functions 8/15
65.21% Lines 15/23

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                                        39x       39x 2x     39x 4x 4x 4x 4x 4x       39x 6x 6x 4x 2x       39x                                  
import type { User } from "~app/trpc-types";
 
import type {
	ControllerContext,
	ControllerWith,
	SnapshotFn,
	UpdateFn,
} from "../../types";
import {
	applyUpdateFnWithRevert,
	applyWithRevert,
	getUpdatedData,
	withRef,
} from "../utils";
 
type Controller = ControllerWith<{
	procedure: ControllerContext["trpc"]["user"]["get"];
}>;
 
const invalidateUser =
	({ queryClient, procedure }: Controller) =>
	() =>
		queryClient.invalidateQueries(procedure.queryFilter());
 
const upsert = ({ queryClient, procedure }: Controller, user: User) =>
	queryClient.setQueryData(procedure.queryKey(), user);
 
const update =
	({ queryClient, procedure }: Controller) =>
	(updater: UpdateFn<User>) =>
		withRef<User | undefined>((ref) => {
			queryClient.setQueryData(procedure.queryKey(), (user) => {
				ref.current = user;
				return getUpdatedData(user, updater);
			});
		}).current;
 
export const getController = ({ queryClient, trpc }: ControllerContext) => {
	const controller = { queryClient, procedure: trpc.user.get };
	return {
		update: (updater: UpdateFn<User>) => update(controller)(updater),
		upsert: (user: User) => upsert(controller, user),
	};
};
 
export const getRevertController = ({
	queryClient,
	trpc,
}: ControllerContext) => {
	const controller = { queryClient, procedure: trpc.user.get };
	return {
		update: (updater: UpdateFn<User>, revertUpdater: SnapshotFn<User>) =>
			applyUpdateFnWithRevert(update(controller), updater, revertUpdater),
		upsert: (user: User) =>
			applyWithRevert(
				() => upsert(controller, user),
				() => {
					invalidateUser(controller);
				},
			),
	};
};