refactor(middleware-cors) Split check origin function
MODIFY
packages/middleware-cors/src/checkOrigin.spec.ts
packages/middleware-cors/src/checkOrigin.spec.ts
-import { checkOrigin } from './checkOrigin';
+import { checkOrigin, checkStringOrigin, checkArrayOrigin, checkRegexpOrigin } from './checkOrigin';
import { createMockRequest } from './middleware.spec';
describe('checkOrigin', () => {
@@ -32,7 +32,7 @@ describe('checkOrigin', () => {
done();
});
- test('check array option correctly', done => {
+ test('check regexp option correctly', done => {
const option1 = /[a-z]/;
const option2 = /[0-9]/;
const req1 = createMockRequest('GET', { origin: 'fake-origin-a' });
@@ -43,3 +43,36 @@ describe('checkOrigin', () => {
done();
});
});
+
+describe('checkStringOrigin', () => {
+ test('check string option correctly', done => {
+ const option1 = 'fake-origin';
+ const option2 = 'fake-origin-2';
+
+ expect(checkStringOrigin('fake-origin', option1)).toBeTruthy();
+ expect(checkStringOrigin('fake-origin', option2)).toBeFalsy();
+ done();
+ });
+});
+
+describe('checkArrayOrigin', () => {
+ test('check array option correctly', done => {
+ const option1 = ['fake-origin'];
+ const option2 = ['fake-origin-2'];
+
+ expect(checkArrayOrigin('fake-origin', option2)).toBeFalsy();
+ expect(checkArrayOrigin('fake-origin', option1)).toBeTruthy();
+ done();
+ });
+});
+
+describe('checkStringOrigin', () => {
+ test('check regexp option correctly', done => {
+ const option1 = /[a-z]/;
+ const option2 = /[0-9]/;
+
+ expect(checkRegexpOrigin('fake-origin', option1)).toBeTruthy();
+ expect(checkRegexpOrigin('fake-origin', option2)).toBeFalsy();
+ done();
+ });
+});

MODIFY
packages/middleware-cors/src/checkOrigin.ts
packages/middleware-cors/src/checkOrigin.ts
@@ -7,6 +7,17 @@ export const checkOrigin = (
): boolean => {
const origin = req.headers.origin as string;
+ return [
+ checkStringOrigin,
+ checkArrayOrigin,
+ checkRegexpOrigin,
+ ].some(check => check(origin, option));
+};
+
+export const checkStringOrigin = (
+ origin: string,
+ option: string | string[] | RegExp,
+): boolean => {
if (isString(option) && option === '*') {
return true;
} else if (
@@ -15,15 +26,20 @@ export const checkOrigin = (
origin.match(option as string)
) {
return true;
- } else if (
- Array.isArray(option) &&
- option.length > 0 &&
- option.includes(origin)
- ) {
- return true;
- } else if (option instanceof RegExp && option.test(origin)) {
- return true;
}
return false;
};
+
+export const checkArrayOrigin = (
+ origin: string,
+ option: string | string[] | RegExp,
+): boolean =>
+ Array.isArray(option) && option.length > 0 && option.includes(origin)
+ ? true
+ : false;
+
+export const checkRegexpOrigin = (
+ origin: string,
+ option: string | string[] | RegExp,
+): boolean => (option instanceof RegExp && option.test(origin) ? true : false);

refactor(middleware-cors) Split check origin function