Skip to content

Commit 77ba6c1

Browse files
Merge pull request #31 from contentstack/feat/DX-3457-improve-error-msgs
updated error messages
2 parents e9bc20c + f19a3bd commit 77ba6c1

File tree

6 files changed

+92
-35
lines changed

6 files changed

+92
-35
lines changed

.github/workflows/codeql-analysis.yml

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ jobs:
3838

3939
# Initializes the CodeQL tools for scanning.
4040
- name: Initialize CodeQL
41-
uses: github/codeql-action/init@v2
41+
uses: github/codeql-action/init@v3
4242
with:
4343
languages: ${{ matrix.language }}
4444
# If you wish to specify custom queries, you can do so here or in a config file.
@@ -52,7 +52,7 @@ jobs:
5252
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
5353
# If this step fails, then you should remove it and run the build manually (see below)
5454
- name: Autobuild
55-
uses: github/codeql-action/autobuild@v2
55+
uses: github/codeql-action/autobuild@v3
5656

5757
# ℹ️ Command-line programs to run using the OS shell.
5858
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
@@ -65,4 +65,4 @@ jobs:
6565
# ./location_of_script_within_repo/buildscript.sh
6666

6767
- name: Perform CodeQL Analysis
68-
uses: github/codeql-action/analyze@v2
68+
uses: github/codeql-action/analyze@v3

src/core.ts

Lines changed: 19 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import { debug as Debug } from 'debug';
1212
import { createServer } from 'http';
1313
import { promisify } from 'util';
1414
import { logger as log } from './logger';
15+
import { MESSAGES } from './messages';
1516

1617

