infoalloggi-monorepo/apps/infoalloggi/src/utils/kysely-helper.ts

64 lines
1.8 KiB
TypeScript
Raw Normal View History

import { isValid } from "date-fns";
2025-08-04 17:45:44 +02:00
import { expressionBuilder } from "kysely";
import { jsonArrayFrom, jsonObjectFrom } from "kysely/helpers/postgres";
2025-08-28 18:27:07 +02:00
import type Database from "~/schemas/Database";
2025-08-04 17:45:44 +02:00
import type { UsersId } from "~/schemas/public/Users";
// export function getMessagesArray() {
// const eb = expressionBuilder<Database, "chats">();
// return jsonArrayFrom(
// eb
// .selectFrom("messages")
// .selectAll("messages")
// .whereRef("messages.chatid", "=", "chats.chatid")
// .leftJoin("users", "users.id", "messages.sender")
// .select(["users.nome as sender_nome", "users.isAdmin as sender_isAdmin"])
// .orderBy("messages.time", "asc"),
// ).as("messagesArray");
// }
2025-08-04 17:45:44 +02:00
export type UserInfoQueryType = {
2025-08-28 18:27:07 +02:00
id: UsersId;
username: string;
email: string;
nome: string | null;
2025-08-04 17:45:44 +02:00
};
export function getUserInfo() {
2025-08-28 18:27:07 +02:00
const eb = expressionBuilder<Database, "chats">();
return jsonObjectFrom(
eb
.selectFrom("users")
.select(["id", "username", "email", "nome"])
.whereRef("users.id", "=", "chats.user_ref"),
).as("userinfo");
2025-08-04 17:45:44 +02:00
}
export function withImages() {
const eb = expressionBuilder<Database, "annunci">();
return jsonArrayFrom(
eb
.selectFrom("images_refs")
.select(["img", "thumb"])
.whereRef("images_refs.codice", "=", "annunci.codice")
.orderBy("images_refs.ordine", "asc"),
).as("images");
}
export function withVideos() {
const eb = expressionBuilder<Database, "annunci">();
return jsonArrayFrom(
eb
.selectFrom("videos_refs")
.select(["video", "thumb"])
.whereRef("videos_refs.codice", "=", "annunci.codice")
.orderBy("videos_refs.ordine", "asc"),
).as("videos");
}
export function parseNullableDateString(str: string | null): Date | null {
if (str === null) {
return null;
}
const date = new Date(str);
return isValid(date) ? date : null;
}