Skip to content
Snippets Groups Projects
FAQService.ts 1.27 KiB
Newer Older
Ramiro's avatar
Ramiro committed
import { Op } from 'sequelize';
Ramiro's avatar
Ramiro committed
import { FAQDTO } from '../DTOs/FAQDTO';
Ramiro's avatar
Ramiro committed
import FAQ from '../Models/FAQ';
Ramiro's avatar
Ramiro committed

const list = (): Promise<FAQ[]> => FAQ.findAll({
Ramiro's avatar
Ramiro committed
  attributes: ['id', 'question', 'answer', 'position', 'createdAt'],
Ramiro's avatar
Ramiro committed
  where: {
    deletedAt: null,
  },
Ramiro's avatar
Ramiro committed
  order: ['position'],
Ramiro's avatar
Ramiro committed
});

const create = (createDto: FAQDTO): Promise<FAQ> => FAQ.create(createDto);

const update = async (id: number, createDto: FAQDTO): Promise<FAQ | null> => {
  const faq: FAQ | null = await FAQ.findOne({
    where: {
      id,
      deletedAt: null,
    },
  });
  if (!faq) {
    return null;
  }
Ramiro's avatar
Ramiro committed
  const { question, answer, position } = createDto;
  const positionFaq: FAQ | null = await FAQ.findOne({
    where: {
      id: {
        [Op.ne]: id,
      },
      position,
      deletedAt: null,
    },
  });
  if (positionFaq) {
    return null;
  }
Ramiro's avatar
Ramiro committed
  return faq.update({
Ramiro's avatar
Ramiro committed
    question, answer, position,
Ramiro's avatar
Ramiro committed
  });
};

const deleteFAQ = async (id: number): Promise<boolean> => {
  const faq: FAQ | null = await FAQ.findOne({
    where: {
      id,
      deletedAt: null,
    },
  });
  if (!faq) {
    return false;
  }
  await faq.update({
    deletedAt: new Date(),
  });
  return true;
};

export default {
  list,
  create,
  update,
  deleteFAQ,
};