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

FLPATH-752: Adapt FE to use generated OpenApi client #41

Merged
merged 6 commits into from
Nov 27, 2023
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
7 changes: 7 additions & 0 deletions plugins/notifications-frontend/openapitools.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"$schema": "./node_modules/@openapitools/openapi-generator-cli/config.schema.json",
"spaces": 2,
"generator-cli": {
"version": "7.1.0"
}
}
9 changes: 5 additions & 4 deletions plugins/notifications-frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,19 +22,19 @@
"clean": "backstage-cli package clean",
"prepack": "backstage-cli package prepack",
"postpack": "backstage-cli package postpack",
"tsc": "tsc"
"tsc": "tsc",
"openapi:generate": "openapi-generator-cli generate -i ../notifications-backend/src/openapi.yaml --enable-post-process-file -g typescript-fetch -o ./src/openapi && find ./src/openapi -name '*.ts' -exec sed -i '1i // @ts-nocheck' {} \\;"
},
"dependencies": {
"@backstage/core-components": "^0.13.6",
"@backstage/core-plugin-api": "^1.7.0",
"@backstage/theme": "^0.4.3",
"@backstage/plugin-notifications-common": "0.1.0",
"lodash": "^4.17.21",
"@material-table/core": "^3.1.0",
"@material-ui/core": "^4.9.13",
"@material-ui/icons": "^4.11.3",
"@material-ui/lab": "^4.0.0-alpha.45",
"@material-table/core": "^3.1.0",
"@mui/material": "^5.12.2",
"lodash": "^4.17.21",
"react-use": "^17.4.0"
},
"peerDependencies": {
Expand All @@ -46,6 +46,7 @@
"@backstage/core-app-api": "1.11.0",
"@backstage/dev-utils": "1.0.22",
"@backstage/test-utils": "^1.4.4",
"@openapitools/openapi-generator-cli": "^2.7.0",
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^12.1.5",
"@testing-library/user-event": "^14.5.1",
Expand Down
128 changes: 26 additions & 102 deletions plugins/notifications-frontend/src/api/NotificationsApiImpl.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,31 @@
import { ConfigApi, IdentityApi } from '@backstage/core-plugin-api';
import { IdentityApi } from '@backstage/core-plugin-api';

import {
CreateNotificationRequest,
CreateBody,
DefaultConfig,
GetNotificationsRequest,
Notification,
} from '@backstage/plugin-notifications-common';

NotificationsApi as NotificationsOpenApi,
} from '../openapi';
import {
NotificationMarkAsRead,
NotificationsApi,
NotificationsCountQuery,
NotificationsFilter,
NotificationsQuery,
} from './notificationsApi';

export type NotificationsApiOptions = {
configApi: ConfigApi;
identityApi: IdentityApi;
};

