kal
kal
Explore posts from servers
TTCTheo's Typesafe Cult
Created by kal on 10/19/2024 in #questions
One click image upload form
No description
2 replies
TTCTheo's Typesafe Cult
Created by kal on 7/23/2024 in #questions
Vertical scroll on element with dynamic height
No description
3 replies
DTDrizzle Team
Created by kal on 6/19/2024 in #help
How to properly handle/distinguish between errors
I'm using Drizzle ORM with a postgres. I'd like to distinguish between certain errors that occur when inserting / querying the database. In my current case, I would like to know specifically when my insertion fails as a result of a user not existing in the database. (See the comments in the catch block in the following example)
/**
*
* @param targetID the ID of the user to receive the friend request
*/
async sendUserFriendRequest(targetID: string): Promise<boolean> {
try {
await db
.insert(friends)
.values({
user1_ID: this.userID,
user2_ID: targetID,
status: "pending",
})
.onConflictDoNothing({ target: [friends.user1_ID, friends.user2_ID] });

log("social").debug(
`user ${this.userID} sent friend request to user ${targetID}`,
);
} catch (e) {
// if e is caused by targetID user not existing
// return false
// else
log("social").error(
`user '${this.userID}' failed to send friend request to user '${targetID}' %o`,
e,
);
return false;
}

return true;
}
/**
*
* @param targetID the ID of the user to receive the friend request
*/
async sendUserFriendRequest(targetID: string): Promise<boolean> {
try {
await db
.insert(friends)
.values({
user1_ID: this.userID,
user2_ID: targetID,
status: "pending",
})
.onConflictDoNothing({ target: [friends.user1_ID, friends.user2_ID] });

log("social").debug(
`user ${this.userID} sent friend request to user ${targetID}`,
);
} catch (e) {
// if e is caused by targetID user not existing
// return false
// else
log("social").error(
`user '${this.userID}' failed to send friend request to user '${targetID}' %o`,
e,
);
return false;
}

return true;
}
The error I get when a user does not exist is like so:
{
[message]: 'insert or update on table "friends" violates foreign key constraint "friends_user2_user_id_fk"',
length: 256,
name: 'error',
severity: 'ERROR',
code: '23503',
detail: 'Key (user2)=(hi) is not present in table "user".',
hint: undefined,
position: undefined,
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: 'public',
table: 'friends',
column: undefined,
dataType: undefined,
constraint: 'friends_user2_user_id_fk',
file: 'ri_triggers.c',
line: '2619',
routine: 'ri_ReportViolation'
}
{
[message]: 'insert or update on table "friends" violates foreign key constraint "friends_user2_user_id_fk"',
length: 256,
name: 'error',
severity: 'ERROR',
code: '23503',
detail: 'Key (user2)=(hi) is not present in table "user".',
hint: undefined,
position: undefined,
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: 'public',
table: 'friends',
column: undefined,
dataType: undefined,
constraint: 'friends_user2_user_id_fk',
file: 'ri_triggers.c',
line: '2619',
routine: 'ri_ReportViolation'
}
What is the proper / best way to differentiate between causes of errors while using drizzle?
1 replies
TTCTheo's Typesafe Cult
Created by kal on 6/16/2024 in #questions
TSUP advice - typescript behaving differently after build
I have little experience with building my typescript code into packages that I can then publish and subsequently then download from the npm registry - however that is exactly what I am trying to do right now. After doing some research it seems TSUP is a favourable tool to use to bundle ts into a package. I followed this video from Matt Pocock https://www.youtube.com/watch?v=eh89VE3Mk5g However, when I import my class from the generated dist folder, typescript is not able to infer types correctly. This occurs when I call one of my factory methods, which generates a method that accepts an argument of a type dependant on the argument provided to the factory method. It is hard to explain without an example, so here is a simple one:
import { z } from "zod";
import { WsSchema } from "./dist";

const schema = new WsSchema({
TEST: z.object({}),
MESSAGE: z.string(),
});


// Typescript should infer here that .data() should expect a string argument.

// Typescript is able to do so when the WsSchema class is imported from its source file, but it expects an argument of type 'unkown' when imported from the generated dist

// this should not be valid and typescript should complain here, but it does not when importing from the dist folder
schema.send("MESSAGE").data({})
import { z } from "zod";
import { WsSchema } from "./dist";

const schema = new WsSchema({
TEST: z.object({}),
MESSAGE: z.string(),
});


// Typescript should infer here that .data() should expect a string argument.

// Typescript is able to do so when the WsSchema class is imported from its source file, but it expects an argument of type 'unkown' when imported from the generated dist

// this should not be valid and typescript should complain here, but it does not when importing from the dist folder
schema.send("MESSAGE").data({})
Here is the project repo, this behaviour should be very easily re-creatable if you clone the project and run the build script, and then use the example provided above. https://github.com/FlynnHillier/ws-schema/tree/lib Could anyone advise on why typescript is behaving differently post build? I am nowhere near familiar enough with tsup or publishing in general to know where to start in resolving this - any suggestions are appreciated 🙂
2 replies
TTCTheo's Typesafe Cult
Created by kal on 5/17/2024 in #questions
Include padding bottom when overflow-y-scroll
I have an element that needs to be scrollable. Specifically, this element is the parent element that encapsulates all elements bar my sidebar (im using nextjs, this element is element that encapsulates children in the root layout). I would like that when the element is scrolled, that the bottom padding is also included in the scroll, e.g if we were to scroll all the way down the page, the bottom padding on the element should be visible. Currently, when we scroll all the way down the element, the page cuts off before the bottom padding is displayed. (In the image attached, I have scroll the page all the way down) RootLayout:
import type { Metadata } from "next";
import "./globals.css";
import { SideNavBar } from "./_components/layout/SideNavBar";

