grafana/public/app/features/manage-dashboards/services/ValidationSrv.ts
Leo 27b6b3b3bd
Folder: Replace folderId with folderUid (#58393)
* support folderuid in FolderPicker

* support folderuid in unified alerting

* support folderuid when returning to view mode after editing a panel

* support folderuid when preselecting the folderpicker in dashboard general settings

* support folderuid when saving dashboard

* support folderuid when pre-selecting folderpicker in dashboard form

* support folderuid in routes when loading a dashboard

* support folderuid when saving dashboard json

* support folderuid when validating new dashboard name

* support folderuid when moving dashboard to another folder

* support folderuid on dashboard action buttons

* support folderuid when creating a new dashboard on an empty folder

* support folderuid when showing library panel modal

* support folderuid when saving library panel

* support folderuid when importing dashboard

* fixed broken tests

* use folderuid when importing dashboards

* remove commented line

* fix typo when comparing uid values
2022-11-17 09:22:57 +01:00

66 lines
1.8 KiB
TypeScript

import { backendSrv } from 'app/core/services/backend_srv';
const hitTypes = {
FOLDER: 'dash-folder',
DASHBOARD: 'dash-db',
};
class ValidationError extends Error {
type: string;
constructor(type: string, message: string) {
super(message);
this.type = type;
}
}
export class ValidationSrv {
rootName = 'general';
validateNewDashboardName(folderUid: any, name: string) {
return this.validate(folderUid, name, 'A dashboard or a folder with the same name already exists');
}
validateNewFolderName(name?: string) {
return this.validate(0, name, 'A folder or dashboard in the general folder with the same name already exists');
}
private async validate(folderId: any, name: string | undefined, existingErrorMessage: string) {
name = (name || '').trim();
const nameLowerCased = name.toLowerCase();
if (name.length === 0) {
throw new ValidationError('REQUIRED', 'Name is required');
}
if (folderId === 0 && nameLowerCased === this.rootName) {
throw new ValidationError('EXISTING', 'This is a reserved name and cannot be used for a folder.');
}
const promises = [];
promises.push(backendSrv.search({ type: hitTypes.FOLDER, folderIds: [folderId], query: name }));
promises.push(backendSrv.search({ type: hitTypes.DASHBOARD, folderIds: [folderId], query: name }));
const res = await Promise.all(promises);
let hits: any[] = [];
if (res.length > 0 && res[0].length > 0) {
hits = res[0];
}
if (res.length > 1 && res[1].length > 0) {
hits = hits.concat(res[1]);
}
for (const hit of hits) {
if (nameLowerCased === hit.title.toLowerCase()) {
throw new ValidationError('EXISTING', existingErrorMessage);
}
}
return;
}
}
export const validationSrv = new ValidationSrv();