meals-made-easy-app/src/app/shared/components/recipe-comments-list/recipe-comments-list.ts
2026-02-05 18:34:40 -06:00

58 lines
2.3 KiB
TypeScript

import { Component, computed, inject, input } from '@angular/core';
import { FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { RecipeService } from '../../services/RecipeService';
import { injectInfiniteQuery, injectMutation } from '@tanstack/angular-query-experimental';
import { AuthService } from '../../services/AuthService';
import { DateTimeFormatPipe } from '../../pipes/dateTimeFormat.pipe';
import { SliceView } from '../../models/SliceView.model';
import { RecipeComment } from '../../models/RecipeComment.model';
@Component({
selector: 'app-recipe-comments-list',
imports: [ReactiveFormsModule, DateTimeFormatPipe],
templateUrl: './recipe-comments-list.html',
styleUrl: './recipe-comments-list.css',
})
export class RecipeCommentsList {
public readonly recipeUsername = input.required<string>();
public readonly recipeSlug = input.required<string>();
private readonly recipeService = inject(RecipeService);
private readonly authService = inject(AuthService);
protected readonly username = this.authService.username;
protected readonly isLoggedIn = computed(() => !!this.authService.accessToken());
protected commentsQuery = injectInfiniteQuery(() => ({
initialPageParam: 0,
getNextPageParam: (previousPage: SliceView<RecipeComment>) =>
previousPage.slice.hasNext ? previousPage.slice.number + 1 : undefined,
queryKey: ['recipeComments', this.recipeUsername(), this.recipeSlug()],
queryFn: ({ pageParam }) => {
return this.recipeService.getComments(this.recipeUsername(), this.recipeSlug(), {
page: pageParam,
size: 10,
sort: [
{
property: 'created',
order: 'DESC',
},
],
});
},
}));
protected readonly addCommentForm = new FormGroup({
comment: new FormControl('', Validators.required),
});
protected readonly addCommentMutation = injectMutation(() => ({
mutationFn: (commentText: string) =>
this.recipeService.addComment(this.recipeUsername(), this.recipeSlug(), commentText),
}));
protected onCommentSubmit() {
this.addCommentMutation.mutate(this.addCommentForm.value.comment!);
}
}