Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

portalicious: fix request caching #6007

Merged
merged 1 commit into from
Oct 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 28 additions & 2 deletions interfaces/Portalicious/src/app/domains/domain-api.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,14 @@ import {
HttpWrapperService,
Perform121ServiceRequestParams,
} from '~/services/http-wrapper.service';
import {
PaginateQuery,
PaginateQueryService,
} from '~/services/paginate-query.service';

export abstract class DomainApiService {
protected httpWrapperService = inject(HttpWrapperService);
protected paginateQueryService = inject(PaginateQueryService);
protected queryClient = injectQueryClient();

protected pathToQueryKey = (
Expand All @@ -28,6 +33,7 @@ export abstract class DomainApiService {
processResponse,
requestOptions = {},
method = 'GET',
paginateQuery,
...opts
}: {
path: Parameters<typeof DomainApiService.prototype.pathToQueryKey>[0];
Expand All @@ -37,16 +43,36 @@ export abstract class DomainApiService {
'endpoint' | 'method'
>;
method?: Perform121ServiceRequestParams['method'];
paginateQuery?: Signal<PaginateQuery | undefined>;
} & Partial<UndefinedInitialDataOptions<ProcessedResponseShape>>) {
return () => {
const queryKey = this.pathToQueryKey(path);
const endpoint = queryKey.join('/');

return queryOptions({
...opts,
// eslint-disable-next-line @tanstack/query/exhaustive-deps
queryKey,
queryKey: [
...queryKey,
method,
endpoint,
JSON.stringify(requestOptions),
paginateQuery && paginateQuery(),
processResponse,
],
queryFn: async () => {
if (paginateQuery) {
const { params } = requestOptions;
const paginateQueryParams =
this.paginateQueryService.paginateQueryToHttpParamsObject(
paginateQuery(),
);

requestOptions.params = {
...params,
...paginateQueryParams,
};
}

const response =
await this.httpWrapperService.perform121ServiceRequest<BackendDataShape>(
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { Injectable, Signal } from '@angular/core';

import { DomainApiService } from '~/domains/domain-api.service';
import { ProjectMetrics } from '~/domains/metric/metric.model';

const BASE_ENDPOINT = (projectId: Signal<number>) => [
'programs',
projectId,
'metrics',
];

@Injectable({
providedIn: 'root',
})
export class MetricApiService extends DomainApiService {
getProjectSummaryMetrics(projectId: Signal<number>) {
return this.generateQueryOptions<ProjectMetrics>({
path: [...BASE_ENDPOINT(projectId), 'program-stats-summary'],
});
}

public invalidateCache(projectId: Signal<number>): Promise<void> {
return this.queryClient.invalidateQueries({
queryKey: this.pathToQueryKey(BASE_ENDPOINT(projectId)),
});
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { ProgramStats } from '@121-service/src/metrics/dto/program-stats.dto';

import { Dto } from '~/utils/dto-type';
// TODO: AB#30152 This type should be refactored to use Dto121Service
export type ProjectMetrics = Dto<ProgramStats>;
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { HttpParams } from '@angular/common/http';
import { inject, Injectable, Signal } from '@angular/core';

import { uniqBy } from 'lodash';
Expand All @@ -9,7 +8,6 @@ import {
Attribute,
AttributeWithTranslatedLabel,
Project,
ProjectMetrics,
ProjectUser,
ProjectUserAssignment,
ProjectUserWithRolesLabel,
Expand Down Expand Up @@ -54,12 +52,6 @@ export class ProjectApiService extends DomainApiService {
});
}

getProjectSummaryMetrics(projectId: Signal<number>) {
return this.generateQueryOptions<ProjectMetrics>({
path: [BASE_ENDPOINT, projectId, 'metrics/program-stats-summary'],
});
}

getProjectUsers(projectId: Signal<number>) {
return this.generateQueryOptions<
ProjectUser[],
Expand Down Expand Up @@ -95,23 +87,19 @@ export class ProjectApiService extends DomainApiService {
includeTemplateDefaultAttributes?: boolean;
filterShowInPeopleAffectedTable?: boolean;
}) {
const params = new HttpParams({
fromObject: {
includeCustomAttributes,
includeProgramQuestions,
includeFspQuestions,
includeTemplateDefaultAttributes,
filterShowInPeopleAffectedTable,
},
});

return this.generateQueryOptions<
Attribute[],
AttributeWithTranslatedLabel[]
>({
path: [BASE_ENDPOINT, projectId, 'attributes'],
requestOptions: {
params,
params: {
includeCustomAttributes,
includeProgramQuestions,
includeFspQuestions,
includeTemplateDefaultAttributes,
filterShowInPeopleAffectedTable,
},
},
processResponse: (attributes) => {
return uniqBy(attributes, 'name').map((attribute) => {
Expand Down Expand Up @@ -224,12 +212,10 @@ export class ProjectApiService extends DomainApiService {
'financial-service-providers/intersolve-voucher/vouchers',
],
requestOptions: {
params: new HttpParams({
fromObject: {
referenceId: voucherReferenceId,
payment: paymentId.toString(),
},
}),
params: {
referenceId: voucherReferenceId,
payment: paymentId.toString(),
},
responseAsBlob: true,
},
});
Expand All @@ -244,18 +230,17 @@ export class ProjectApiService extends DomainApiService {
registrationReferenceId: string;
paymentId: number;
}) {
let params = new HttpParams();
params = params.append('referenceId', registrationReferenceId);
params = params.append('payment', paymentId);

return this.generateQueryOptions<number>({
path: [
BASE_ENDPOINT,
projectId,
'financial-service-providers/intersolve-voucher/vouchers/balance',
],
requestOptions: {
params,
params: {
referenceId: registrationReferenceId,
payment: paymentId,
},
},
});
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { ProgramStats } from '@121-service/src/metrics/dto/program-stats.dto';
import { FoundProgramDto } from '@121-service/src/programs/dto/found-program.dto';
import { ProgramController } from '@121-service/src/programs/programs.controller';
import { UserController } from '@121-service/src/user/user.controller';
Expand All @@ -9,9 +8,6 @@ import { ArrayElement } from '~/utils/type-helpers';
// TODO: AB#30152 This type should be refactored to use Dto121Service
export type Project = Dto<FoundProgramDto>;

// TODO: AB#30152 This type should be refactored to use Dto121Service
export type ProjectMetrics = Dto<ProgramStats>;

export type ProjectUser = ArrayElement<
Dto121Service<UserController['getUsersInProgram']>
>;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { HttpParams } from '@angular/common/http';
import { inject, Injectable, Signal } from '@angular/core';
import { Injectable, Signal } from '@angular/core';

import { queryOptions } from '@tanstack/angular-query-experimental';

Expand All @@ -17,10 +16,7 @@ import {
VisaCardAction,
WalletWithCards,
} from '~/domains/registration/registration.model';
import {
PaginateQuery,
PaginateQueryService,
} from '~/services/paginate-query.service';
import { PaginateQuery } from '~/services/paginate-query.service';

const BASE_ENDPOINT = (projectId: Signal<number>) => [
'programs',
Expand All @@ -32,31 +28,14 @@ const BASE_ENDPOINT = (projectId: Signal<number>) => [
providedIn: 'root',
})
export class RegistrationApiService extends DomainApiService {
paginateQueryService = inject(PaginateQueryService);

getManyByQuery(
projectId: Signal<number>,
paginateQuery: Signal<PaginateQuery | undefined>,
) {
return () => {
const path = [...BASE_ENDPOINT(projectId)];

return queryOptions({
queryKey: [path, paginateQuery()],
queryFn: async () =>
this.httpWrapperService.perform121ServiceRequest<FindAllRegistrationsResult>(
{
method: 'GET',
endpoint: this.pathToQueryKey(path).join('/'),
params:
this.paginateQueryService.paginateQueryToHttpParams(
paginateQuery(),
),
},
),
enabled: () => !!paginateQuery(),
});
};
return this.generateQueryOptions<FindAllRegistrationsResult>({
path: [...BASE_ENDPOINT(projectId)],
paginateQuery,
});
}

getRegistrationById(
Expand Down Expand Up @@ -100,7 +79,9 @@ export class RegistrationApiService extends DomainApiService {
]).join('/'),
body,
params:
this.paginateQueryService.paginateQueryToHttpParams(paginateQuery),
this.paginateQueryService.paginateQueryToHttpParamsObject(
paginateQuery,
),
});
}

Expand Down Expand Up @@ -223,11 +204,9 @@ export class RegistrationApiService extends DomainApiService {
return this.httpWrapperService.perform121ServiceRequest({
method: 'PATCH',
endpoint,
params: new HttpParams({
fromObject: {
pause: pauseStatus,
},
}),
params: {
pause: pauseStatus,
},
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
import { InfoTooltipComponent } from '~/components/info-tooltip/info-tooltip.component';
import { PageLayoutComponent } from '~/components/page-layout/page-layout.component';
import { SkeletonInlineComponent } from '~/components/skeleton-inline/skeleton-inline.component';
import { MetricApiService } from '~/domains/metric/metric.api.service';
import { PaymentApiService } from '~/domains/payment/payment.api.service';
import { ProjectApiService } from '~/domains/project/project.api.service';
import { MetricTileComponent } from '~/pages/project-monitoring/components/metric-tile/metric-tile.component';
Expand Down Expand Up @@ -52,13 +53,14 @@ export class ProjectMonitoringPageComponent {
projectId = input.required<number>();

readonly locale = inject(LOCALE_ID);
readonly metricApiService = inject(MetricApiService);
readonly projectApiService = inject(ProjectApiService);
readonly paymentApiService = inject(PaymentApiService);
readonly translatableStringService = inject(TranslatableStringService);

project = injectQuery(this.projectApiService.getProject(this.projectId));
metrics = injectQuery(() => ({
...this.projectApiService.getProjectSummaryMetrics(this.projectId)(),
...this.metricApiService.getProjectSummaryMetrics(this.projectId)(),
enabled: !!this.project.data()?.id,
}));
payments = injectQuery(() => ({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,11 @@ export class CustomMessagePreviewComponent {
private messagingService = inject(MessagingService);

messagePreview = injectQuery(() => ({
queryKey: [this.messageData(), this.projectId, this.previewRegistration],
queryKey: [
this.messageData(),
this.projectId(),
this.previewRegistration(),
],
queryFn: () =>
this.messagingService.getMessagePreview(
this.messageData(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { SkeletonModule } from 'primeng/skeleton';

import { AppRoutes } from '~/app.routes';
import { SkeletonInlineComponent } from '~/components/skeleton-inline/skeleton-inline.component';
import { MetricApiService } from '~/domains/metric/metric.api.service';
import { PaymentApiService } from '~/domains/payment/payment.api.service';
import { ProjectApiService } from '~/domains/project/project.api.service';
import { ProjectMetricContainerComponent } from '~/pages/projects-overview/components/project-metric-container/project-metric-container.component';
Expand All @@ -37,14 +38,15 @@ import { TranslatableStringPipe } from '~/pipes/translatable-string.pipe';
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ProjectSummaryCardComponent {
private metricApiService = inject(MetricApiService);
private projectApiService = inject(ProjectApiService);
private paymentApiService = inject(PaymentApiService);

public id = input.required<number>();

public project = injectQuery(this.projectApiService.getProject(this.id));
public metrics = injectQuery(() => ({
...this.projectApiService.getProjectSummaryMetrics(this.id)(),
...this.metricApiService.getProjectSummaryMetrics(this.id)(),
enabled: !!this.project.data()?.id,
}));
public payments = injectQuery(() => ({
Expand Down
10 changes: 3 additions & 7 deletions interfaces/Portalicious/src/app/services/http-wrapper.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
HttpErrorResponse,
HttpHeaders,
HttpParams,
HttpParamsOptions,
HttpStatusCode,
} from '@angular/common/http';
import { inject, Injectable } from '@angular/core';
Expand All @@ -22,12 +23,7 @@ interface PerformRequestParams {
body?: unknown;
responseAsBlob?: boolean;
isUpload?: boolean;
params?:
| HttpParams
| Record<
string,
boolean | number | readonly (boolean | number | string)[] | string
>;
params?: HttpParamsOptions['fromObject'];
}

export type Perform121ServiceRequestParams = { endpoint: string } & Omit<
Expand Down Expand Up @@ -158,7 +154,7 @@ export class HttpWrapperService {
headers: this.createHeaders(isUpload),
responseType: responseAsBlob ? 'blob' : undefined,
withCredentials: true,
params,
params: new HttpParams({ fromObject: params }),
body,
})
.pipe(
Expand Down
Loading
Loading