Skip to content

Commit cb1e0bc

Browse files
feature(): add scope option to the controller decorator
1 parent b2b5cb1 commit cb1e0bc

3 files changed

Lines changed: 26 additions & 6 deletions

File tree

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,30 @@
1-
import { PATH_METADATA } from '../../constants';
2-
import { isUndefined } from '../../utils/shared.utils';
1+
import { PATH_METADATA, SCOPE_OPTIONS_METADATA } from '../../constants';
2+
import { isString, isUndefined } from '../../utils/shared.utils';
3+
import { ScopeOptions } from './../../interfaces/scope-options.interface';
4+
5+
export interface ControllerOptions extends ScopeOptions {
6+
path?: string;
7+
}
38

49
/**
510
* Defines the controller. Controller can inject dependencies through constructor.
611
* Those dependencies have to belong to the same module.
712
*/
8-
export function Controller(prefix?: string): ClassDecorator {
9-
const path = isUndefined(prefix) ? '/' : prefix;
13+
export function Controller();
14+
export function Controller(prefix: string);
15+
export function Controller(options: ControllerOptions);
16+
export function Controller(
17+
prefixOrOptions?: string | ControllerOptions,
18+
): ClassDecorator {
19+
const defaultPath = '/';
20+
const [path, scopeOptions] = isUndefined(prefixOrOptions)
21+
? [defaultPath, undefined]
22+
: isString(prefixOrOptions)
23+
? [prefixOrOptions, undefined]
24+
: [prefixOrOptions.path || defaultPath, { scope: prefixOrOptions.scope }];
25+
1026
return (target: object) => {
1127
Reflect.defineMetadata(PATH_METADATA, path, target);
28+
Reflect.defineMetadata(SCOPE_OPTIONS_METADATA, scopeOptions, target);
1229
};
1330
}

packages/core/injector/module.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -348,6 +348,7 @@ export class Module {
348348
metatype: controller,
349349
instance: null,
350350
isResolved: false,
351+
scope: this.getClassScope(controller),
351352
host: this,
352353
}),
353354
);

packages/core/test/injector/module.spec.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { Scope } from '@nestjs/common';
1+
import { Controller, Scope } from '@nestjs/common';
22
import { expect } from 'chai';
33
import * as sinon from 'sinon';
44
import { Injectable } from '../../../common';
@@ -30,14 +30,16 @@ describe('Module', () => {
3030
const setSpy = sinon.spy(collection, 'set');
3131
(module as any)._controllers = collection;
3232

33+
@Controller({ scope: Scope.REQUEST })
3334
class Test {}
35+
3436
module.addController(Test);
3537
expect(setSpy.getCall(0).args).to.deep.equal([
3638
'Test',
3739
new InstanceWrapper({
3840
host: module,
3941
name: 'Test',
40-
scope: 0,
42+
scope: Scope.REQUEST,
4143
metatype: Test,
4244
instance: null,
4345
isResolved: false,

0 commit comments

Comments
 (0)