1718
let _config: any = {};
@@ -26,25 +27,25 @@ let jsonParser = promisify(bodyParser.json({ limit: '1mb' }));
2627
*/
2728
const requestHandler = (request, response) => {
2829

29-
log.info(`Request recived, '${request.method} : ${request.url}'`);
30+
log.info(MESSAGES.REQUEST_RECEIVED);
3031
debug('_config', _config);
3132
// Explicitly remove or override the X-Powered-By header
3233
response.setHeader('X-Powered-By', '');
3334
return Promise.resolve().then(() => {
3435
// Should be a POST call.
3536
if (request.method && request.method !== 'POST') {
36-
debug('Only POST call is supported.');
37+
debug(MESSAGES.ONLY_POST_SUPPORTED);
3738
return Promise.reject({
38-
body: `Only POST call is supported.`,
39+
body: `Only POST requests are supported.`,
3940
statusCode: 400,
4041
statusMessage: 'Not allowed',
4142
});
4243
}
4344
}).then(() => {
4445
// validate endpoint
45-
debug(`${request.url} invoked`);
46+
debug(MESSAGES.REQUEST_INVOKED(request.url));
4647
if (_config && _config.listener && request.url !== _config.listener.endpoint) {
47-
debug('url authentication failed');
48+
debug(MESSAGES.URL_AUTH_FAILED);
4849
return Promise.reject({
4950
body: `${request.url} not found.`,
5051
statusCode: 404,
@@ -53,12 +54,12 @@ const requestHandler = (request, response) => {
5354
}
5455
}).then(() => {
5556
// verify authorization
56-
debug('validating basic auth', _config.listener);
57+
debug(MESSAGES.VALIDATING_BASIC_AUTH, _config.listener);
5758
if (_config && _config.listener && _config.listener.basic_auth) {
58-
debug('validating basic auth');
59+
debug(MESSAGES.VALIDATING_BASIC_AUTH);
5960
const creds = BasicAuth(request);
6061
if (!creds || (creds.name !== _config.listener.basic_auth.user || creds.pass !== _config.listener.basic_auth.pass)) {
61-
debug('basic auth failed');
62+
debug(MESSAGES.BASIC_AUTH_FAILED);
6263
debug(
6364
'expected %O but received %O',
6465
_config.listener.basic_auth,
@@ -73,12 +74,12 @@ const requestHandler = (request, response) => {
7374
}
7475
}).then(() => {
7576
// validate custom headers
76-
debug('validate custom headers');
77+
debug(MESSAGES.VALIDATING_CUSTOM_HEADERS);
7778
if (_config && _config.listener) {
7879
for (const headerKey in _config.listener.headers) {
79-
debug('validating headers');
80+
debug(MESSAGES.VALIDATING_HEADERS);
8081
if (request.headers[headerKey] !== _config.listener.headers[headerKey]) {
81-
debug(`${headerKey} was not found in req headers`);
82+
debug(MESSAGES.HEADER_NOT_FOUND(headerKey));
8283
return Promise.reject({
8384
body: 'Header key mismatch.',
8485
statusCode: 417,
@@ -88,7 +89,7 @@ const requestHandler = (request, response) => {
8889
}
8990
}
9091
}).then(async () => {
91-
debug('parsing json');
92+
debug(MESSAGES.PARSING_JSON);
9293
try {
9394
if (_config.reqBodyLimit) {
9495
jsonParser = promisify(bodyParser.json({ limit: _config.reqBodyLimit }));
@@ -103,13 +104,13 @@ const requestHandler = (request, response) => {
103104
locale = body.data.locale;
104105
}
105106
debug('_config.listener.actions[type]', _config.listener.actions[type]);
106-
debug('event', event);
107+
debug(MESSAGES.EVENT, event);
107108
// validate event:type
108109
if (
109110
!_config.listener.actions[type] ||
110111
_config.listener.actions[type].indexOf(event) === -1
111112
) {
112-
debug(`${event}:${type} not defined for processing`);
113+
debug(MESSAGES.EVENT_NOT_DEFINED(event, type));
113114
return Promise.reject({
114115
body: `${event}:${type} not defined for processing`,
115116
statusCode: 403,
@@ -137,9 +138,9 @@ const requestHandler = (request, response) => {
137138
}
138139
data.event = event;
139140
_notify(data).then((data) => {
140-
debug('Data [_notify]', data);
141+
debug(MESSAGES.DATA_RECEIVED_NOTIFY, data);
141142
}).catch((error) => {
142-
debug('Error [_notify]', error);
143+
debug(MESSAGES.ERROR_OCCURRED_NOTIFY, error);
143144
});
144145
return Promise.resolve({ statusCode: 200, statusMessage: 'OK', body: data });
145146
} catch (err) {
@@ -150,7 +151,7 @@ const requestHandler = (request, response) => {
150151
});
151152
}
152153
}).then((value) => {
153-
debug('Value', value);
154+
debug(MESSAGES.VALUE, value);
154155
response.setHeader('Content-Type', 'application/json');
155156
response.statusCode = value.statusCode;
156157
response.statusMessage = value.statusMessage;
@@ -162,7 +163,7 @@ const requestHandler = (request, response) => {
162163
response.end(JSON.stringify(safeBody));
163164
return;
164165
}).catch((error) => {
165-
debug('Error', error);
166+
debug(MESSAGES.ERROR, error);
166167
const safeError = {
167168
statusCode: error.statusCode || 500,
168169
statusMessage: error.statusMessage || 'Internal Server Error',

src/index.ts

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import { merge } from 'lodash';
1111
import { createListener } from './core';
1212
import { defaultConfig } from './defaults';
1313
import { logger as log, setLogger } from './logger';
14+
import { MESSAGES } from './messages';
1415

1516
const debug = Debug('webhook:listener');
1617
let notify;
@@ -26,7 +27,7 @@ export function register(consumer: any) {
2627
if (typeof consumer !== 'function') {
2728
throw new Error('Provide function to notify consumer.');
2829
}
29-
debug('register called with %O', notify);
30+
debug(MESSAGES.REGISTER_CALLED, notify);
3031
notify = consumer;
3132
return true;
3233
}
@@ -44,7 +45,7 @@ export function start(userConfig: any, customLogger?: any) {
4445
if (customLogger) {
4546
setLogger(customLogger);
4647
}
47-
debug('start called with %O', userConfig);
48+
debug(MESSAGES.START_CALLED, userConfig);
4849
appConfig = merge(appConfig, userConfig)
4950
validateConfig(appConfig);
5051

@@ -59,10 +60,10 @@ export function start(userConfig: any, customLogger?: any) {
5960
);
6061
}
6162

62-
debug('starting with config: ' + JSON.stringify(appConfig));
63+
debug(MESSAGES.STARTING_WITH_CONFIG(JSON.stringify(appConfig)));
6364
const port = process.env.PORT || appConfig.listener.port;
6465
const server = createListener(appConfig, notify).listen(port, () => {
65-
log.info(`Server running at port ${port}`);
66+
log.info(MESSAGES.SERVER_RUNNING(port));
6667
});
6768
return resolve(server);
6869
} catch (error) {
@@ -102,14 +103,14 @@ function validateConfig(customConfig) {
102103
customConfig.listener.endpoint = '/' + customConfig.listener.endpoint;
103104
}
104105
} else {
105-
throw new TypeError('Please provide valide listener.endpoint');
106+
throw new TypeError(MESSAGES.INVALID_LISTENER_ENDPOINT);
106107
}
107108
}
108109
if (
109110
customConfig.listener.port &&
110111
typeof customConfig.listener.port !== 'number'
111112
) {
112-
throw new TypeError('Please provide valide listener.port');
113+
throw new TypeError(MESSAGES.INVALID_LISTENER_PORT);
113114
}
114115
}
115116
}

src/logger.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { Console } from 'console';
2+
import { MESSAGES } from './messages';
23

34
let logger;
45
logger = new Console(process.stdout, process.stderr);
@@ -11,10 +12,10 @@ logger = new Console(process.stdout, process.stderr);
1112
function setLogger(customLogger) {
1213
const validator = validateLogger(customLogger);
1314
if (!validator) {
14-
console.warn('Failed to register logger, using console for logging.');
15+
console.warn(MESSAGES.LOGGER_REGISTRATION_FAILED);
1516
} else {
1617
logger = customLogger;
17-
logger.info('Logger registered successfully.');
18+
logger.info(MESSAGES.LOGGER_REGISTERED_SUCCESS);
1819
}
1920
}
2021

@@ -26,7 +27,7 @@ const validateLogger = (instance) => {
2627
const requiredFn = ['info', 'warn', 'log', 'error', 'debug'];
2728
requiredFn.forEach((name) => {
2829
if (typeof instance[name] !== 'function') {
29-
console.warn(`Unable to register custom logger since '${name}()' does not exist on ${instance}!`);
30+
console.warn(MESSAGES.UNABLE_TO_REGISTER_LOGGER(name, instance));
3031
flag = true;
3132
}
3233
});

src/messages.ts

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/*!
2+
* contentstack-webhook-listener
3+
* copyright (c) Contentstack LLC
4+
* MIT Licensed
5+
*/
6+
7+
'use strict';
8+
9+
/**
10+
* Centralized messages for the webhook listener.
11+
* This file contains all log messages, debug messages, and error messages
12+
* used throughout the application.
13+
*/
14+
15+
export const MESSAGES = {
16+
// Debug messages for index.ts
17+
REGISTER_CALLED: 'Register called with object: %O',
18+
START_CALLED: 'Start called with object: %O',
19+
STARTING_WITH_CONFIG: (config: string) => `Starting with config: ${config}`,
20+
21+
// Log messages for index.ts
22+
SERVER_RUNNING: (port: string | number) => `Server is running on port ${port}.`,
23+
24+
// Error messages for index.ts
25+
INVALID_LISTENER_ENDPOINT: 'Please provide a valid listener endpoint.',
26+
INVALID_LISTENER_PORT: 'Please provide a valid listener port.',
27+
28+
// Log messages for core.ts
29+
REQUEST_RECEIVED: 'Request received.',
30+
31+
// Debug messages for core.ts
32+
ONLY_POST_SUPPORTED: 'Only POST requests are supported.',
33+
REQUEST_INVOKED: (url: string) => `Request invoked: ${url}`,
34+
URL_AUTH_FAILED: 'URL authentication failed.',
35+
VALIDATING_BASIC_AUTH: 'Validating basic authentication...',
36+
BASIC_AUTH_FAILED: 'Basic authentication failed.',
37+
VALIDATING_CUSTOM_HEADERS: 'Validating custom headers...',
38+
VALIDATING_HEADERS: 'Validating headers...',
39+
HEADER_NOT_FOUND: (headerKey: string) => `Header '${headerKey}' was not found in the request.`,
40+
PARSING_JSON: 'Parsing JSON...',
41+
EVENT: 'Event',
42+
EVENT_NOT_DEFINED: (event: string, type: string) => `Event '${event}:${type}' not defined for processing.`,
43+
DATA_RECEIVED_NOTIFY: 'Data received for [_notify].',
44+
ERROR_OCCURRED_NOTIFY: 'Error occurred in [_notify].',
45+
VALUE: 'Value',
46+
ERROR: 'Error',
47+
48+
// Logger messages
49+
LOGGER_REGISTRATION_FAILED: 'Failed to register logger.',
50+
LOGGER_REGISTERED_SUCCESS: 'Logger registered successfully.',
51+
UNABLE_TO_REGISTER_LOGGER: (name: string, instance: any) =>
52+
`Unable to register custom logger: '${name}()' does not exist on ${instance}.`,
53+
};
54+

test/unit/index.test.js

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ describe("Test start method without user config.", () => {
101101
.then(response => {
102102
expect(response.statusCode).toBe(400);
103103
expect(response.body.error.message).toBe(
104-
"Only POST call is supported.",
104+
"Only POST requests are supported.",
105105
);
106106
});
107107
});
@@ -147,7 +147,7 @@ describe("Test start method with custom logger", () => {
147147
});
148148
});
149149

150-
describe("Test start method with invalid user config", async () => {
150+
describe("Test start method with invalid user config", () => {
151151
test("It should throw error when endpoint in config set to number", () => {
152152
let config;
153153
register(notify);
@@ -160,7 +160,7 @@ describe("Test start method with invalid user config", async () => {
160160
start(config)
161161
.then(svr => {})
162162
.catch(error => {
163-
expect(error.message).toBe("Please provide valide listener.endpoint");
163+
expect(error.message).toBe("Please provide a valid listener endpoint.");
164164
});
165165
});
166166

@@ -176,7 +176,7 @@ describe("Test start method with invalid user config", async () => {
176176
start(config)
177177
.then(svr => {})
178178
.catch(error => {
179-
expect(error.message).toBe("Please provide valide listener.port");
179+
expect(error.message).toBe("Please provide a valid listener port.");
180180
});
181181
});
182182
});
@@ -223,7 +223,7 @@ describe("Test start method with user config", () => {
223223
.then(response => {
224224
expect(response.statusCode).toBe(400);
225225
expect(response.body.error.message).toBe(
226-
"Only POST call is supported.",
226+
"Only POST requests are supported.",
227227
);
228228
});
229229
});

0 commit comments

Comments
 (0)