Skip to content

Commit

Permalink
feat: support dotted property names
Browse files Browse the repository at this point in the history
  • Loading branch information
fedeci committed Jan 16, 2021
1 parent 55097d4 commit e26d3df
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 6 deletions.
22 changes: 20 additions & 2 deletions src/context-items/rename.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Meta } from '../base';
import { Rename } from './rename';

it('the new path is identical to the old one', () => {
const context = new ContextBuilder().build();
const context = new ContextBuilder().setFields(['foo']).build();
const meta: Meta = { req: {}, location: 'body', path: 'foo' };

expect(new Rename('foo').run(context, 'value', meta)).resolves;
Expand All @@ -19,7 +19,7 @@ it('throws an error if trying to rename more than one field', async () => {
describe('throws an error if using wildcards', () => {
it('in context fields', async () => {
const context = new ContextBuilder().setFields(['foo.*']).build();
const meta: Meta = { req: {}, location: 'body', path: 'foo' };
const meta: Meta = { req: {}, location: 'body', path: 'foo.*' };

await expect(new Rename('_foo').run(context, 'value', meta)).rejects.toThrow();
});
Expand Down Expand Up @@ -65,3 +65,21 @@ it('throws an error if trying to rename to an existing property', () => {
_foo: 'value',
});
});

it('should rename params with dotted property names', () => {
const context = new ContextBuilder().setFields(['[4.0]']).build();
const meta: Meta = {
req: {
body: {
'4.0': 'value',
},
},
location: 'body',
path: '[4.0]',
};

expect(new Rename('[5.2]').run(context, 'value', meta)).resolves;
expect(meta.req.body).toEqual({
'5.2': 'value',
});
});
9 changes: 5 additions & 4 deletions src/context-items/rename.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,17 @@ export class Rename implements ContextItem {
if (context.fields.length !== 1) {
throw new Error('Cannot rename multiple fields.');
}
const field = context.fields[0];
if (field.includes('*') || this.newPath.includes('*')) {
const newPath = _.toPath(this.newPath);
const fieldPath = _.toPath(context.fields[0]);
if (fieldPath.includes('*') || newPath.includes('*')) {
throw new Error('Cannot use rename() with wildcards.');
}

if (_.get(req[location], this.newPath) !== undefined) {
if (_.get(req[location], newPath) !== undefined) {
throw new Error(`Cannot rename to req.${location}.${path} as it already exists.`);
}

_.set(req[location], this.newPath, value);
_.set(req[location], newPath, value);
_.unset(req[location], path);
}
return Promise.resolve();
Expand Down

0 comments on commit e26d3df

Please sign in to comment.