Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(store): add support of standalone API for ng-add store #3874

Merged
merged 2 commits into from
May 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions modules/schematics-core/testing/create-workspace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,13 @@ export async function createWorkspace(
appTree
);

appTree = await schematicRunner.runExternalSchematic(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as other comment about schematics-core

'@schematics/angular',
'application',
{ ...appOptions, name: 'bar-standalone', standalone: true },
appTree
);

appTree = await schematicRunner.runExternalSchematic(
'@schematics/angular',
'library',
Expand Down
23 changes: 22 additions & 1 deletion modules/store/schematics-core/utility/project.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
import { TargetDefinition } from '@angular-devkit/core/src/workspace';
import { getWorkspace } from './config';
import { Tree } from '@angular-devkit/schematics';
import { SchematicsException, Tree } from '@angular-devkit/schematics';

export interface WorkspaceProject {
root: string;
projectType: string;
architect: {
[key: string]: TargetDefinition;
};
}

export function getProject(
Expand Down Expand Up @@ -52,3 +56,20 @@ export function isLib(

return project.projectType === 'library';
}

export function getProjectMainFile(
Copy link
Member

@brandonroberts brandonroberts May 5, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We keep our schematics-core synced across packages for consistency. This should be moved to

https://github.com/ngrx/platform/blob/master/modules/schematics-core/utility/project.ts

And then run

yarn copy:schematics

To copy it to schematics-core folder in the other packages.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hm... I just tried to do the steps you described but it seems like the yarn copy:schematics does nothing in my case. I expect the code under module/schematics-core will be propagated to store/schematics-core/..., however, I see no changes after running this command. Am I missing something?
P.S. The output of yarn copy:schematics shows that the task was successfully executed.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm maybe it's an operating system path issue in our script. To not hold this up, if everything is good, we'll merge it and I'll follow up with the schematics-core move.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alright, so from my side no actions are needed anymore? :)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right :)

host: Tree,
options: { project?: string | undefined; path?: string | undefined }
) {
if (isLib(host, options)) {
throw new SchematicsException(`Invalid project type`);
}
const project = getProject(host, options);
const projectOptions = project.architect['build'].options;

if (!projectOptions?.main) {
throw new SchematicsException(`Could not find the main file`);
}

return projectOptions.main as string;
}
50 changes: 50 additions & 0 deletions modules/store/schematics/ng-add/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,4 +161,54 @@ describe('Store ng-add Schematic', () => {
},
});
});

describe('Store ng-add Schematic for standalone application', () => {
const projectPath = getTestProjectPath(undefined, {
name: 'bar-standalone',
});
const standaloneDefaultOptions = {
...defaultOptions,
project: 'bar-standalone',
standalone: true,
};

it('provides minimal store setup', async () => {
const options = { ...standaloneDefaultOptions, minimal: true };
const tree = await schematicRunner.runSchematic(
'ng-add',
options,
appTree
);

const content = tree.readContent(`${projectPath}/src/app/app.config.ts`);
const files = tree.files;

expect(content).toMatch(/provideStore\(\)/);
expect(content).not.toMatch(
/import { reducers, metaReducers } from '\.\/reducers';/
);
expect(files.indexOf(`${projectPath}/src/app/reducers/index.ts`)).toBe(
-1
);
});
it('provides full store setup', async () => {
const options = { ...standaloneDefaultOptions };
const tree = await schematicRunner.runSchematic(
'ng-add',
options,
appTree
);

const content = tree.readContent(`${projectPath}/src/app/app.config.ts`);
const files = tree.files;

expect(content).toMatch(/provideStore\(reducers, \{ metaReducers \}\)/);
expect(content).toMatch(
/import { reducers, metaReducers } from '\.\/reducers';/
);
expect(
files.indexOf(`${projectPath}/src/app/reducers/index.ts`)
).toBeGreaterThanOrEqual(0);
});
});
});
82 changes: 78 additions & 4 deletions modules/store/schematics/ng-add/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@ import {
parseName,
} from '../../schematics-core';
import { Schema as RootStoreOptions } from './schema';
import {
addFunctionalProvidersToStandaloneBootstrap,
callsProvidersFunction,
} from '@schematics/angular/private/standalone';
import { getProjectMainFile } from '../../schematics-core/utility/project';

