/
ngrx.ts
114 lines (97 loc) · 2.75 KB
/
ngrx.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
import {
apply,
chain,
url,
mergeWith,
template,
move,
noop,
filter,
Rule,
Tree,
SchematicContext
} from '@angular-devkit/schematics';
import { Schema } from './schema';
import * as path from 'path';
import { names, toFileName } from '@nrwl/workspace';
import {
addImportsToModule,
addNgRxToPackageJson,
addExportsToBarrel,
RequestContext
} from './rules';
import { formatFiles } from '@nrwl/workspace';
/**
* Rule to generate the Nx 'ngrx' Collection
* Note: see https://nx.dev/angular/guides/misc-ngrx for guide to generated files
*/
export default function generateNgrxCollection(_options: Schema): Rule {
return (host: Tree, context: SchematicContext) => {
const options = normalizeOptions(_options);
if (!options.module) {
throw new Error(`The required --module option must be passed`);
} else if (!host.exists(options.module)) {
throw new Error(`Path does not exist: ${options.module}`);
}
const requestContext: RequestContext = {
featureName: options.name,
moduleDir: path.dirname(options.module),
options,
host
};
if (options.minimal) {
options.onlyEmptyRoot = true;
}
if (options.skipImport) {
options.onlyAddFiles = true;
}
const fileGeneration =
!options.onlyEmptyRoot || (!options.root && options.minimal)
? [generateNgrxFilesFromTemplates(options)]
: [];
const moduleModification = !options.onlyAddFiles
? [
addImportsToModule(requestContext),
addExportsToBarrel(requestContext.options)
]
: [];
const packageJsonModification = !options.skipPackageJson
? [addNgRxToPackageJson()]
: [];
return chain([
...fileGeneration,
...moduleModification,
...packageJsonModification,
formatFiles(options)
])(host, context);
};
}
// ********************************************************
// Internal Function
// ********************************************************
/**
* Generate 'feature' scaffolding: actions, reducer, effects, interfaces, selectors, facade
*/
function generateNgrxFilesFromTemplates(options: Schema) {
const name = options.name;
const moduleDir = path.dirname(options.module);
const excludeFacade = path => path.match(/^((?!facade).)*$/);
const templateSource = apply(
url(options.syntax === 'creators' ? './creator-files' : './files'),
[
!options.facade ? filter(excludeFacade) : noop(),
template({ ...options, tmpl: '', ...names(name) }),
move(moduleDir)
]
);
return mergeWith(templateSource);
}
/**
* Extract the parent 'directory' for the specified
*/
function normalizeOptions(options: Schema): Schema {
return {
...options,
directory: toFileName(options.directory)
};
}