Skip to content

Commit

Permalink
fix(CliConfig): allow set on array item properties
Browse files Browse the repository at this point in the history
Support changing properties of array items in `CliConfig.set` method.
This makes the following commands to work:
  - `$ ng set apps[0].main my-main.ts`
  - `$ ng set apps.0.test my-test.ts`

Closes angular#1763
  • Loading branch information
platosha committed Aug 22, 2016
1 parent a761bc5 commit d325f93
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 6 deletions.
19 changes: 13 additions & 6 deletions addon/ng2/models/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,14 +60,21 @@ export class CliConfig {
let properties: any;
let additionalProperties: boolean;

jsonPath = jsonPath.replace(/\[(\d+)\]/g, '.$1');
const checkPath = jsonPath.split('.').reduce((o, i) => {
if (!o || !o.properties) {
if (!o || (o.type === 'array' && !o.items) || (o.type === 'object' && !o.properties)) {
throw new Error(`Invalid config path.`);
}
properties = o.properties;

additionalProperties = o.additionalProperties;

return o.properties[i];
if (o.type === 'array') {
return o.items;
}

properties = o.properties;

return properties[i];
}, schema);
const configPath = jsonPath.split('.').reduce((o, i) => o[i], this._config);

Expand All @@ -84,18 +91,18 @@ export class CliConfig {
}
}

if (typeof checkPath.type === 'string' && isNaN(value)) {
if (checkPath.type === 'string' && isNaN(value)) {
parent[name] = value;
return true;
}

if (typeof checkPath.type === 'number' && !isNaN(value)) {
if (checkPath.type === 'number' && !isNaN(value)) {
parent[name] = value;
return true;
}

if (typeof value != checkPath.type) {
throw new Error(`Invalid value type. Trying to set ${typeof value} to ${path.type}`);
throw new Error(`Invalid value type. Trying to set ${typeof value} to ${checkPath.type}`);
}
}

Expand Down
12 changes: 12 additions & 0 deletions tests/models/config.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,18 @@ describe.skip('Config Tests', () => {
expect(contents.project.name).to.be.equal('new-project-name');
});

it('Updates properties of array items successfully', () => {
let c = new CliConfig(configCopy);
c.set('apps.0.main', 'new-main.ts');
c.set('apps[0].test', 'new-test.ts');
c.save();

let contents = getContents();

expect(contents.apps[0].main).to.be.equal('new-main.ts');
expect(contents.apps[0].test).to.be.equal('new-test.ts');
});

it('Throws an error if try to assign property that does not exists', () => {
let c = new CliConfig(configCopy);

Expand Down

0 comments on commit d325f93

Please sign in to comment.