feat(@schematics/angular): generate functional interceptors

Adds a `--functional` flag to the interceptor schematic to generate a functional interceptor (as we can now do for guards and resolvers)
This commit is contained in:
ced 2022-11-25 13:47:27 +01:00 committed by angular-robot[bot]
parent 534921c29c
commit 9299dea649
7 changed files with 57 additions and 3 deletions

View File

@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { <%= camelize(name) %>Interceptor } from './<%= dasherize(name) %>.interceptor';
describe('<%= camelize(name) %>Interceptor', () => {
const interceptor: HttpInterceptorFn = (req, next) =>
TestBed.runInInjectionContext(() => <%= camelize(name) %>Interceptor(req, next));
beforeEach(() => {
TestBed.configureTestingModule({});
});
it('should be created', () => {
expect(interceptor).toBeTruthy();
});
});

View File

@ -0,0 +1,5 @@
import { HttpInterceptorFn } from '@angular/common/http';
export const <%= camelize(name) %>Interceptor: HttpInterceptorFn = (req, next) => {
return next(req);
}

View File

@ -14,8 +14,17 @@ export default function (options: InterceptorOptions): Rule {
// This schematic uses an older method to implement the flat option
const flat = options.flat;
options.flat = true;
return generateFromFiles(options, {
const extraTemplateValues = {
'if-flat': (s: string) => (flat ? '' : s),
});
};
return options.functional
? generateFromFiles(
{ ...options, templateFilesDirectory: './functional-files' },
extraTemplateValues,
)
: generateFromFiles(
{ ...options, templateFilesDirectory: './class-files' },
extraTemplateValues,
);
}

View File

@ -74,4 +74,23 @@ describe('Interceptor Schematic', () => {
.toPromise();
expect(appTree.files).toContain('/projects/bar/custom/app/foo/foo.interceptor.ts');
});
it('should create a functional interceptor', async () => {
const tree = await schematicRunner
.runSchematicAsync('interceptor', { ...defaultOptions, functional: true }, appTree)
.toPromise();
const fileString = tree.readContent('/projects/bar/src/app/foo/foo.interceptor.ts');
expect(fileString).toContain(
'export const fooInterceptor: HttpInterceptorFn = (req, next) => {',
);
});
it('should create a helper function to run a functional interceptor in a test', async () => {
const tree = await schematicRunner
.runSchematicAsync('interceptor', { ...defaultOptions, functional: true }, appTree)
.toPromise();
const fileString = tree.readContent('/projects/bar/src/app/foo/foo.interceptor.spec.ts');
expect(fileString).toContain('const interceptor: HttpInterceptorFn = (req, next) => ');
expect(fileString).toContain('TestBed.runInInjectionContext(() => fooInterceptor(req, next));');
});
});

View File

@ -40,6 +40,11 @@
"type": "boolean",
"description": "Do not create \"spec.ts\" test files for the new interceptor.",
"default": false
},
"functional": {
"type": "boolean",
"description": "Creates the interceptor as a `HttpInterceptorFn`.",
"default": false
}
},
"required": ["name", "project"]