lego/back-end/src/services/box.service.ts
2024-11-18 14:18:29 +01:00

69 lines
1.7 KiB
TypeScript

import { new_client } from '../db/db_client';
import { Box } from '../types/box';
import { Either, eitherLeft, eitherRight } from '../utils/utils';
type DBBox = {
id_boite: number;
titre_boite: string;
date_boite: string;
};
function db2box(data: DBBox): Box {
const box: Box = {
id: data.id_boite,
title: data.titre_boite,
date: new Date(data.date_boite),
};
return box;
}
const getBox = async (idOrTitle: number | string): Promise<Either<Box, string>> => {
const client = new_client();
await client.connect();
let res;
if (typeof idOrTitle !== 'number') {
res = await client.query("SELECT * FROM boites WHERE titre_boite=$1;", [`${idOrTitle}`]);
} else {
res = await client.query("SELECT * FROM boites WHERE id_boite=$1;", [idOrTitle]);
}
if (res.rows.length === 0) {
await client.end();
return eitherRight<Box, string>("Does not exist.");
}
const box = db2box(res.rows[0]);
await client.end();
return eitherLeft<Box, string>(box);
}
const getAllBoxes = async () => {
const client = new_client();
await client.connect();
const res = await client.query("SELECT * FROM boites");
await client.end();
return res.rows.map(db2box);
}
const getAllBoxesFromDate = async (date: Date) => {
const client = new_client();
await client.connect();
const YYYY = date.getFullYear();
const MM = date.getMonth() + 1;
const DD = date.getDate();
const dateString = `${YYYY}-${MM}-${DD}`;
const res = await client.query("SELECT * FROM boites WHERE date_boite > $1", [dateString]);
await client.end();
return res.rows.map(db2box);
}
const boxService = {
getBox,
getAllBoxes,
getAllBoxesFromDate,
};
export default boxService;