Skip to content

Instantly share code, notes, and snippets.

@imaginamundo
Created April 28, 2024 17:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imaginamundo/d990e63f0aaba7244a173d8fe28f06bb to your computer and use it in GitHub Desktop.
Save imaginamundo/d990e63f0aaba7244a173d8fe28f06bb to your computer and use it in GitHub Desktop.
Schema and query to get user with list of friends
// Schema
export const users = createTable("users", {
id: text("id")
.primaryKey()
.$defaultFn(() => crypto.randomUUID()),
username: text("username").unique().notNull(),
email: text("email").unique().notNull(),
password: text("password").notNull(),
});
export const usersRelations = relations(users, ({ one, many }) => ({
friends: many(userFriends, {
relationName: "user-friends",
}),
}));
export const friendshipStatusEnum = pgEnum("status", ["pending", "accepted", "canceled"]);
export const userFriends = createTable(
"user_friends",
{
id: serial("id").primaryKey(),
requestUserId: text("request_user_id").notNull(),
targetUserId: text("target_user_id").notNull(),
status: friendshipStatusEnum("status").notNull(),
lastUpdate: timestamp("last_update")
.notNull()
.default(sql`CURRENT_TIMESTAMP`),
},
(table) => ({
friends: index("friends_index").on(table.requestUserId, table.targetUserId),
}),
);
export const friendsUserRelations = relations(userFriends, ({ one }) => ({
requestUser: one(users, {
fields: [userFriends.requestUserId],
references: [users.id],
relationName: "requested-friends",
}),
targetUser: one(users, {
fields: [userFriends.targetUserId],
references: [users.id],
relationName: "targeted-friends",
}),
}));
// Query
await db.query.users.findFirst({
where: (user, { eq }) => eq(user.username, username),
with: {
friends: {
where: and(
eq(userFriends.requestUserId, "user id"),
eq(userFriends.targetUserId, "user id"),
ne(userFriends.status, "canceled"),
),
with: {
targetUser: {
with: {
profile: true,
},
},
requestUser: {
with: {
profile: true,
},
},
},
},
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment