88 lines
2.2 KiB
TypeScript
88 lines
2.2 KiB
TypeScript
import { Op } from "sequelize";
|
|
import Hotel from "../models/hotel.model";
|
|
|
|
interface IHotelRepository {
|
|
create(hotel: {name: string, address: string}): Promise<Hotel>;
|
|
retrieveAll(searchParams: {name: string, address: string}): Promise<Hotel[]>;
|
|
retrieveById(hotelId: number): Promise<Hotel | null>;
|
|
update(hotel: Hotel): Promise<number>;
|
|
delete(hotelId: number): Promise<number>;
|
|
deleteAll(): Promise<number>;
|
|
}
|
|
|
|
class HotelRepository implements IHotelRepository {
|
|
async create(hotel: {name: string, address: string}): Promise<Hotel> {
|
|
try {
|
|
return await Hotel.create({
|
|
name: hotel.name,
|
|
address: hotel.address,
|
|
});
|
|
} catch (err) {
|
|
throw new Error("Failed to create Hotel!");
|
|
}
|
|
}
|
|
|
|
async retrieveAll(searchParams: {name?: string, address?: string): Promise<Hotel[]> {
|
|
try {
|
|
let condition: SearchCondition = {};
|
|
|
|
if (searchParams?.name) {
|
|
condition.name = { [Op.like]: `%${searchParams.name}%` };
|
|
}
|
|
|
|
if (searchParams?.address) {
|
|
condition.address = { [Op.like]: `%${searchParams.address}%` };
|
|
}
|
|
return await Hotel.findAll({ where: condition });
|
|
} catch (error) {
|
|
throw new Error("Failed to retrieve Hotels!");
|
|
}
|
|
}
|
|
|
|
async retrieveById(hotelId: number): Promise<Hotel | null> {
|
|
try {
|
|
return await Hotel.findByPk(hotelId);
|
|
} catch (error) {
|
|
throw new Error("Failed to retrieve Hotel!");
|
|
}
|
|
}
|
|
|
|
async update(hotel: Hotel): Promise<number> {
|
|
const { id, name, address } = hotel;
|
|
|
|
try {
|
|
const affectedRows = await Hotel.update(
|
|
{ name, address },
|
|
{ where: { id: id } }
|
|
);
|
|
|
|
return affectedRows[0];
|
|
} catch (error) {
|
|
throw new Error("Failed to update Hotel!");
|
|
}
|
|
}
|
|
|
|
async delete(hotelId: number): Promise<number> {
|
|
try {
|
|
const affectedRows = await Hotel.destroy({ where: { id: hotelId } });
|
|
|
|
return affectedRows;
|
|
} catch (error) {
|
|
throw new Error("Failed to delete Hotel!");
|
|
}
|
|
}
|
|
|
|
async deleteAll(): Promise<number> {
|
|
try {
|
|
return Hotel.destroy({
|
|
where: {},
|
|
truncate: false
|
|
});
|
|
} catch (error) {
|
|
throw new Error("Failed to delete Hotels!");
|
|
}
|
|
}
|
|
}
|
|
|
|
export default new HotelRepository();
|