All files / apps/web/src/handlers/user-settings update.ts

100% Statements 9/9
100% Branches 3/3
100% Functions 1/1
100% Lines 9/9

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                    6x                           3x 3x 3x       3x   3x             3x 1x           2x                    
import type { Updateable } from "kysely";
import { z } from "zod";
 
import type { DB } from "~db/types.gen";
import { authProcedure } from "~web/handlers/trpc";
 
import { DEFAULT_ACCOUNT_SETTINGS } from "./get";
 
type SettingsUpdateObject = Updateable<DB["userSettings"]>;
 
export const procedure = authProcedure
	.meta({
		title: "Update  user settings",
		description: "Updates a single  user setting for the current  user.",
	})
	.input(
		z.discriminatedUnion("type", [
			z.strictObject({
				type: z.literal("manualAcceptDebts"),
				value: z.boolean(),
			}),
		]),
	)
	.mutation(async ({ ctx, input }) => {
		const { database } = ctx;
		const updateObject: SettingsUpdateObject = {};
		switch (input.type) {
			// We want this to blow up in case we add more cases
			// oxlint-disable-next-line typescript/no-unnecessary-condition
			case "manualAcceptDebts":
				updateObject.manualAcceptDebts = input.value;
		}
		const existingSettings = await database
			.selectFrom("userSettings")
			.where("userSettings.userId", "=", ctx.auth.userId)
			.limit(1)
			.executeTakeFirst();
		// This reads better without ternary
		// oxlint-disable-next-line unicorn/prefer-ternary
		if (existingSettings) {
			await database
				.updateTable("userSettings")
				.set(updateObject)
				.where("userSettings.userId", "=", ctx.auth.userId)
				.executeTakeFirst();
		} else {
			await database
				.insertInto("userSettings")
				.values({
					userId: ctx.auth.userId,
					...DEFAULT_ACCOUNT_SETTINGS,
					...updateObject,
				})
				.executeTakeFirst();
		}
	});