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: working like other angular schematics, added flat + project #118

Closed
wants to merge 1 commit into from
Closed
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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ All possible commands in the table below:

| Scaffold | Usage | Aliases | Options
| --- | --- | --- | ---
| Module | ng g @ngxs/schematics:module | ngxs-module | --name (required), --project, --path, --sourceRoot, --spec (boolean) --flat (boolean)
| Store | ng g @ngxs/schematics:store | ngxs-store | --name (required), --path, --sourceRoot, --spec (boolean)
| State | ng g @ngxs/schematics:state | ngxs-state | --name (required), --path, --sourceRoot, --spec (boolean)
| Actions | ng g @ngxs/schematics:actions | ngxs-actions | --name (required), --path, --sourceRoot
Expand Down
699 changes: 265 additions & 434 deletions package-lock.json

Large diffs are not rendered by default.

9 changes: 4 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@ngxs/schematics",
"version": "0.0.1-alpha.5",
"version": "0.0.1-alpha.6",
"description": "NGXS schematics for Angular",
"scripts": {
"prepublishOnly": "npm run build",
Expand Down Expand Up @@ -41,14 +41,13 @@
"homepage": "https://github.com/ngxs/schematics#readme",
"schematics": "./src/collection.json",
"dependencies": {
"@angular-devkit/core": "9.1.0",
"@angular-devkit/schematics": "9.1.0",
"typescript": "4.1.3"
"@angular-devkit/schematics": "11.0.6",
"typescript": "4.0.5"
},
"devDependencies": {
"@commitlint/cli": "7.6.1",
"@commitlint/config-conventional": "7.6.0",
"@schematics/angular": "7.3.9",
"@schematics/angular": "11.0.6",
"@types/jest": "24.9.1",
"@types/node": "11.9.0",
"husky": "1.3.1",
Expand Down
6 changes: 6 additions & 0 deletions src/collection.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@
"extends": ["@schematics/angular"],
"$schema": "../node_modules/@angular-devkit/schematics/collection-schema.json",
"schematics": {
"module": {
"factory": "./factories/module/module.factory#module",
"description": "Create a NGXS full module",
"aliases": ["ngxs-module"],
"schema": "./factories/module/schema.json"
},
"store": {
"factory": "./factories/store/store.factory#store",
"description": "Create a NGXS full store",
Expand Down
8 changes: 8 additions & 0 deletions src/factories/module/module.factory.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { Rule } from '@angular-devkit/schematics';
import { ModuleSchema } from './module.schema';
import { FACTORIES } from '../../utils';
import { factoryLoader } from '../../utils/factory-loader';

export function module(options: ModuleSchema): Rule {
return factoryLoader<ModuleSchema>(options, FACTORIES.MODULE);
}
32 changes: 32 additions & 0 deletions src/factories/module/module.schema.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
export interface ModuleSchema {
/**
* The name of the store.
*/
name: string;
/**
* The module location and name.
*/
module: any;
moduleName?: string;
/**
* The name of the project
*/
project?: string;
/**
* The path to create the store.
*/
path?: string;
/**
* The source root path
*/
sourceRoot?: string;
/**
* The spec flag
*/
spec?: boolean;
/**
* The flat dir output flag
*/

flat?: boolean;
}
50 changes: 50 additions & 0 deletions src/factories/module/schema.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
{
"$schema": "http://json-schema.org/schema",
"id": "SchematicsNgxsModule",
"title": "Ngxs Module + Store Options Schema",
"type": "object",
"properties": {
"name": {
"description": "The name of the store.",
"type": "string",
"$default": {
"$source": "argv",
"index": 0
},
"x-prompt": "What name would you like to use for the store?"
},
"path": {
"type": "string",
"format": "path",
"description": "The path to create the store."
},
"project": {
"type": "string",
"description": "The name of the project.",
"$default": {
"$source": "projectName"
}
},
"sourceRoot": {
"type": "string",
"format": "path",
"description": "The source root path"
},
"projectType": {
"type": "string",
"format": "path",
"description": "The project type"
},
"flat": {
"type": "boolean",
"description": "Specifies if it should be flat.",
"default": true
},
"spec": {
"type": "boolean",
"description": "Specifies if a spec file is generated.",
"default": true
}
},
"required": ["name"]
}
4 changes: 4 additions & 0 deletions src/templates/module/__name__.actions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export class <%= classify(name) %>Action {
public static readonly type = '[<%= classify(name) %>] Add item';
constructor(public payload: string) { }
}
24 changes: 24 additions & 0 deletions src/templates/module/__name__.state.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { TestBed, async } from '@angular/core/testing';
import { NgxsModule, Store } from '@ngxs/store';
import { <%= classify(name) %>State, <%= classify(name) %>StateModel } from './<%= dasherize(name) %>.state';
import { <%= classify(name) %>Action } from './<%= dasherize(name) %>.actions';

describe('<%= classify(name) %> store', () => {
let store: Store;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [NgxsModule.forRoot([<%= classify(name) %>State])]
}).compileComponents();
store = TestBed.get(Store);
}));

it('should create an action and add an item', () => {
const expected: <%= classify(name) %>StateModel = {
items: ['item-1']
};
store.dispatch(new <%= classify(name) %>Action('item-1'));
const actual = store.selectSnapshot(<%= classify(name) %>State.getState);
expect(actual).toEqual(expected);
});

});
29 changes: 29 additions & 0 deletions src/templates/module/__name__.state.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { Injectable } from '@angular/core';
import { State, Action, Selector, StateContext } from '@ngxs/store';
import { <%= classify(name) %>Action } from './<%= dasherize(name) %>.actions';

