Skip to content

Commit

Permalink
Fix types
Browse files Browse the repository at this point in the history
  • Loading branch information
cnasikas committed Mar 8, 2024
1 parent 746ac55 commit 32b633c
Show file tree
Hide file tree
Showing 14 changed files with 108 additions and 66 deletions.
4 changes: 2 additions & 2 deletions x-pack/plugins/cases/server/client/attachments/bulk_get.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ import {
BulkGetAttachmentsResponseRt,
} from '../../../common/types/api';
import { decodeWithExcessOrThrow } from '../../../common/api';
import { flattenCommentSavedObjects, isSODecoratedError } from '../../common/utils';
import { createCaseError } from '../../common/error';
import { flattenCommentSavedObjects } from '../../common/utils';
import { createCaseError, isSODecoratedError } from '../../common/error';
import type { CasesClientArgs } from '../types';
import { Operations } from '../../authorization';
import type { BulkGetArgs } from './types';
Expand Down
9 changes: 2 additions & 7 deletions x-pack/plugins/cases/server/client/cases/bulk_create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,8 @@ import { CaseSeverity, UserActionTypes } from '../../../common/types/domain';
import { decodeWithExcessOrThrow } from '../../../common/api';

import { Operations } from '../../authorization';
import { createCaseError } from '../../common/error';
import {
flattenCaseSavedObject,
isSODecoratedError,
isSOError,
transformNewCase,
} from '../../common/utils';
import { createCaseError, isSODecoratedError, isSOError } from '../../common/error';
import { flattenCaseSavedObject, transformNewCase } from '../../common/utils';
import type { CasesClient, CasesClientArgs } from '..';
import { LICENSING_CASE_ASSIGNMENT_FEATURE } from '../../common/constants';
import { decodeOrThrow } from '../../../common/api/runtime_types';
Expand Down
4 changes: 2 additions & 2 deletions x-pack/plugins/cases/server/client/cases/bulk_get.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ import type { CaseAttributes } from '../../../common/types/domain';
import type { CasesBulkGetRequest, CasesBulkGetResponse } from '../../../common/types/api';
import { CasesBulkGetResponseRt, CasesBulkGetRequestRt } from '../../../common/types/api';
import { decodeWithExcessOrThrow } from '../../../common/api';
import { createCaseError } from '../../common/error';
import { flattenCaseSavedObject, isSODecoratedError } from '../../common/utils';
import { createCaseError, isSODecoratedError } from '../../common/error';
import { flattenCaseSavedObject } from '../../common/utils';
import type { CasesClientArgs } from '../types';
import { Operations } from '../../authorization';
import type { CaseSavedObjectTransformed } from '../../common/types/case';
Expand Down
15 changes: 7 additions & 8 deletions x-pack/plugins/cases/server/client/cases/delete.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
* 2.0.
*/

