|
| 1 | +import { |
| 2 | + Rule, |
| 3 | + SchematicContext, |
| 4 | + SchematicsException, |
| 5 | + Tree, |
| 6 | +} from '@angular-devkit/schematics'; |
| 7 | +import { NodePackageInstallTask } from '@angular-devkit/schematics/tasks'; |
| 8 | +import { applyToUpdateRecorder } from '@schematics/angular/utility/change'; |
| 9 | +import * as ts from 'typescript'; |
| 10 | +import { addSymbolToNgModuleMetadata } from '../utility/ast-utils'; |
| 11 | + |
| 12 | +export function ngAdd(): Rule { |
| 13 | + return (tree: Tree, context: SchematicContext) => { |
| 14 | + context.logger.info('Installing dependencies...'); |
| 15 | + context.addTask(new NodePackageInstallTask()); |
| 16 | + |
| 17 | + context.logger.info('Adding DateInterceptorsModule to the app...'); |
| 18 | + const appModulePath = './src/app/app.module.ts'; |
| 19 | + |
| 20 | + if (!tree.exists(appModulePath)) { |
| 21 | + throw new SchematicsException( |
| 22 | + `The file ${appModulePath} doesn't exist...` |
| 23 | + ); |
| 24 | + } |
| 25 | + |
| 26 | + const recorder = tree.beginUpdate(appModulePath); |
| 27 | + const appModuleFileContent = tree.read(appModulePath); |
| 28 | + |
| 29 | + if (appModuleFileContent === null) { |
| 30 | + throw new SchematicsException( |
| 31 | + `The content of ${appModulePath} couldn't be read...` |
| 32 | + ); |
| 33 | + } |
| 34 | + |
| 35 | + const appModuleFileText = appModuleFileContent.toString('utf-8'); |
| 36 | + const sourceFile = ts.createSourceFile( |
| 37 | + appModulePath, |
| 38 | + appModuleFileText, |
| 39 | + ts.ScriptTarget.Latest, |
| 40 | + true |
| 41 | + ); |
| 42 | + const importPath = '@ngx-toolset/date-interceptors'; |
| 43 | + |
| 44 | + for (const symbol of [ |
| 45 | + { |
| 46 | + metadataField: 'imports', |
| 47 | + symbolName: 'DateInterceptorsModule', |
| 48 | + importText: 'DateInterceptorsModule.forRoot()', |
| 49 | + }, |
| 50 | + { |
| 51 | + metadataField: 'providers', |
| 52 | + symbolName: 'API_URL_REGEX', |
| 53 | + importText: '{ provide: API_URL_REGEX, useValue: /^/ },', |
| 54 | + }, |
| 55 | + { |
| 56 | + metadataField: 'providers', |
| 57 | + symbolName: 'API_DATE_FORMAT', |
| 58 | + importText: "{ provide: API_DATE_FORMAT, useValue: '' },", |
| 59 | + }, |
| 60 | + { |
| 61 | + metadataField: 'providers', |
| 62 | + symbolName: 'DATE_STRING_REGEX', |
| 63 | + importText: "{ provide: DATE_STRING_REGEX, useValue: '' },", |
| 64 | + }, |
| 65 | + ]) { |
| 66 | + applyToUpdateRecorder( |
| 67 | + recorder, |
| 68 | + addSymbolToNgModuleMetadata( |
| 69 | + sourceFile, |
| 70 | + appModulePath, |
| 71 | + symbol.metadataField, |
| 72 | + symbol.symbolName, |
| 73 | + importPath, |
| 74 | + symbol.importText |
| 75 | + ) |
| 76 | + ); |
| 77 | + } |
| 78 | + |
| 79 | + tree.commitUpdate(recorder); |
| 80 | + |
| 81 | + return tree; |
| 82 | + }; |
| 83 | +} |
0 commit comments