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

new hooks: 'capitalize' and 'trim' #665

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
64 changes: 64 additions & 0 deletions docs/hooks.md
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,38 @@ Persistent, least-recently-used record cache for services.
| `item` | `Object` | | The record. |
| `clonedItem` | `Object` | | A clone of `item`. |

## capitalize

Converts the first character of string to upper case and the remaining to lower case.

|before|after|methods|multi|details|
|---|---|---|---|---|
|yes||create, update, patch|yes|[source](https://github.com/feathersjs-ecosystem/feathers-hooks-common/blob/master/src/hooks/capitalize.ts)|
||yes|all|||


- Arguments
- `{Array < String >} fieldNames`

|Name|Type|Description|
|---|---|---|
|fieldNames|dot notation|The fields in the record(s) whose values are converted to lower case.|

- **Example**

```js
const { capitalize } = require('feathers-hooks-common')

module.exports = {
before: {
create: capitalize('email', 'username', 'div.dept')
}
}
```

- **Details**

Update either `context.data` (before hook) or `context.result[.data]` (after hook).


## debug
Expand Down Expand Up @@ -2065,6 +2097,38 @@ Transform fields & objects in place in the record(s) using a recursive walk. Pow

> [substack/js-traverse](https://github.com/substack/js-traverse) documents the extensive methods and context available to the transformer function.

## trim

Removes leading and trailing whitespace or specified characters from string.

|before|after|methods|multi|details|
|---|---|---|---|---|
|yes||create, update, patch|yes|[source](https://github.com/feathersjs-ecosystem/feathers-hooks-common/blob/master/src/hooks/trim.ts)|
||yes|all|||


- Arguments
- `{Array < String >} fieldNames`

|Name|Type|Description|
|---|---|---|
|fieldNames|dot notation|The fields in the record(s) whose values are converted to lower case.|

- **Example**

```js
const { trim } = require('feathers-hooks-common')

module.exports = {
before: {
create: trim('email', 'username', 'div.dept')
}
}
```

- **Details**

Update either `context.data` (before hook) or `context.result[.data]` (after hook).

## unless

Expand Down
5 changes: 5 additions & 0 deletions src/common/transform-items.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ export function transformItems <T extends Record<string, any>> (
): void {
(Array.isArray(items) ? items : [items]).forEach(item => {
fieldNames.forEach((fieldName: any) => {
const value = _get(item, fieldName);
if (value === undefined) {
return
}

transformer(item, fieldName, _get(item, fieldName));
});
});
Expand Down
28 changes: 28 additions & 0 deletions src/hooks/capitalize.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import _set from 'lodash/set';
import _capitalize from 'lodash/capitalize';
import { BadRequest } from '@feathersjs/errors';

import { transformItems } from '../common';
import { checkContextIf } from './check-context-if';
import { getItems } from '../utils/get-items';
import type { Hook } from '@feathersjs/feathers';

/**
* Converts the first character of string to upper case and the remaining to lower case.
* {@link https://hooks-common.feathersjs.com/hooks.html#capitalize}
*/
export function capitalize (...fieldNames: string[]): Hook {
return (context: any) => {
checkContextIf(context, 'before', ['create', 'update', 'patch'], 'lowercase');

transformItems(getItems(context), fieldNames, (item: any, fieldName: any, value: any) => {
if (typeof value !== 'string' && value !== null) {
throw new BadRequest(`Expected string data. (lowercase ${fieldName})`);
}

_set(item, fieldName, value ? _capitalize(value) : value);
});

return context;
};
}
10 changes: 4 additions & 6 deletions src/hooks/lower-case.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,11 @@ export function lowerCase (...fieldNames: string[]): Hook {
checkContextIf(context, 'before', ['create', 'update', 'patch'], 'lowercase');

transformItems(getItems(context), fieldNames, (item: any, fieldName: any, value: any) => {
if (value !== undefined) {
if (typeof value !== 'string' && value !== null) {
throw new BadRequest(`Expected string data. (lowercase ${fieldName})`);
}

_set(item, fieldName, value ? value.toLowerCase() : value);
if (typeof value !== 'string' && value !== null) {
throw new BadRequest(`Expected string data. (lowercase ${fieldName})`);
}

_set(item, fieldName, value ? value.toLowerCase() : value);
});

return context;
Expand Down
27 changes: 27 additions & 0 deletions src/hooks/trim.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import _set from 'lodash/set';
import { BadRequest } from '@feathersjs/errors';

import { transformItems } from '../common';
import { checkContextIf } from './check-context-if';
import { getItems } from '../utils/get-items';
import type { Hook } from '@feathersjs/feathers';

/**
* Removes leading and trailing whitespace or specified characters from string.
* {@link https://hooks-common.feathersjs.com/hooks.html#trim}
*/
export function trim (...fieldNames: string[]): Hook {
return (context: any) => {
checkContextIf(context, 'before', ['create', 'update', 'patch'], 'trim');

transformItems(getItems(context), fieldNames, (item: any, fieldName: any, value: any) => {
if (typeof value !== 'string' && value !== null) {
throw new BadRequest(`Expected string data. (lowercase ${fieldName})`);
}

_set(item, fieldName, value ? value.trim() : value);
});

return context;
};
}
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
export { actOnDefault, actOnDispatch } from './hooks/act-on-dispatch';
export { alterItems } from './hooks/alter-items';
export { cache } from './hooks/cache';
export { capitalize } from './hooks/capitalize';
export { checkContextIf } from './hooks/check-context-if';
export { debug } from './hooks/debug';
export { dePopulate } from './hooks/de-populate';
Expand Down Expand Up @@ -35,6 +36,7 @@ export { sifter } from './hooks/sifter';
export { softDelete } from './hooks/soft-delete';
export { stashBefore } from './hooks/stash-before';
export { traverse } from './hooks/traverse';
export { trim } from './hooks/trim';
export { unless } from './hooks/unless'
export { validate } from './hooks/validate';
export { validateSchema } from './hooks/validate-schema';
Expand Down
130 changes: 130 additions & 0 deletions test/hooks/capitalize.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@

import { assert } from 'chai';
import { capitalize } from '../../src';

let hookBefore: any;
let hookAfter: any;
let hookFindPaginate: any;
let hookFind: any;

describe('services capitalize', () => {
describe('updates data', () => {
beforeEach(() => {
hookBefore = { type: 'before', method: 'create', data: { first: 'John', last: 'DOE' } };
hookAfter = { type: 'after', method: 'create', result: { first: 'jane', last: 'doE' } };
hookFindPaginate = {
type: 'after',
method: 'find',
result: {
total: 2,
data: [
{ first: 'John', last: 'DOE' },
{ first: 'jane', last: 'doE' }
]
}
};
hookFind = {
type: 'after',
method: 'find',
result: [
{ first: 'John', last: 'DOE' },
{ first: 'jane', last: 'doE' }
]
};
});

it('updates hook before::create', () => {
capitalize('first', 'last')(hookBefore);
assert.deepEqual(hookBefore.data, { first: 'John', last: 'Doe' });
});

it('updates hook after::find with pagination', () => {
capitalize('first', 'last')(hookFindPaginate);
assert.deepEqual(hookFindPaginate.result.data, [
{ first: 'John', last: 'Doe' },
{ first: 'Jane', last: 'Doe' }
]);
});

it('updates hook after::find with no pagination', () => {
capitalize('first', 'last')(hookFind);
assert.deepEqual(hookFind.result, [
{ first: 'John', last: 'Doe' },
{ first: 'Jane', last: 'Doe' }
]);
});

it('updates hook after', () => {
capitalize('first', 'last')(hookAfter);
assert.deepEqual(hookAfter.result, { first: 'Jane', last: 'Doe' });
});

it('does not throw if field is missing', () => {
const hook: any = { type: 'before', method: 'create', data: { last: 'Doe' } };
capitalize('first', 'last')(hook);
assert.deepEqual(hook.data, { last: 'Doe' });
});

it('does not throw if field is undefined', () => {
const hook: any = { type: 'before', method: 'create', data: { first: undefined, last: 'doe' } };
capitalize('first', 'last')(hook);
assert.deepEqual(hook.data, { first: undefined, last: 'Doe' });
});

it('does not throw if field is null', () => {
const hook: any = { type: 'before', method: 'create', data: { first: null, last: 'doe' } };
capitalize('first', 'last')(hook);
assert.deepEqual(hook.data, { first: null, last: 'Doe' });
});

it('throws if field is not a string', () => {
const hook: any = { type: 'before', method: 'create', data: { first: 1, last: 'doe' } };
assert.throws(() => { capitalize('first', 'last')(hook); });
});
});

describe('handles dot notation', () => {
beforeEach(() => {
hookBefore = {
type: 'before',
method: 'create',
data: { empl: { name: { first: 'john', last: 'doE' }, status: 'aa' }, dept: 'ACCT' }
};
});

it('prop with no dots', () => {
capitalize('dept')(hookBefore);
assert.deepEqual(hookBefore.data,
{ empl: { name: { first: 'john', last: 'doE' }, status: 'aa' }, dept: 'Acct' }
);
});

it('prop with 1 dot', () => {
capitalize('empl.status')(hookBefore);
assert.deepEqual(hookBefore.data,
{ empl: { name: { first: 'john', last: 'doE' }, status: 'Aa' }, dept: 'ACCT' }
);
});

it('prop with 2 dots', () => {
capitalize('empl.name.first')(hookBefore);
assert.deepEqual(hookBefore.data,
{ empl: { name: { first: 'John', last: 'doE' }, status: 'aa' }, dept: 'ACCT' }
);
});

it('ignores bad or missing paths', () => {
capitalize('empl.xx.first')(hookBefore);
assert.deepEqual(hookBefore.data,
{ empl: { name: { first: 'john', last: 'doE' }, status: 'aa' }, dept: 'ACCT' }
);
});

it('ignores bad or missing no dot path', () => {
capitalize('xx')(hookBefore);
assert.deepEqual(hookBefore.data,
{ empl: { name: { first: 'john', last: 'doE' }, status: 'aa' }, dept: 'ACCT' }
);
});
});
});
Loading