|
import { |
|
chain, |
|
externalSchematic, |
|
Rule, |
|
Tree, |
|
SchematicContext, |
|
move |
|
} from '@nrwl/workspace/node_modules/@angular-devkit/schematics'; |
|
import { Linter } from '@nrwl/workspace/src/utils/lint'; |
|
import { toFileName, formatFiles } from '@nrwl/workspace'; |
|
import { SchematicsException } from '@angular-devkit/schematics'; |
|
import { strings } from '@angular-devkit/core'; |
|
|
|
export interface Schema { |
|
name: string; |
|
directory?: string; |
|
skipTsConfig: boolean; |
|
skipFormat: boolean; |
|
tags?: string; |
|
simpleModuleName: boolean; |
|
unitTestRunner: 'jest' | 'none'; |
|
linter: Linter; |
|
} |
|
|
|
export interface NormalizedSchema extends Schema { |
|
name: string; |
|
fileName: string; |
|
projectRoot: string; |
|
projectDirectory: string; |
|
parsedTags: string[]; |
|
} |
|
|
|
export const nestjsModule = ( |
|
name: string |
|
) => `import { Module } from '@nestjs/common'; |
|
|
|
@Module({ |
|
imports: [], |
|
controllers: [], |
|
providers: [] |
|
}) |
|
export class ${strings.classify(name)}Module {} |
|
|
|
`; |
|
|
|
export default function(schema: Schema): Rule { |
|
return (_host: Tree, _context: SchematicContext) => { |
|
const options = normalizeOptions(schema); |
|
|
|
return chain([ |
|
externalSchematic('@nrwl/workspace', 'library', schema), |
|
addNestModule(options), |
|
move( |
|
`${options.projectRoot}/src/lib/${options.name}`, |
|
`${options.projectRoot}/src/lib` |
|
), |
|
formatFiles(options) |
|
]); |
|
}; |
|
} |
|
|
|
function addNestModule(schema: NormalizedSchema) { |
|
const modulePath = `${schema.projectRoot}/src/lib/${schema.name}.module`; |
|
return (host: Tree) => { |
|
host.rename( |
|
`${schema.projectRoot}/src/lib/${schema.name}.ts`, |
|
`${modulePath}.ts` |
|
); |
|
|
|
host.overwrite( |
|
`${schema.projectRoot}/src/index.ts`, |
|
`export * from './lib/${schema.name}.module';` |
|
); |
|
|
|
host.overwrite(`${modulePath}.ts`, nestjsModule(schema.name)); |
|
|
|
return host; |
|
}; |
|
} |
|
|
|
function normalizeOptions(options: Schema): NormalizedSchema { |
|
const name = toFileName(options.name); |
|
const projectDirectory = options.directory |
|
? `${toFileName(options.directory)}/${name}` |
|
: name; |
|
|
|
const projectName = projectDirectory.replace(new RegExp('/', 'g'), '-'); |
|
const fileName = options.simpleModuleName ? name : projectName; |
|
const projectRoot = `libs/${projectDirectory}`; |
|
|
|
const parsedTags = options.tags |
|
? options.tags.split(',').map(s => s.trim()) |
|
: []; |
|
|
|
return { |
|
...options, |
|
fileName, |
|
name: projectName, |
|
projectRoot, |
|
projectDirectory, |
|
parsedTags |
|
}; |
|
} |
|
|
|
export const fileReadText = (host: Tree, path: string): string => { |
|
const source = host.read(path); |
|
if (source === null) { |
|
throw new SchematicsException(`File ${path} does not exist.`); |
|
} |
|
|
|
return source.toString('utf-8'); |
|
}; |