diff --git a/src/packages/router/index.js b/src/packages/router/index.js index 254ea237..201ed68d 100644 --- a/src/packages/router/index.js +++ b/src/packages/router/index.js @@ -6,7 +6,7 @@ import Namespace from './namespace'; import { build, define } from './definitions'; import createReplacer from './utils/create-replacer'; import type { Router$opts } from './interfaces'; -import type Route from './route'; // eslint-disable-line no-duplicate-imports +import type Route from './route'; /** * @private diff --git a/src/packages/router/test/create-replacer.test.js b/src/packages/router/test/create-replacer.test.js new file mode 100644 index 00000000..290d08c5 --- /dev/null +++ b/src/packages/router/test/create-replacer.test.js @@ -0,0 +1,46 @@ +// @flow +import { expect } from 'chai'; +import { it, describe, before } from 'mocha'; + +import { getTestApp } from '../../../../test/utils/get-test-app'; +import createReplacer from '../utils/create-replacer'; + +describe('module "router"', () => { + describe('util createReplacer()', () => { + let subject; + + before(async () => { + const app = await getTestApp(); + // $FlowIgnore + const healthController = app.controllers.get('health'); + const { constructor: HealthController } = healthController; + + class AdminHealthController extends HealthController {} + + subject = createReplacer(new Map([ + // $FlowIgnore + ['posts', app.controllers.get('posts')], + ['health', healthController], + // $FlowIgnore + ['admin/posts', app.controllers.get('admin/posts')], + ['admin/health', new AdminHealthController({ + namespace: 'admin' + })] + ])); + }); + + it('returns an instance of RegExp', () => { + expect(subject).to.be.an.instanceOf(RegExp); + }); + + it('correctly replaces dynamic parts', () => { + expect( + 'posts/1'.replace(subject, '$1/:dynamic') + ).to.equal('posts/:dynamic'); + + expect( + 'health/1'.replace(subject, '$1/:dynamic') + ).to.equal('health/:dynamic'); + }); + }); +}); diff --git a/src/packages/router/utils/create-replacer.js b/src/packages/router/utils/create-replacer.js index 4065d642..4640d584 100644 --- a/src/packages/router/utils/create-replacer.js +++ b/src/packages/router/utils/create-replacer.js @@ -9,9 +9,25 @@ export default function createReplacer( ): RegExp { const names = Array .from(controllers) - .map(([, { model }]) => model) - .filter(Boolean) - .map(({ resourceName }) => resourceName) + .map(([, controller]) => { + const { model, namespace } = controller; + + if (model) { + return model.resourceName; + } + + let { constructor: { name } } = controller; + + name = name + .replace(/controller/ig, '') + .toLowerCase(); + + return namespace + .split('/') + .reduce((str, part) => ( + str.replace(new RegExp(part, 'ig'), '') + ), name); + }) .filter((str, idx, arr) => idx === arr.lastIndexOf(str)) .join('|');