export const metadata: Metadata = {
title: "next Chessalyze",
description: "chess with your friends!",
};

export default async function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en" className="h-full">
<head></head>
<body className="bg-stone-700 text-orange-50">
<div className="flex h-screen w-full flex-row ">
<SideNavBar />
<div className="h-full w-full overflow-y-auto p-3 lg:p-5">
{children}
</div>
</div>
</body>
</html>
);
}
import type { Metadata } from "next";
import "./globals.css";
import { SideNavBar } from "./_components/layout/SideNavBar";

export const metadata: Metadata = {
title: "next Chessalyze",
description: "chess with your friends!",
};

export default async function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en" className="h-full">
<head></head>
<body className="bg-stone-700 text-orange-50">
<div className="flex h-screen w-full flex-row ">
<SideNavBar />
<div className="h-full w-full overflow-y-auto p-3 lg:p-5">
{children}
</div>
</div>
</body>
</html>
);
}
39 replies
TTCTheo's Typesafe Cult
Created by kal on 5/4/2024 in #questions
next 14 Showing image fallback on public folder image 404
No description
14 replies
DTDrizzle Team
Created by kal on 4/19/2024 in #help
Infer typescript type from table with relations
No description
4 replies
DTDrizzle Team
Created by kal on 4/11/2024 in #help
How to reference composite key in foreign key
I'm trying to create a foreign key which points to another tables composite primary key. I cannot seem to find anywhere how this is meant to be achieved. I have attached a simplified version of the code I am trying to get to work. As you can see in the moves table I am creating a composite primary key. How do I then reference that in the moveTimestamps table. Also, what should I put in place of varchar in the moveTimestamps table move column, typically I would just match the data type as what it is referencing, but in thise case it should reference both an interger and a varchar.
const moves = pgTable(
"moves",
{
gameID: varchar("game_id")
.notNull()
.references(() => games.id, { onDelete: "cascade" }),
turn: integer("turn").notNull().unique(), },
(table) => {
return {
pk: primaryKey({ name: "id", columns: [table.gameID, table.turn] }),
};
},
);
const moves = pgTable(
"moves",
{
gameID: varchar("game_id")
.notNull()
.references(() => games.id, { onDelete: "cascade" }),
turn: integer("turn").notNull().unique(), },
(table) => {
return {
pk: primaryKey({ name: "id", columns: [table.gameID, table.turn] }),
};
},
);
export const moveTimestamps = pgTable("moveTimestamps", {
move: varchar("move")
.notNull()
.references(() => //!What do i put here!)
.primaryKey(),
});
export const moveTimestamps = pgTable("moveTimestamps", {
move: varchar("move")
.notNull()
.references(() => //!What do i put here!)
.primaryKey(),
});
6 replies
TTCTheo's Typesafe Cult
Created by kal on 4/3/2024 in #questions
next 14 prevent infinite redirects in layout
Hello, I'm creating a chess.com clone - I am attempting to redirect the user if they are currently in a game and they are trying to access any page that is not the 'game page'. Intuitively I thought to do this in a server layout component, so that I can query the serverside game's manager and check if the player is in a game and redirect them if they are. My conditions works, and the user is in fact in a game, they are redirected. However, because they are redirected to a page that is nested within the layout with the redirect condition in, they are redirected again and a redirect cycle begins. How would I go about ensuring that the user is only redirected for this reason once. My initial thought was to do something like if(path !== "/play") redirect("/play") (/play is the page with the game interface on) but I have been having trouble accessing the 'current path' from within the server side layout component. Thanks in advance for any help 🙂
4 replies
TtRPC
Created by kal on 3/26/2024 in #❓-help
Context with trpc ws client
No description
10 replies
TTCTheo's Typesafe Cult
Created by kal on 3/25/2024 in #questions
nextjs 14 TRPC, correctly setting up ws subscriptions
I am using nextJS 14 app router in combination with TRPC. I've been trying to implement TRPC's subscriptions feature to my nextJS app, however I have found that there seems to be very little documentation on the web on how to effectively do this. One resource I did stumble across was this repo maintained by trpc's developers. In it, they have two seperate files prodServer.ts & wssDevServer.ts in src/server/. Ideally there'd only be one file that serves to setup the ws server for both production and development, why is it that they use a separate file for each here? Another problem I have with this is that the wssDevServer file is ran in parallel with the main nextjs script next dev via tsx wssDevServer.ts which means the servers are set up using two sets of configuration (next config under the hood for next dev and tsx for wssDevServer). This causes issues in my app as dependencies which are loaded correctly when the project is ran using next dev, begin encountering various ESM/commonJS mismatch errors when loaded by WSSDevServer, another headache caused by having two servers instead of one. I understand ProdServer.ts does run the ws server on the same server as the next app, however from my understanding this file must be built everytime it is ran, which is obviously not ideal for development. I'd like to be sure I'm implementing TRPC's subscriptions to my nextJS app as effectively as possible, any knowledge is appreciated.
4 replies
TTCTheo's Typesafe Cult
Created by kal on 3/15/2024 in #questions
nextJS trpc subscriptions using createEnv
No description
2 replies