ValidationSrv.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import { backendSrv } from 'app/core/services/backend_srv';
  2. const hitTypes = {
  3. FOLDER: 'dash-folder',
  4. DASHBOARD: 'dash-db',
  5. };
  6. export class ValidationSrv {
  7. rootName = 'general';
  8. validateNewDashboardName(folderId: any, name: string) {
  9. return this.validate(folderId, name, 'A dashboard or a folder with the same name already exists');
  10. }
  11. validateNewFolderName(name?: string) {
  12. return this.validate(0, name, 'A folder or dashboard in the general folder with the same name already exists');
  13. }
  14. private async validate(folderId: any, name: string | undefined, existingErrorMessage: string) {
  15. name = (name || '').trim();
  16. const nameLowerCased = name.toLowerCase();
  17. if (name.length === 0) {
  18. throw {
  19. type: 'REQUIRED',
  20. message: 'Name is required',
  21. };
  22. }
  23. if (folderId === 0 && nameLowerCased === this.rootName) {
  24. throw {
  25. type: 'EXISTING',
  26. message: 'This is a reserved name and cannot be used for a folder.',
  27. };
  28. }
  29. const promises = [];
  30. promises.push(backendSrv.search({ type: hitTypes.FOLDER, folderIds: [folderId], query: name }));
  31. promises.push(backendSrv.search({ type: hitTypes.DASHBOARD, folderIds: [folderId], query: name }));
  32. const res = await Promise.all(promises);
  33. let hits: any[] = [];
  34. if (res.length > 0 && res[0].length > 0) {
  35. hits = res[0];
  36. }
  37. if (res.length > 1 && res[1].length > 0) {
  38. hits = hits.concat(res[1]);
  39. }
  40. for (const hit of hits) {
  41. if (nameLowerCased === hit.title.toLowerCase()) {
  42. throw {
  43. type: 'EXISTING',
  44. message: existingErrorMessage,
  45. };
  46. }
  47. }
  48. return;
  49. }
  50. }
  51. export const validationSrv = new ValidationSrv();