import { Boom } from '@hapi/boom';
import pMap from 'p-map';
import { chunk } from 'lodash';
import type { SavedObjectsBulkDeleteObject } from '@kbn/core/server';
Expand All @@ -21,7 +20,7 @@ import {
MAX_DOCS_PER_PAGE,
} from '../../../common/constants';
import type { CasesClientArgs } from '..';
import { createCaseError } from '../../common/error';
import { createCaseError, createCaseErrorFromSOError, isSOError } from '../../common/error';
import type { OwnerEntity } from '../../authorization';
import { Operations } from '../../authorization';
import { createFileEntities, deleteFiles } from '../files';
Expand All @@ -47,13 +46,13 @@ export async function deleteCases(

for (const theCase of cases.saved_objects) {
// bulkGet can return an error.
if (theCase.error != null) {
throw createCaseError({
message: `Failed to delete cases ids: ${JSON.stringify(ids)}: ${theCase.error.error}`,
error: new Boom(theCase.error.message, { statusCode: theCase.error.statusCode }),
logger,
});
if (isSOError(theCase)) {
throw createCaseErrorFromSOError(
theCase.error,
`Failed to delete cases ids: ${JSON.stringify(ids)}`
);
}

entities.set(theCase.id, { id: theCase.id, owner: theCase.attributes.owner });
}

Expand Down
9 changes: 6 additions & 3 deletions x-pack/plugins/cases/server/client/cases/get.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

import type { SavedObjectsResolveResponse } from '@kbn/core/server';
import type { SavedObject, SavedObjectsResolveResponse } from '@kbn/core/server';
import type { AttachmentTotals, Case, CaseAttributes, User } from '../../../common/types/domain';
import type {
AllCategoriesFindRequest,
Expand Down Expand Up @@ -33,7 +33,10 @@ import type { CasesClientArgs } from '..';
import { Operations } from '../../authorization';
import { combineAuthorizedAndOwnerFilter } from '../utils';
import { CasesService } from '../../services';
import type { CaseSavedObjectTransformed } from '../../common/types/case';
import type {
CaseSavedObjectTransformed,
CaseTransformedAttributes,
} from '../../common/types/case';
import { decodeOrThrow } from '../../../common/api/runtime_types';
import { CaseRt } from '../../../common/types/domain';

Expand Down Expand Up @@ -112,7 +115,7 @@ export const getCasesByAlertID = async (
// if there was an error retrieving one of the cases (maybe it was deleted, but the alert comment still existed)
// just ignore it
const validCasesInfo = casesInfo.saved_objects.filter(
(caseInfo) => caseInfo.error === undefined
(caseInfo): caseInfo is SavedObject<CaseTransformedAttributes> => caseInfo.error === undefined
);

ensureSavedObjectsAreAuthorized(
Expand Down
6 changes: 3 additions & 3 deletions x-pack/plugins/cases/server/client/cases/update.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ import {
MAX_USER_ACTIONS_PER_CASE,
} from '../../../common/constants';
import { Operations } from '../../authorization';
import { createCaseError } from '../../common/error';
import { createCaseError, isSOError } from '../../common/error';
import {
createAlertUpdateStatusRequest,
flattenCaseSavedObject,
Expand Down Expand Up @@ -281,7 +281,7 @@ function partitionPatchRequest(
for (const reqCase of patchReqCases) {
const foundCase = casesMap.get(reqCase.id);

if (!foundCase || foundCase.error) {
if (!foundCase || isSOError(foundCase)) {
nonExistingCases.push(reqCase);
} else if (foundCase.version !== reqCase.version) {
conflictedCases.push(reqCase);
Expand Down Expand Up @@ -341,7 +341,7 @@ export const update = async (
* only for read.
*/
const casesMap = myCases.saved_objects.reduce((acc, so) => {
acc.set(so.id, so);
acc.set(so.id, so as CaseSavedObjectTransformed);
return acc;
}, new Map<string, CaseSavedObjectTransformed>());

Expand Down
32 changes: 32 additions & 0 deletions x-pack/plugins/cases/server/common/error.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import { isSOError, isSODecoratedError } from './error';

describe('common utils', () => {
describe('isSOError', () => {
it('returns true if the SO is an error', () => {
expect(isSOError({ error: { statusCode: '404' } })).toBe(true);
});

it('returns false if the SO is not an error', () => {
expect(isSOError({})).toBe(false);
});
});

describe('isSODecoratedError', () => {
it('returns true if the SO error is a decorated error', () => {
// @ts-expect-error: only the isBoom property is required
expect(isSODecoratedError({ isBoom: true })).toBe(true);
});

it('returns false if the SO is not a decorated error', () => {
// @ts-expect-error: only the isBoom property is required
expect(isSODecoratedError({})).toBe(false);
});
});
});
32 changes: 32 additions & 0 deletions x-pack/plugins/cases/server/common/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@
*/

import { Boom, isBoom } from '@hapi/boom';
import type { SavedObjectError } from '@kbn/core-saved-objects-common';
import type { DecoratedError } from '@kbn/core-saved-objects-server';
import type { Logger } from '@kbn/core/server';
import type { SOWithErrors } from './types';

export interface HTTPError extends Error {
statusCode: number;
Expand Down Expand Up @@ -82,3 +85,32 @@ export function createCaseError({

return new CaseError(message, error);
}

export const isSOError = <T>(so: { error?: unknown }): so is SOWithErrors<T> => so.error != null;

export const isSODecoratedError = (
error: SavedObjectError | DecoratedError
): error is DecoratedError => Boolean((error as DecoratedError).isBoom);

export const createCaseErrorFromSOError = (
error: SavedObjectError | DecoratedError,
message: string
) => {
if (isSODecoratedError(error)) {
return createCaseError({
message: `${message}: ${error.output.payload.error}`,
error: new Boom(error.message, {
statusCode: error.output.statusCode,
message: error.output.payload.message,
}),
});
}

return createCaseError({
message: `${message}: ${error.error}`,
error: new Boom(error.message, {
statusCode: error.statusCode,
message: error.message,
}),
});
};
24 changes: 0 additions & 24 deletions x-pack/plugins/cases/server/common/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,8 @@ import {
transformNewCase,
getApplicationRoute,
getCaseViewPath,
isSOError,
countUserAttachments,
isPersistableStateOrExternalReference,
isSODecoratedError,
} from './utils';
import { newCase } from '../routes/api/__mocks__/request_responses';
import { CASE_VIEW_PAGE_TABS } from '../../common/types';
Expand Down Expand Up @@ -1566,28 +1564,6 @@ describe('common utils', () => {
});
});

describe('isSOError', () => {
it('returns true if the SO is an error', () => {
expect(isSOError({ error: { statusCode: '404' } })).toBe(true);
});

it('returns false if the SO is not an error', () => {
expect(isSOError({})).toBe(false);
});
});

describe('isSODecoratedError', () => {
it('returns true if the SO error is a decorated error', () => {
// @ts-expect-error: only the isBoom property is required
expect(isSODecoratedError({ isBoom: true })).toBe(true);
});

it('returns false if the SO is not a decorated error', () => {
// @ts-expect-error: only the isBoom property is required
expect(isSODecoratedError({})).toBe(false);
});
});

describe('countUserAttachments', () => {
it('returns 0 for an empty array', () => {
expect(countUserAttachments([])).toBe(0);
Expand Down
10 changes: 1 addition & 9 deletions x-pack/plugins/cases/server/common/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@ import type {
import { flatMap, uniqWith, xorWith } from 'lodash';
import type { LensServerPluginSetup } from '@kbn/lens-plugin/server';
import { addSpaceIdToPath } from '@kbn/spaces-plugin/common';
import type { SavedObjectError } from '@kbn/core-saved-objects-common';
import type { DecoratedError } from '@kbn/core-saved-objects-server';
import type {
ActionsAttachmentPayload,
AlertAttachmentPayload,
Expand All @@ -43,7 +41,7 @@ import {
OWNER_INFO,
} from '../../common/constants';
import type { CASE_VIEW_PAGE_TABS } from '../../common/types';
import type { AlertInfo, FileAttachmentRequest, SOWithErrors } from './types';
import type { AlertInfo, FileAttachmentRequest } from './types';

import type { UpdateAlertStatusRequest } from '../client/alerts/types';
import {
Expand Down Expand Up @@ -475,12 +473,6 @@ export const getCaseViewPath = (params: {
return `${basePath}${normalizePath(CASE_VIEW_PATH.replace(':detailName', caseId))}`;
};

export const isSOError = <T>(so: { error?: unknown }): so is SOWithErrors<T> => so.error != null;

export const isSODecoratedError = (
error: SavedObjectError | DecoratedError
): error is DecoratedError => Boolean((error as DecoratedError).isBoom);

export const countUserAttachments = (
attachments: Array<SavedObject<AttachmentAttributes>>
): number => {
Expand Down
3 changes: 2 additions & 1 deletion x-pack/plugins/cases/server/services/attachments/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import {
FILE_ATTACHMENT_TYPE,
} from '../../../common/constants';
import { buildFilter, combineFilters } from '../../client/utils';
import { defaultSortField, isSOError } from '../../common/utils';
import { defaultSortField } from '../../common/utils';
import type { AggregationResponse } from '../../client/metrics/types';
import {
extractAttachmentSORefsFromAttributes,
Expand Down Expand Up @@ -53,6 +53,7 @@ import {
AttachmentTransformedAttributesRt,
AttachmentPartialAttributesRt,
} from '../../common/types/attachments';
import { isSOError } from '../../common/error';

export class AttachmentService {
private readonly _getter: AttachmentGetter;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import type {
} from '@kbn/core/server';
import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { FILE_SO_TYPE } from '@kbn/files-plugin/common';
import { isSOError } from '../../../common/error';
import { decodeOrThrow } from '../../../../common/api';
import type {
AttachmentPersistedAttributes,
Expand Down Expand Up @@ -42,7 +43,6 @@ import {
import { partitionByCaseAssociation } from '../../../common/partitioning';
import type { AttachmentSavedObject } from '../../../common/types';
import { getCaseReferenceId } from '../../../common/references';
import { isSOError } from '../../../common/utils';

export class AttachmentGetter {
constructor(private readonly context: ServiceContext) {}
Expand Down
20 changes: 16 additions & 4 deletions x-pack/plugins/cases/server/services/cases/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { savedObjectsClientMock } from '@kbn/core/server/mocks';
import type {
SavedObject,
SavedObjectReference,
SavedObjectsBulkResponse,
SavedObjectsCreateOptions,
SavedObjectsFindResponse,
SavedObjectsFindResult,
Expand Down Expand Up @@ -1847,7 +1848,9 @@ describe('CasesService', () => {
],
});

const res = await service.getCases({ caseIds: ['a'] });
const res = (await service.getCases({
caseIds: ['a'],
})) as SavedObjectsBulkResponse<CaseTransformedAttributes>;

expect(res.saved_objects[0].attributes.connector.id).toMatchInlineSnapshot(`"1"`);
expect(
Expand Down Expand Up @@ -1882,7 +1885,10 @@ describe('CasesService', () => {
],
});

const res = await service.getCases({ caseIds: ['a'] });
const res = (await service.getCases({
caseIds: ['a'],
})) as SavedObjectsBulkResponse<CaseTransformedAttributes>;

expect(res.saved_objects[0].attributes.severity).toEqual(CaseSeverity.LOW);
expect(res.saved_objects[1].attributes.severity).toEqual(CaseSeverity.MEDIUM);
expect(res.saved_objects[2].attributes.severity).toEqual(CaseSeverity.HIGH);
Expand All @@ -1907,7 +1913,10 @@ describe('CasesService', () => {
],
});

const res = await service.getCases({ caseIds: ['a'] });
const res = (await service.getCases({
caseIds: ['a'],
})) as SavedObjectsBulkResponse<CaseTransformedAttributes>;

expect(res.saved_objects[0].attributes.status).toEqual(CaseStatuses.open);
expect(res.saved_objects[1].attributes.status).toEqual(CaseStatuses['in-progress']);
expect(res.saved_objects[2].attributes.status).toEqual(CaseStatuses.closed);
Expand All @@ -1922,7 +1931,10 @@ describe('CasesService', () => {
],
});

const res = await service.getCases({ caseIds: ['a'] });
const res = (await service.getCases({
caseIds: ['a'],
})) as SavedObjectsBulkResponse<CaseTransformedAttributes>;

expect(res.saved_objects[0].attributes).not.toHaveProperty('total_alerts');
expect(res.saved_objects[0].attributes).not.toHaveProperty('total_comments');
expect(res.saved_objects[1].attributes).not.toHaveProperty('total_alerts');
Expand Down
4 changes: 2 additions & 2 deletions x-pack/plugins/cases/server/services/cases/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ import type {
SavedObjectsBulkResponseWithErrors,
SOWithErrors,
} from '../../common/types';
import { defaultSortField, flattenCaseSavedObject, isSOError } from '../../common/utils';
import { defaultSortField, flattenCaseSavedObject } from '../../common/utils';
import { DEFAULT_PAGE, DEFAULT_PER_PAGE } from '../../routes/api';
import { combineFilters } from '../../client/utils';
import { includeFieldsRequiredForAuthentication } from '../../authorization/utils';
Expand All @@ -46,7 +46,7 @@ import {
} from './transform';
import type { AttachmentService } from '../attachments';
import type { AggregationBuilder, AggregationResponse } from '../../client/metrics/types';
import { createCaseError } from '../../common/error';
import { createCaseError, isSOError } from '../../common/error';
import type {
CasePersistedAttributes,
CaseSavedObjectTransformed,
Expand Down

0 comments on commit 32b633c

Please sign in to comment.