fork of hey-api/openapi-ts because I need some additional things
1import { JsonPipe } from '@angular/common';
2import { Component, effect, inject, signal, viewChild } from '@angular/core';
3import { FormsModule, NgForm } from '@angular/forms';
4import { MatButtonModule } from '@angular/material/button';
5import { MatCardModule } from '@angular/material/card';
6import { MatFormFieldModule } from '@angular/material/form-field';
7import { MatInputModule } from '@angular/material/input';
8import { MatProgressSpinner } from '@angular/material/progress-spinner';
9import { MatSnackBar } from '@angular/material/snack-bar';
10import { injectMutation, injectQuery } from '@tanstack/angular-query-experimental';
11
12import type { Pet } from '../../client';
13import {
14 addPetMutation,
15 getPetByIdOptions,
16 updatePetMutation,
17} from '../../client/@tanstack/angular-query-experimental.gen';
18
19@Component({
20 imports: [
21 JsonPipe,
22 FormsModule,
23 MatButtonModule,
24 MatCardModule,
25 MatFormFieldModule,
26 MatInputModule,
27 MatProgressSpinner,
28 ],
29 selector: 'app-pet-store',
30 standalone: true,
31 styleUrls: ['./pet-store.component.css'],
32 templateUrl: './pet-store.component.html',
33})
34export class PetStoreComponent {
35 #snackbar = inject(MatSnackBar);
36 form = viewChild.required(NgForm);
37
38 petId = signal<Pet['id']>(undefined);
39
40 petState = injectQuery(() => ({
41 enabled: (this.petId() ?? 0) > 0,
42 ...getPetByIdOptions({
43 path: { petId: this.petId()! },
44 }),
45 }));
46
47 addPet = injectMutation(() => ({
48 ...addPetMutation(),
49 onError: (err) => {
50 this.#snackbar.open(err.message);
51 },
52 onSuccess: () => {
53 this.#snackbar.open('Pet added successfully!');
54 },
55 }));
56 updatePet = injectMutation(() => ({
57 ...updatePetMutation(),
58 onError: (err) => {
59 this.#snackbar.open(err.message);
60 },
61 onSuccess: () => {
62 this.#snackbar.open('Pet updated successfully!');
63 },
64 }));
65
66 nextPetState: Partial<Pet> = {};
67
68 constructor() {
69 effect(() => {
70 const err = this.petState.error();
71
72 if (err) {
73 this.#snackbar.open(String(err));
74 }
75 });
76
77 effect(() => {
78 this.nextPetState = { ...this.petState.data() };
79 });
80 }
81
82 getRandomPet() {
83 // random id 1-10
84 this.petId.set(Math.floor(Math.random() * (10 - 1 + 1) + 1));
85 }
86
87 handleUpdatePet = async (event: Event) => {
88 event.preventDefault();
89
90 await this.updatePet.mutateAsync({
91 body: this.nextPetState as Pet,
92 });
93 };
94
95 onSubmit = async (form: NgForm) => {
96 if (!form.valid) {
97 return;
98 }
99
100 await this.addPet.mutateAsync({
101 body: this.nextPetState as Pet,
102 });
103 };
104}