export interface <%= classify(name) %>StateModel {
items: string[];
}

@State<<%= classify(name) %>StateModel>({
name: '<%= camelize(name) %>',
defaults: {
items: []
}
})
@Injectable()
export class <%= classify(name) %>StateModule {

@Selector()
public static getState(state: <%= classify(name) %>StateModel) {
return state;
}

@Action(<%= classify(name) %>Action)
public add(ctx: StateContext<<%= classify(name) %>StateModel>, { payload }: <%= classify(name) %>Action) {
const stateModel = ctx.getState();
stateModel.items = [...stateModel.items, payload];
ctx.setState(stateModel);
}
}
1 change: 1 addition & 0 deletions src/utils/common/factories.enum.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
export enum FACTORIES {
STATE = 'state',
STORE = 'store',
MODULE = 'module',
ACTIONS = 'actions',
STARTER_KIT = 'starter-kit'
}
137 changes: 128 additions & 9 deletions src/utils/factory-loader.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,136 @@
import { mergeWith, Rule, SchematicsException } from '@angular-devkit/schematics';
import {
branchAndMerge,
chain,
mergeWith,
Rule,
SchematicsException
} from '@angular-devkit/schematics';

import { FACTORIES } from './common/factories.enum';
import { isEmpty } from './common/properties';
import { StarterKitSchema } from '../factories/starter-kit/starter-kit.schema';

import { transform } from './transform-options';
import { generate } from './generate-factory';
import { Tree } from '@angular-devkit/schematics';
import * as ts from 'typescript';
import { strings, normalize } from '@angular-devkit/core';
import { addImportToModule } from '@schematics/angular/utility/ast-utils';
import { parseName } from '@schematics/angular/utility/parse-name';
import {
buildRelativePath,
findModuleFromOptions
} from '@schematics/angular/utility/find-module';
import { InsertChange } from '@schematics/angular/utility/change';

