common-cents-api/src/expenses/expenses.service.ts

72 lines
2.3 KiB
TypeScript

import { Injectable } from '@nestjs/common';
import { CreateExpenseDto } from './dto/create-expense.dto';
import { UpdateExpenseDto } from './dto/update-expense.dto';
import { ExpenseDataService } from './expense-data.service';
import { GetExpenseDto } from './dto/get-expense.dto';
import { Temporal } from '@js-temporal/polyfill';
@Injectable()
export class ExpensesService {
public constructor(private expenseDataService: ExpenseDataService) { }
public async findAll(): Promise<GetExpenseDto[]> {
const expenses = await this.expenseDataService.getAll();
return expenses.map(exp => {
return { ...exp, date: Temporal.PlainDate.from(exp.date) };
})
}
public async findById(id: string): Promise<GetExpenseDto> {
const expense = await this.expenseDataService.getById(id);
if (!expense) {
throw new Error('No expense found');
}
return { ...expense, date: Temporal.PlainDate.from(expense.date) };
}
public async create(createExpense: CreateExpenseDto): Promise<GetExpenseDto> {
const date = createExpense.date.toString();
const category = { id: createExpense.categoryId };
const merchant = createExpense.merchantId ? { id: createExpense.merchantId } : undefined;
const tags = createExpense.tagIds?.map(id => {
return { id };
})
const expense = await this.expenseDataService.create({
date,
cents: createExpense.cents,
note: createExpense.note,
category,
merchant,
tags
});
return { ...expense, date: Temporal.PlainDate.from(expense.date) };
}
public async update(updateExpense: UpdateExpenseDto): Promise<GetExpenseDto> {
const date = updateExpense.date.toString();
const category = { id: updateExpense.categoryId };
const merchant = updateExpense.merchantId ? { id: updateExpense.merchantId } : undefined;
const tags = updateExpense.tagIds?.map(id => {
return { id };
})
const expense = await this.expenseDataService.update({
id: updateExpense.id,
date,
cents: updateExpense.cents,
note: updateExpense.note,
category,
merchant,
tags
});
return { ...expense, date: Temporal.PlainDate.from(expense.date) };
}
public async remove(id: string): Promise<void> {
await this.expenseDataService.delete(id);
}
}