function addImportToNgModule(options: RootStoreOptions): Rule {
return (host: Tree) => {
Expand Down Expand Up @@ -138,14 +143,81 @@ function addNgRxESLintPlugin() {
};
}

function addStandaloneConfig(options: RootStoreOptions): Rule {
return (host: Tree) => {
const mainFile = getProjectMainFile(host, options);

if (host.exists(mainFile)) {
const storeProviderFn = 'provideStore';

if (callsProvidersFunction(host, mainFile, storeProviderFn)) {
// exit because the store config is already provided
return host;
}
const storeProviderOptions = options.minimal
? []
: [
ts.factory.createIdentifier('reducers'),
ts.factory.createIdentifier('{ metaReducers }'),
];
const patchedConfigFile = addFunctionalProvidersToStandaloneBootstrap(
host,
mainFile,
storeProviderFn,
'@ngrx/store',
storeProviderOptions
);

if (options.minimal) {
// no need to add imports if it is minimal
return host;
}

// insert reducers import into the patched file
const configFileContent = host.read(patchedConfigFile);
const source = ts.createSourceFile(
patchedConfigFile,
configFileContent?.toString('utf-8') || '',
ts.ScriptTarget.Latest,
true
);
const statePath = `/${options.path}/${options.statePath}`;
const relativePath = buildRelativePath(
`/${patchedConfigFile}`,
statePath
);

const recorder = host.beginUpdate(patchedConfigFile);

const change = insertImport(
source,
patchedConfigFile,
'reducers, metaReducers',
relativePath
);

if (change instanceof InsertChange) {
recorder.insertLeft(change.pos, change.toAdd);
}

host.commitUpdate(recorder);

return host;
}
throw new SchematicsException(
`Main file not found for a project ${options.project}`
);
};
}

export default function (options: RootStoreOptions): Rule {
return (host: Tree, context: SchematicContext) => {
options.path = getProjectPath(host, options);

const parsedPath = parseName(options.path, '');
options.path = parsedPath.path;

if (options.module) {
if (options.module && !options.standalone) {
options.module = findModuleFromOptions(host, {
name: '',
module: options.module,
Expand All @@ -166,10 +238,12 @@ export default function (options: RootStoreOptions): Rule {
move(parsedPath.path),
]);

const configOrModuleUpdate = options.standalone
? addStandaloneConfig(options)
: addImportToNgModule(options);

return chain([
branchAndMerge(
chain([addImportToNgModule(options), mergeWith(templateSource)])
),
branchAndMerge(chain([configOrModuleUpdate, mergeWith(templateSource)])),
options && options.skipPackageJson ? noop() : addNgRxStoreToPackageJson(),
options && options.skipESLintPlugin ? noop() : addNgRxESLintPlugin(),
])(host, context);
Expand Down
5 changes: 5 additions & 0 deletions modules/store/schematics/ng-add/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,11 @@
"type": "boolean",
"default": false,
"description": "Do not register the NgRx ESLint Plugin."
},
"standalone": {
"type": "boolean",
"default": false,
"description": "Configure store for standalone application"
}
},
"required": []
Expand Down
1 change: 1 addition & 0 deletions modules/store/schematics/ng-add/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,5 @@ export interface Schema {
*/
minimal?: boolean;
skipESLintPlugin?: boolean;
standalone?: boolean;
}
4 changes: 3 additions & 1 deletion projects/ngrx.io/content/guide/store/install.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,14 @@ ng add @ngrx/store@latest
| `--minimal` | Flag to only provide minimal setup for the root state management. Only registers `StoreModule.forRoot()` in the provided `module` with an empty object, and default runtime checks. | `boolean` |`true`
| `--statePath` | The file path to create the state in. | `string` | `reducers` |
| `--stateInterface` | The type literal of the defined interface for the state. | `string` | `State` |
| `--standalone` | Flag to configure store for standalone application. | `boolean` |`false` |

This command will automate the following steps:

1. Update `package.json` > `dependencies` with `@ngrx/store`.
2. Run `npm install` to install those dependencies.
3. Update your `src/app/app.module.ts` > `imports` array with `StoreModule.forRoot({})`.
3. Update your `src/app/app.module.ts` > `imports` array with `StoreModule.forRoot({})`
4. If the flag `--standalone` is provided, it adds `provideStore()` into the application config.

```sh
ng add @ngrx/store@latest --no-minimal
Expand Down