Skip to content

Commit

Permalink
feat(core): support Nx lib barrels as feature targets
Browse files Browse the repository at this point in the history
  • Loading branch information
NathanWalker committed Jan 17, 2021
1 parent d4ec89a commit 99b9ac5
Show file tree
Hide file tree
Showing 4 changed files with 111 additions and 8 deletions.
41 changes: 41 additions & 0 deletions packages/angular/src/schematics/ngrx/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,4 +154,45 @@ describe('ngrx schematic', () => {
// console.log('content:', content)
expect(content.indexOf(`StoreModule.forFeature`)).toBeGreaterThanOrEqual(0);
});

it('should create ngrx state for Nx lib only', async () => {
// console.log('appTree:', appTree);
appTree = Tree.empty();
appTree = createXplatWithNativeScriptWeb(appTree, null, 'angular', 'sample');
const options: GenerateOptions = {
name: 'auth',
feature: '@testing/sample',
};
let tree = await runSchematic('ngrx', options, appTree);
const files = tree.files;
// console.log(files. slice(91,files.length));

// state should not be setup in xplat architecture
expect(
files.indexOf(`/libs/xplat/core/src/lib/state/auth.actions.ts`)
).toBe(-1);

// state should be lib specific
expect(
files.indexOf(
`/libs/sample/src/lib/state/auth.actions.ts`
)
).toBeGreaterThanOrEqual(0);

// file content
let indexPath =
`/libs/sample/src/lib/state/auth.actions.ts`;
let content = getFileContent(tree, indexPath);
// console.log(barrelPath + ':');
// console.log(barrelIndex);
// symbol should be at end of collection
expect(content.indexOf(`AuthActions`)).toBeGreaterThanOrEqual(0);

let modulePath = '/libs/sample/src/lib/sample.module.ts';
content = getFileContent(tree, modulePath);
// console.log(modulePath + ':');
// console.log(content);
// symbol should be at end of collection
expect(content.indexOf(`StoreModule.forFeature`)).toBeGreaterThanOrEqual(0);
});
});
46 changes: 40 additions & 6 deletions packages/angular/src/utils/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import {
SchematicsException,
externalSchematic,
} from '@angular-devkit/schematics';
import { formatFiles, createOrUpdate } from '@nrwl/workspace';
import { formatFiles, createOrUpdate, readJsonInTree } from '@nrwl/workspace';
import {
addGlobal,
insert,
Expand Down Expand Up @@ -253,7 +253,7 @@ export function generate(type: IGenerateType, options) {
platform,
'angular'
);
return adjustModule(type, options, `libs/xplat/${xplatFolderName}`);
return adjustModule(tree, type, options, `libs/xplat/${xplatFolderName}`);
});
} else {
throw new Error(unsupportedPlatformError(platform));
Expand Down Expand Up @@ -289,7 +289,7 @@ export function generate(type: IGenerateType, options) {
// adjust feature module metadata if needed
(tree: Tree, context: SchematicContext) =>
!options.projects && platforms.length === 0
? adjustModule(type, options, 'libs/xplat')(tree, context)
? adjustModule(tree, type, options, 'libs/xplat')(tree, context)
: noop()(tree, context),

// project handling
Expand Down Expand Up @@ -322,6 +322,31 @@ export function getFeatureName(options: IGenerateOptions) {
return featureName;
}

export function isFeatureNxLib(featureName: string) {
return featureName && featureName.indexOf('@') === 0;
}

export function getNxFeaturePath(tree: Tree, featureName: string) {
const tsConfig = readJsonInTree(tree, 'tsconfig.base.json');
if (tsConfig) {
if (
tsConfig.compilerOptions &&
tsConfig.compilerOptions.paths &&
tsConfig.compilerOptions.paths[featureName]
) {
let libPath = tsConfig.compilerOptions.paths[featureName][0];
return libPath.replace('index.ts', 'lib');
} else {
throw new Error(
`No lib barrel path found in tsconfig.base.json matching "${featureName}"`
);
}
} else {
throw new Error('Workspace must have tsconfig.base.json.');
}
return null;
}

export function addToFeature(
xplatFolderName: string,
type: IGenerateType,
Expand All @@ -332,12 +357,16 @@ export function addToFeature(
forSubFolder?: boolean
) {
let featureName: string = getFeatureName(options);
const isNxLib = isFeatureNxLib(featureName);

options.needsIndex = false; // reset

const srcSubFolderPath = options.projects ? '' : '/src/lib';
let featurePath: string;
if (shouldTargetCoreBarrel(type, featureName)) {
// support targeting Nx libs with feature argument using the lib barrel (ie, @scope/mylib)
if (isNxLib) {
featurePath = getNxFeaturePath(tree, featureName);
} else if (shouldTargetCoreBarrel(type, featureName)) {
// services and/or state should never be generated in shared or ui features
// therefore place in core (since they are service level)
featureName = 'core';
Expand All @@ -353,7 +382,7 @@ export function addToFeature(
moveTo = `libs/xplat/features/src/lib/${featureName}/base`;
} else {
moveTo = `${featurePath}/${type}${type === 'state' ? '' : 's'}`;
if (!tree.exists(featureModulePath)) {
if (!isNxLib && !tree.exists(featureModulePath)) {
let optionName: string;
if (prefixPath !== 'libs') {
// parse platform from prefix
Expand Down Expand Up @@ -574,13 +603,18 @@ export function adjustBarrelIndexForType(
}

export function adjustModule(
tree: Tree,
type: IGenerateType,
options: IGenerateOptions,
prefixPath: string
) {
let featureName: string = getFeatureName(options);
const isNxLib = isFeatureNxLib(featureName);
let featurePath: string;
if (shouldTargetCoreBarrel(type, featureName)) {
if (isNxLib) {
featurePath = getNxFeaturePath(tree, featureName);
featureName = featureName.split('/').pop();
} else if (shouldTargetCoreBarrel(type, featureName)) {
featureName = 'core';
featurePath = `${prefixPath}/${featureName}/src/lib`;
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -130,5 +130,5 @@ export default function (options: XplatFeatureHelpers.Schema) {
// // adjust feature module metadata if needed
// (tree: Tree, context: SchematicContext) =>
// !options.projects && targetPlatforms.nativescript
// ? adjustModule(type, options, 'xplat/nativescript')(tree, context)
// ? adjustModule(tree, type, options, 'xplat/nativescript')(tree, context)
// : noop()(tree, context),
30 changes: 29 additions & 1 deletion packages/xplat/src/utils/testing-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,17 +117,45 @@ export function createXplatWithApps(
export function createXplatWithNativeScriptWeb(
tree: Tree,
withRouting?: boolean,
framework?: FrameworkTypes
framework?: FrameworkTypes,
withNxLibName?: string
): Tree {
tree = createEmptyWorkspace(tree, framework);
createXplatLibs(tree);
createXplatNativeScriptAngular(tree, framework);
createXplatWebAngular(tree, framework);
createNativeScriptAngularApp(tree, withRouting);
createWebAngularApp(tree, withRouting);
if (withNxLibName) {
// also create a standard Nx library
createNxLib(tree, withNxLibName);
}
return tree;
}

export function createNxLib(tree: Tree, name: string) {
tree.create(`/libs/${name}/src/lib/index.ts`, '');
tree.create(
`/libs/${name}/src/lib/${name}.module.ts`,
`import {
NgModule
} from '@angular/core';
import { APP_BASE_HREF, CommonModule } from '@angular/common';
@NgModule({
imports: [CommonModule]
})
export class ${name}Module {}`
);
const configPaths = {};
configPaths[`@testing/${name}`] = [`libs/${name}/src/index.ts`]
tree.overwrite(
'/tsconfig.base.json',
JSON.stringify({ compilerOptions: { paths: configPaths } })
);

}

export function createXplatLibs(tree: Tree) {
tree.create('/libs/xplat/core/src/lib/index.ts', '');
tree.create(
Expand Down

0 comments on commit 99b9ac5

Please sign in to comment.