Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save saiashirwad/98bc2b90f01d1acba341a639a601d68d to your computer and use it in GitHub Desktop.
Save saiashirwad/98bc2b90f01d1acba341a639a601d68d to your computer and use it in GitHub Desktop.
kysely lol
const threads = await ctx.db
.selectFrom("email")
.innerJoin("emailContact", "emailContact.emailId", "email.id")
.select([sql`max(timestamp)`.as("timestamp"), "threadId"])
.select(["emailContact.contactEmailId"])
.select((eb) =>
jsonObjectFrom(
eb
.selectFrom("email as e")
.select(allColumns(Columns.Email, "e"))
.select((eb) =>
jsonArrayFrom(
eb
.selectFrom("emailUser")
.innerJoin("user", "user.email", "emailUser.userEmailId")
.select([
"user.email",
"user.id",
"user.name",
"user.image",
"emailUser.role",
])
.whereRef("emailUser.emailId", "=", "e.id"),
).as("users"),
)
.select((eb) =>
jsonArrayFrom(
eb
.selectFrom("emailAttachment")
.select(
allColumns(Columns.EmailAttachment, "emailAttachment"),
)
.whereRef("emailAttachment.emailId", "=", "e.id"),
).as("attachments"),
)
.whereRef("e.threadId", "=", "email.threadId")
.orderBy("e.timestamp", "desc")
.limit(1),
).as("email"),
)
.where("emailContact.contactEmailId", "=", input.contactEmailId)
.orderBy("timestamp", "desc")
.distinct()
.groupBy(["threadId", "subject"])
.$if(!!input.cursor, (qb) =>
qb.where("email.timestamp", "<=", input.cursor ?? new Date()),
)
.execute();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment