diff --git a/src/index.test.ts b/src/index.test.ts index f1ead67..8884097 100644 --- a/src/index.test.ts +++ b/src/index.test.ts @@ -1,7 +1,7 @@ import * as HttpStatusV1 from '../test/v1'; import * as HttpStatusV2 from './index'; import { - getReasonPhrase, getStatusCode, ReasonPhrases, StatusCodes, + getReasonPhrase, getStatusCode, ReasonPhrases, StatusCodes, validateStatusCode, } from './index'; import codes from '../codes.json'; @@ -87,3 +87,17 @@ describe('v2', () => { expect(() => { getStatusCode('blah blah'); }).toThrowError(/Reason phrase does not exist: blah blah/); }); }); + +describe('validateStatusCode', () => { + test('Valid status code', () => { + expect(validateStatusCode(200)).toBe(true); + expect(validateStatusCode(404)).toBe(true); + expect(validateStatusCode(500)).toBe(true); + }); + + test('Invalid status code', () => { + expect(validateStatusCode(0)).toBe(false); + expect(validateStatusCode(1000)).toBe(false); + expect(validateStatusCode(-200)).toBe(false); + }); +}); diff --git a/src/index.ts b/src/index.ts index d688d56..a40e1cb 100644 --- a/src/index.ts +++ b/src/index.ts @@ -3,12 +3,14 @@ import legacyCodes from './legacy'; import { getStatusCode, getStatusText, + validateStatusCode, } from './utils-functions'; export { getStatusCode, getReasonPhrase, getStatusText, + validateStatusCode, } from './utils-functions'; export { @@ -25,4 +27,5 @@ export default { ...legacyCodes, getStatusCode, getStatusText, + validateStatusCode, }; diff --git a/src/utils-functions.ts b/src/utils-functions.ts index 9a8cfdd..67afb76 100644 --- a/src/utils-functions.ts +++ b/src/utils-functions.ts @@ -45,3 +45,13 @@ export function getStatusCode(reasonPhrase: string): (number) { * @returns {string|undefined} The associated reason phrase (e.g. "Bad Request", "OK") * */ export const getStatusText = getReasonPhrase; + +/** + * Returns true if the given status code is a valid HTTP status code. + * + * @param {number} statusCode The HTTP status code + * @returns {boolean} True if the status code is valid, false otherwise + * */ +export function validateStatusCode(statusCode: number): boolean { + return Object.values(reasonPhraseToStatusCode).includes(statusCode); +}