export function factoryLoader<T>(options: T | any, factory: FACTORIES): Rule {
if (isEmpty(options.name)) {
throw new SchematicsException('Invalid options, "name" is required.');
function addDeclarationToNgModule(options: any): Rule {
return (host: Tree) => {
if (!options.module) {
return host;
}

const modulePath = options.module;

const text = host.read(modulePath);
if (text === null) {
throw new SchematicsException(`File ${modulePath} does not exist.`);
}
const sourceText = text.toString();
const source = ts.createSourceFile(modulePath, sourceText, ts.ScriptTarget.Latest, true);

const changes = addImportToModule(
source,
modulePath,
`NgxsModule.${
options.projectType === 'app' ? 'forRoot([' : 'forFeature(['
}${strings.classify(`${options.name}StateModule`)}])`,
'@ngxs/store'
);
const changes2 = addImportToModule(
source,
modulePath,
`${strings.classify(`${options.name}StateModule`)}`,
buildRelativePath(
modulePath,
normalize(
`/${options.path}/` +
(options.flat ? '' : strings.dasherize(options.name) + '/') +
`${options.name}.state`
)
)
);

const recorder = host.beginUpdate(modulePath);
for (const change of changes) {
if (change instanceof InsertChange) {
recorder.insertLeft(change.pos, change.toAdd);
}
}
for (const change of changes2) {
if (change instanceof InsertChange) {
change.toAdd.toString().match('import')
? recorder.insertLeft(change.pos, change.toAdd)
: undefined;
}
}
host.commitUpdate(recorder);

return host;
};
}

function getWorkspace(host) {
const workspaceConfig = host.read('/angular.json');
if (!workspaceConfig) {
throw new SchematicsException('Could not find Angular workspace configuration');
}

options = transform<StarterKitSchema>(options);
return mergeWith(generate({ options, factory }));
// convert workspace to string
const workspaceContent = workspaceConfig.toString();

// parse workspace string into JSON object
const workspace: any = JSON.parse(workspaceContent);
return workspace;
}

export function factoryLoader<T>(options: T | any, factory: FACTORIES): Rule {
return (tree: Tree) => {
if (isEmpty(options.name)) {
throw new SchematicsException('Invalid options, "name" is required.');
}

// parse workspace string into JSON object
const workspace = getWorkspace(tree);

if (!options.project) {
options.project = workspace.defaultProject;
}
const projectName = options.project as string;

const project = workspace.projects[projectName];

options.projectType = project.projectType === 'application' ? 'app' : 'lib';

options.sourceRoot = project.sourceRoot;
if (options.path === undefined) {
options.path = `${project.sourceRoot}/${options.projectType}`;
}

const moduleDasherized =
options.projectType === 'app' ? options.projectType : strings.dasherize(projectName);

options.modulePath = `${moduleDasherized}.module.ts`;

options.module = options.modulePath;

if (options.module) {
options.module = findModuleFromOptions(tree, options);
}

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

return chain([
addDeclarationToNgModule(options),
branchAndMerge(mergeWith(generate({ options, factory })))
]);
};
}
7 changes: 6 additions & 1 deletion src/utils/generate-factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { join, Path } from '@angular-devkit/core';
import * as strings from '@angular-devkit/core/src/utils/strings';
import { GenerateFactoryInterface } from './interfaces/generate-factory.interface';
import { Parser } from './parser';
import { normalize } from 'path';

export function generate({ options, factory }: Partial<GenerateFactoryInterface>): Source {
const parser: Parser = new Parser();
Expand All @@ -12,6 +13,10 @@ export function generate({ options, factory }: Partial<GenerateFactoryInterface>
...strings,
...options
}),
move(options.path)
move(
normalize(
`/${options.path}/` + (options.flat ? '' : strings.dasherize(options.name) + '/')
)
)
]);
}
4 changes: 4 additions & 0 deletions src/utils/interfaces/generate-factory.interface.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
import { FACTORIES } from '../common/factories.enum';

export interface SchemaOptions {
name: string;
path: string;
spec: boolean;
flat: boolean;
}

export interface GenerateFactoryInterface {
workspace: Partial<any>;
application: Partial<any>;
options: Partial<SchemaOptions>;
factory: FACTORIES;
isSpec: boolean;
Expand Down
Loading