Skip to content

Commit 8208d71

Browse files
committed
fix: Fixes tests
1 parent dd57208 commit 8208d71

File tree

5 files changed

+113
-67
lines changed

5 files changed

+113
-67
lines changed
Lines changed: 14 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,16 @@
1-
import { BAD_REQUEST, NO_CONTENT, UNAUTHORIZED } from 'http-status-codes';
2-
import NoModel from 'jscommons/dist/errors/NoModel';
3-
import Unauthorised from 'jscommons/dist/errors/Unauthorised';
4-
import { Warnings } from 'rulr';
5-
import stringToStream from 'string-to-stream';
1+
import { NO_CONTENT } from 'http-status-codes';
62
import getActivityId from '../../expressPresenter/utils/getActivityId';
73
import getEtag from '../../expressPresenter/utils/getEtag';
84
import getProfileId from '../../expressPresenter/utils/getProfileId';
95
import validateVersionHeader from '../../expressPresenter/utils/validateVersionHeader';
10-
import { jsonContentType, xapiHeaderVersion } from '../../utils/constants';
6+
import { xapiHeaderVersion } from '../../utils/constants';
117
import { deleteActivityProfile } from './deleteActivityProfile';
128
import { AuthConfig } from './utils/getAuthConfig/AuthConfig';
139
import { getClient } from './utils/getClient/getClient';
1410
import { FileStorageConfig } from './utils/getFileStorageConfig/FileStorageConfig';
1511
import { MongoRecordStorageConfig } from './utils/getRecordStorageConfig/RecordStorageConfig';
1612
import { TrackingConfig } from './utils/getTrackingConfig/TrackingConfig';
1713
import { HttpRequest, HttpResponse } from './utils/HttpInterfaces';
18-
import { translateWarning } from './utils/translateWarning';
1914