export class NotificationsApiImpl implements NotificationsApi {
private readonly backendUrl: string;
private readonly identityApi: IdentityApi;
private readonly backendRestApi: NotificationsOpenApi;

constructor(options: NotificationsApiOptions) {
this.backendUrl = options.configApi.getString('backend.baseUrl');
this.identityApi = options.identityApi;

const configuration = DefaultConfig;
this.backendRestApi = new NotificationsOpenApi(configuration);
}

private async getLogedInUsername(): Promise<string> {
Expand All @@ -34,110 +36,32 @@ export class NotificationsApiImpl implements NotificationsApi {
return userEntityRef.slice('start:'.length - 1);
}

private addFilter(url: URL, user: string, filter: NotificationsFilter) {
url.searchParams.append('user', user);

if (filter.containsText) {
url.searchParams.append('containsText', filter.containsText);
}
if (filter.createdAfter) {
url.searchParams.append(
'createdAfter',
filter.createdAfter.toISOString(),
);
}
if (filter.messageScope) {
url.searchParams.append('messageScope', filter.messageScope);
}
if (filter.isRead !== undefined) {
url.searchParams.append('read', filter.isRead ? 'true' : 'false');
}
}

async post(notification: CreateNotificationRequest): Promise<string> {
const url = new URL(`${this.backendUrl}/api/notifications/notifications`);

const response = await fetch(url.href, {
method: 'POST',
body: JSON.stringify(notification),
headers: { 'Content-Type': 'application/json' },
async createNotification(notification: CreateBody): Promise<string> {
const data = await this.backendRestApi.createNotification({
createBody: notification,
});
const data = await response.json();
if (response.status !== 200 && response.status !== 201) {
throw new Error(data.message || data.error?.message);
}

return Promise.resolve(data.messageId);
return data.messageId;
}

async getNotifications(query: NotificationsQuery): Promise<Notification[]> {
const url = new URL(`${this.backendUrl}/api/notifications/notifications`);
async getNotifications(
query: GetNotificationsRequest,
): Promise<Notification[]> {
const user = await this.getLogedInUsername();

url.searchParams.append('pageSize', `${query.pageSize}`);
url.searchParams.append('pageNumber', `${query.pageNumber}`);

if (query.sorting) {
url.searchParams.append('orderBy', `${query.sorting.fieldName}`);
url.searchParams.append('orderByDirec', `${query.sorting.direction}`);
}

this.addFilter(url, user, query);

const response = await fetch(url.href);
const data = await response.json();
if (response.status !== 200 && response.status !== 201) {
throw new Error(data.message);
}

if (!Array.isArray(data)) {
throw new Error('Unexpected format of notifications received');
}

return data;
return this.backendRestApi.getNotifications({ ...query, user });
}

async getNotificationsCount(query: NotificationsCountQuery): Promise<number> {
const url = new URL(
`${this.backendUrl}/api/notifications/notifications/count`,
);
const user = await this.getLogedInUsername();

this.addFilter(url, user, query);

const response = await fetch(url.href);
const data = await response.json();
if (response.status !== 200 && response.status !== 201) {
throw new Error(data.message);
}

const count = parseInt(data.count, 10);
if (Number.isNaN(count)) {
throw new Error('Unexpected format of notifications count received');
}

return count;
const data = await this.backendRestApi.getNotificationsCount({
...query,
user,
});
return data.count;
}

async markAsRead({
notificationId,
isRead,
}: NotificationMarkAsRead): Promise<void> {
const url = new URL(
`${this.backendUrl}/api/notifications/notifications/read`,
);
async markAsRead(params: NotificationMarkAsRead): Promise<void> {
const user = await this.getLogedInUsername();

url.searchParams.append('read', isRead ? 'true' : 'false');
url.searchParams.append('user', user);
url.searchParams.append('messageId', notificationId);

const response = await fetch(url.href, {
method: 'PUT',
});

if (response.status !== 200 && response.status !== 201) {
throw new Error('Failed to mark the message as read');
}
return this.backendRestApi.setRead({ ...params, user });
}
}
42 changes: 18 additions & 24 deletions plugins/notifications-frontend/src/api/notificationsApi.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,26 @@
import { createApiRef } from '@backstage/core-plugin-api';

import {
CreateNotificationRequest,
CreateBody,
GetNotificationsCountRequest,
GetNotificationsRequest,
Notification,
NotificationsQuerySorting,
} from '@backstage/plugin-notifications-common';

export type NotificationsFilter = {
containsText?: string;
createdAfter?: Date;
messageScope?: 'all' | 'user' | 'system';
isRead?: boolean; // if undefined, include both read and unread
};

export type NotificationsQuery = NotificationsFilter & {
pageSize: number;
pageNumber: number;

sorting?: NotificationsQuerySorting;
};
export type NotificationsCountQuery = NotificationsFilter;

export type NotificationMarkAsRead = {
notificationId: string;
isRead: boolean;
};
SetReadRequest,
} from '../openapi';

export type NotificationsCreateRequest = CreateBody;

export type NotificationsQuery = Omit<GetNotificationsRequest, 'user'>;

export type NotificationsCountQuery = Omit<
GetNotificationsCountRequest,
'user'
>;

export type NotificationMarkAsRead = Omit<SetReadRequest, 'user'>;
export interface NotificationsApi {
/** Create a notification. Returns its new ID. */
post(notification: CreateNotificationRequest): Promise<string>;
createNotification(notification: NotificationsCreateRequest): Promise<string>;

/** Read a list of notifications based on filter parameters. */
getNotifications(query?: NotificationsQuery): Promise<Notification[]>;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import React from 'react';

import { SidebarItem } from '@backstage/core-components';
import { useApi } from '@backstage/core-plugin-api';
import { Notification } from '@backstage/plugin-notifications-common';

import {
IconButton,
Expand All @@ -17,6 +16,7 @@ import NotificationsOffIcon from '@material-ui/icons/NotificationsOff';

import { notificationsApiRef } from '../api';
import { NOTIFICATIONS_ROUTE } from '../constants';
import { Notification } from '../openapi';
import { usePollingEffect } from './usePollingEffect';

const NotificationsErrorIcon = () => (
Expand Down Expand Up @@ -58,7 +58,7 @@ export const NotificationsSidebarItem = ({
try {
setUnreadCount(
await notificationsApi.getNotificationsCount({
isRead: false,
read: false,
messageScope: 'user',
}),
);
Expand All @@ -67,10 +67,8 @@ export const NotificationsSidebarItem = ({
pageSize: 1,
pageNumber: 1,
createdAfter: pageLoadingTime,
sorting: {
fieldName: 'created',
direction: 'desc',
},
orderBy: 'created',
orderByDirec: 'desc',
messageScope: 'system',
});

Expand Down
Loading