Skip to content
This repository was archived by the owner on Jun 22, 2021. It is now read-only.

feat: Adds convertPropertyFilter util. #10

Merged
merged 2 commits into from
Mar 26, 2018
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
6 changes: 6 additions & 0 deletions docs/facade.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,12 @@ The facade contains common functions for storage and retrieval of entities from
- [removeEntities](./functions.md#removeentities)
- [removeEntity](./functions.md#removeentity)

This package also contains some utility functions outside of the Facade that you might find useful.

- [convertPropertyFilter](./utils.md#convertPropertyFilter)
- [createCursorFromEntity](./utils.md#createCursorFromEntity)
- [createPaginationFilter](./utils.md#createPaginationFilter)

The [facade in this package is a TypeScript interface](../src/Facade.ts), but concrete implementations of the interface are listed below.

- [Memory](https://github.com/js-entity-repos/memory) - This is useful for testing client/server side.
Expand Down
4 changes: 2 additions & 2 deletions docs/options.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ interface TodoEntity extends Entity {
This is an object containing some of the entity's properties. This package uses [TypeScript's Partial type](https://www.typescriptlang.org/docs/handbook/advanced-types.html) applied to an [Entity](#entity) (using `Partial<Entity>`).

### Filter
This is an object that filters the entities. The [filter type definition](../src/types/Filter.ts) currently supports the following operators which have been [borrowed from Mongo](https://docs.mongodb.com/manual/reference/operator/query/).
This is an object that filters the entities. The [filter type definition](../src/types/Filter.ts) currently supports the following operators which have been [borrowed from Mongo](https://docs.mongodb.com/manual/reference/operator/query/). In some cases (like dates) you may need to use the [`convertPropertyFilter` utility function](./utils.md#convertPropertyFilter).

Operator | Description
--- | ---
Expand Down Expand Up @@ -110,6 +110,6 @@ This package contains the [TypeScript Sort type definition](../src/types/Sort.ts
### Pagination
This is an object with three properties, `limit`, `direction`, and `cursor`. The `limit` property defines how many entities to return (maximum). The `direction` property defines whether the entities should be iterated through forwards (when `'forward'`) or backwards (when `'backward'`) from the `cursor`. The `cursor` property defines where to start iterating through the entities. Cursors have been used instead of `skip` and `limit` to avoid the [pagination issues discussed by Rakhitha Nimesh](https://www.sitepoint.com/paginating-real-time-data-cursor-based-pagination/).

Concrete implementations of the facade can use the [`createCursorFromEntity`](../src/utils/createCursorFromEntity) and [`createPaginationFilter`](../src/utils/createPaginationFilter) utility functions to generate cursors.
Concrete implementations of the facade can use the [`createCursorFromEntity`](./utils.md#createCursorFromEntity) and [`createPaginationFilter`](./utils.md#createPaginationFilter) utility functions to generate cursors.

This package contains the [TypeScript Pagination interface](../src/types/Pagination.ts) and the [TypeScript Cursor type definition](../src/types/Cursor.ts). It also contains [constants for `'forward'` and `'backward'`](../src/types/PaginationDirection.ts) that should always be used to avoid breaking changes in the future.
69 changes: 69 additions & 0 deletions docs/utils.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# Utils

This package contains some common utility functions that can be used by both users and implementors of the [Facade](./facade.md#facade).

- [convertPropertyFilter](#convertPropertyFilter)
- [createCursorFromEntity](#createCursorFromEntity)
- [createPaginationFilter](#createPaginationFilter)

### convertPropertyFilter
Converts the filter value for a certain property name. For example, if you have a date property on your entity called `createdAt` storing the date at which an entity was created, then if you filter the property using a string (usually via [js-entity-repos/express](https://github.com/js-entity-repos/express)), you can use this util to ensure that the string is converted to a date before using the filter in the database. This is usually used by users of the js-entity-repos inside a `constructFilter` function in the factory config of [concrete implementations of the Facade](./facade.md#facade), the [Knex implementation allows this configuration function](https://github.com/js-entity-repos/knex#construct-the-facade) amongst others.

```ts
import convertPropertyFilter from '@js-entity-repos/core/dist/utils/convertPropertyFilter';

convertPropertyFilter({
converter: (value: any) => new Date(value),
propertyName: 'createdAt',
filter: { createdAt: '2018-01-01' },
});
// Returns the result of { createdAt: new Date('2018-01-01') }
```

### createCursorFromEntity
Exactly what it says on the tin, this creates a cursor from an entity. A cursor is constructed by creating a [filter](./options#filter) that will filter out entities not expected in the next set of paginated results. This filter is then stringified to JSON and base 64 encoded. This function is usually used by [concrete implementations of the Facade](./facade.md#facade) like [Knex's getEntities implementation](https://github.com/js-entity-repos/knex/blob/master/src/functions/getEntities.ts)..

```ts
import createCursorFromEntity from '@js-entity-repos/core/dist/utils/createCursorFromEntity';
import { asc } from '@js-entity-repos/core/dist/types/SortOrder';

createCursorFromEntity(undefined, { id: asc });
// Returns undefined

createCursorFromEntity({
booleanProp: true,
id: 'test_id_1',
numberProp: 1,
stringProp: 'test_string_prop',
}, {
id: asc,
});
// Returns eyJpZCI6InRlc3RfaWQifQ==
```

### createPaginationFilter
Takes a [pagination option](./options#pagination) and a [sort option](./options#sort)) to produces a [filter](./options#filter) that can filter out entities not expected in the next set of paginated results. This function is usually used by [concrete implementations of the Facade](./facade.md#facade) like [Knex's getEntities implementation](https://github.com/js-entity-repos/knex/blob/master/src/functions/getEntities.ts).

```ts
import createPaginationFilter from '@js-entity-repos/core/dist/utils/createPaginationFilter';
import { asc, desc } from '@js-entity-repos/core/dist/types/SortOrder';
import { backward, forward } from '@js-entity-repos/core/dist/types/PaginationDirection';

createPaginationFilter(
{ cursor: undefined, direction: forward, limit: 1 },
{ id: asc, numberProp: desc }
);
// Returns {}

createPaginationFilter(
{ cursor: nextCursor, direction: forward, limit: 1 },
{ id: asc, numberProp: desc }
);
// Returns the result of { id: { $gt: lastEntity.id }, numberProp: { $lte: lastEntity.numberProp } }

createPaginationFilter(
{ cursor: prevCursor, direction: backward, limit: 1 },
{ id: asc, numberProp: desc }
);
// Returns the result of { id: { $lt: firstEntity.id }, numberProp: { $gte: firstEntity.numberProp } }
```
33 changes: 33 additions & 0 deletions src/utils/convertPropertyFilter/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import 'mocha'; // tslint:disable-line:no-import-side-effect
import * as assert from 'power-assert';
import { TestEntity } from '../../tests/utils/testEntity';
import { Filter } from '../../types/Filter';
import convertPropertyFilter from './index';

describe('convertPropertyFilter', () => {
const originalValue = 10;
const expectedValue = '10';
const converter = (value: any) => value.toString();
const propertyName = 'numberProp';

it('should convert the property value when used inside a prop filter', () => {
const filter: Filter<TestEntity> = { numberProp: { $gt: originalValue } };
const newFilter = convertPropertyFilter({ converter, filter, propertyName });
const expectedFilter = { numberProp: { $gt: expectedValue } };
assert.deepEqual(newFilter, expectedFilter);
});

it('should convert the property value when used inside an entity filter', () => {
const filter: Filter<TestEntity> = { numberProp: originalValue, stringProp: 'test_string' };
const newFilter = convertPropertyFilter({ converter, filter, propertyName });
const expectedFilter = { numberProp: expectedValue, stringProp: 'test_string' };
assert.deepEqual(newFilter, expectedFilter);
});

it('should convert the property value when used inside a condition filter', () => {
const filter: Filter<TestEntity> = { $and: [{ numberProp: originalValue }] };
const newFilter = convertPropertyFilter({ converter, filter, propertyName });
const expectedFilter = { $and: [{ numberProp: expectedValue }] };
assert.deepEqual(newFilter, expectedFilter);
});
});
50 changes: 50 additions & 0 deletions src/utils/convertPropertyFilter/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { isArray, isPlainObject, mapValues } from 'lodash';

export interface Opts {
readonly propertyName: string;
readonly converter: (propertyValue: any) => any;
readonly filter: any;
readonly useConverter?: boolean;
}

const convertPropertyFilter = ({
converter,
filter,
propertyName,
useConverter = false,
}: Opts): any => {
if (isPlainObject(filter)) {
return mapValues(filter, (subFilter, filterKey) => {
if (filterKey !== propertyName) {
return convertPropertyFilter({
converter,
filter: subFilter,
propertyName,
useConverter,
});
}
return convertPropertyFilter({
converter,
filter: subFilter,
propertyName,
useConverter: true,
});
});
}
if (isArray(filter)) {
return filter.map((subFilter) => {
return convertPropertyFilter({
converter,
filter: subFilter,
propertyName,
useConverter,
});
});
}
if (!useConverter) {
return filter;
}
return converter(filter);
};

export default convertPropertyFilter;