2015
export interface DeleteActivityProfileViaHttpConfig {
2116
readonly authConfig: AuthConfig;
@@ -28,61 +23,18 @@ export async function deleteActivityProfileViaHttp(
2823
config: DeleteActivityProfileViaHttpConfig,
2924
req: HttpRequest,
3025
): Promise<HttpResponse> {
31-
try {
32-
const client = await getClient(config, req.headers.authorization);
33-
validateVersionHeader(req.headers['x-experience-api-version']);
26+
const client = await getClient(config, req.headers.authorization);
27+
validateVersionHeader(req.headers['x-experience-api-version']);
3428

35-
const ifMatch = getEtag(req.headers['if-match']);
36-
const activityId = getActivityId(req.query.activityId);
37-
const profileId = getProfileId(req.query.profileId);
29+
const ifMatch = getEtag(req.headers['if-match']);
30+
const activityId = getActivityId(req.query.activityId);
31+
const profileId = getProfileId(req.query.profileId);
3832

39-
await deleteActivityProfile(config, { activityId, client, profileId, ifMatch });
40-
return {
41-
statusCode: NO_CONTENT,
42-
headers: {
43-
'X-Experience-API-Version': xapiHeaderVersion,
44-
},
45-
};
46-
} catch (err) {
47-
if (err instanceof Unauthorised) {
48-
return {
49-
statusCode: UNAUTHORIZED,
50-
headers: {
51-
'X-Experience-API-Version': xapiHeaderVersion,
52-
'Content-Type': jsonContentType,
53-
},
54-
body: stringToStream(JSON.stringify({
55-
message: 'Unauthorized',
56-
requestId: req.requestId,
57-
})),
58-
};
59-
}
60-
if (err instanceof NoModel) {
61-
return {
62-
statusCode: UNAUTHORIZED,
63-
headers: {
64-
'X-Experience-API-Version': xapiHeaderVersion,
65-
'Content-Type': jsonContentType,
66-
},
67-
body: stringToStream(JSON.stringify({
68-
message: `No ${err.modelName} found`,
69-
requestId: req.requestId,
70-
})),
71-
};
72-
}
73-
if (err instanceof Warnings) {
74-
return {
75-
statusCode: BAD_REQUEST,
76-
headers: {
77-
'X-Experience-API-Version': xapiHeaderVersion,
78-
'Content-Type': jsonContentType,
79-
},
80-
body: stringToStream(JSON.stringify({
81-
warnings: err.warnings.map(translateWarning),
82-
requestId: req.requestId,
83-
})),
84-
};
85-
}
86-
throw err;
87-
}
33+
await deleteActivityProfile(config, { activityId, client, profileId, ifMatch });
34+
return {
35+
statusCode: NO_CONTENT,
36+
headers: {
37+
'X-Experience-API-Version': xapiHeaderVersion,
38+
},
39+
};
8840
}

src/apps/activities/_functions/deleteActivityProfile/utils/createExpressHandler.ts

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import express from 'express';
22
import { INTERNAL_SERVER_ERROR } from 'http-status-codes';
33
import { v4 as createV4UUID } from 'uuid';
4-
import { HttpHandler, HttpHeaders, HttpQueryParams } from './HttpInterfaces';
4+
import { handleErrorViaHttp } from './handleErrorViaHttp';
5+
import { HttpHandler, HttpHeaders, HttpQueryParams, HttpRequest } from './HttpInterfaces';
56

67
function getExpressRequestHeaders(req: express.Request) {
78
return Object.keys(req.headers).reduce<HttpHeaders>((result, header) => {
@@ -41,7 +42,10 @@ export function createExpressHandler<Config>(handler: HttpHandler<Config>) {
4142
const body = req;
4243
const headers = getExpressRequestHeaders(req);
4344
const query = getExpressRequestQuery(req);
44-
const response = await handler(config, { requestId, query, body, headers });
45+
const request: HttpRequest = { requestId, query, body, headers };
46+
const response = await handler(config, request).catch((err) => {
47+
return handleErrorViaHttp(request, err);
48+
});
4549
res.writeHead(response.statusCode, response.headers);
4650
if (response.body !== undefined) {
4751
response.body.pipe(res);

src/apps/activities/_functions/deleteActivityProfile/utils/getClient/trackClientUsageInNewRelic.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { TrackingOptions } from './trackClientUsage';
22

3+
/* istanbul ignore next */
34
export async function trackInNewRelic(opts: TrackingOptions) {
45
const newrelic = await import('newrelic');
56
newrelic.addCustomAttribute('org_id', opts.organisationId);

src/apps/activities/_functions/deleteActivityProfile/utils/getFileStorageConfig/getFileStorageConfig.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,14 @@ export function getFileStorageConfig(): FileStorageConfig {
88
azureAccount: config.azureStorageRepo.account,
99
azureAccountKey: config.azureStorageRepo.accountKey,
1010
azureContainerName: config.azureStorageRepo.containerName,
11-
azureSubFolder: config.storageSubFolders.activities,
11+
azureSubFolder: config.azureStorageRepo.subFolder.replace(/^\//, ''),
1212
};
1313
case FileStorageProvider.Google: return {
1414
fileStorageProvider: FileStorageProvider.Google,
1515
googleBucketName: config.googleStorageRepo.bucketName,
1616
googleKeyFileName: config.googleStorageRepo.keyFileName,
1717
googleProjectId: config.googleStorageRepo.projectId,
18-
googleSubFolder: config.storageSubFolders.activities,
18+
googleSubFolder: config.googleStorageRepo.subFolder.replace(/^\//, ''),
1919
};
2020
case FileStorageProvider.S3: return {
2121
fileStorageProvider: FileStorageProvider.S3,
@@ -29,7 +29,7 @@ export function getFileStorageConfig(): FileStorageConfig {
2929
};
3030
default: case FileStorageProvider.Local: return {
3131
fileStorageProvider: FileStorageProvider.Local,
32-
localStorageDir: `${config.localStorageRepo.storageDir}/${config.storageSubFolders.activities}`,
32+
localStorageDir: config.localStorageRepo.storageDir,
3333
};
3434
}
3535
}
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
import {
2+
BAD_REQUEST,
3+
FORBIDDEN,
4+
INTERNAL_SERVER_ERROR,
5+
NOT_FOUND,
6+
PRECONDITION_FAILED,
7+
UNAUTHORIZED,
8+
} from 'http-status-codes';
9+
import Forbidden from 'jscommons/dist/errors/Forbidden';
10+
import NoModel from 'jscommons/dist/errors/NoModel';
11+
import Unauthorised from 'jscommons/dist/errors/Unauthorised';
12+
import { Warnings } from 'rulr';
13+
import stringToStream from 'string-to-stream';
14+
import ExpiredClientError from '../../../errors/ExpiredClientError';
15+
import IfMatch from '../../../errors/IfMatch';
16+
import IfNoneMatch from '../../../errors/IfNoneMatch';
17+
import UntrustedClientError from '../../../errors/UntrustedClientError';
18+
import { jsonContentType, xapiHeaderVersion } from '../../../utils/constants';
19+
import { HttpRequest, HttpResponse } from './HttpInterfaces';
20+
import { translateWarning } from './translateWarning';
21+
22+
function createErrorResponse(statusCode: number, jsonBody: object): HttpResponse {
23+
return {
24+
statusCode,
25+
headers: {
26+
'X-Experience-API-Version': xapiHeaderVersion,
27+
'Content-Type': jsonContentType,
28+
},
29+
body: stringToStream(JSON.stringify(jsonBody)),
30+
};
31+
}
32+
33+
// tslint:disable-next-line: no-any
34+
export function handleErrorViaHttp(req: HttpRequest, err?: any) {
35+
if (err instanceof Unauthorised) {
36+
return createErrorResponse(UNAUTHORIZED, {
37+
message: 'Unauthorized',
38+
requestId: req.requestId,
39+
});
40+
}
41+
if (err instanceof NoModel) {
42+
return createErrorResponse(NOT_FOUND, {
43+
message: `No ${err.modelName} found`,
44+
requestId: req.requestId,
45+
});
46+
}
47+
if (err instanceof Warnings) {
48+
return createErrorResponse(BAD_REQUEST, {
49+
warnings: err.warnings.map(translateWarning),
50+
requestId: req.requestId,
51+
});
52+
}
53+
if (err instanceof IfMatch) {
54+
return createErrorResponse(PRECONDITION_FAILED, {
55+
message: 'IfMatch does not match Etag because a modification has been made since it was retrieved',
56+
requestId: req.requestId,
57+
});
58+
}
59+
if (err instanceof IfNoneMatch) {
60+
return createErrorResponse(PRECONDITION_FAILED, {
61+
message: 'IfNoneMatch was used to detect that the resource was already present',
62+
requestId: req.requestId,
63+
});
64+
}
65+
if (err instanceof Forbidden) {
66+
return createErrorResponse(FORBIDDEN, {
67+
message: 'Forbidden',
68+
requestId: req.requestId,
69+
});
70+
}
71+
if (err instanceof ExpiredClientError) {
72+
return createErrorResponse(FORBIDDEN, {
73+
message: 'Your organisation has expired',
74+
requestId: req.requestId,
75+
});
76+
}
77+
if (err instanceof UntrustedClientError) {
78+
return createErrorResponse(FORBIDDEN, {
79+
message: 'Your client has been disabled',
80+
requestId: req.requestId,
81+
});
82+
}
83+
// tslint:disable-next-line: no-console
84+
console.error(req.requestId, err);
85+
return createErrorResponse(INTERNAL_SERVER_ERROR, {
86+
message: 'A server error occurred',
87+
requestId: req.requestId,
88+
});
89+
}

0 commit comments

Comments
 (0)