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

Refactor, split code into modules #79

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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 jest.config.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
moduleDirectories: ["node_modules", "src"],
};
18,833 changes: 4,320 additions & 14,513 deletions package-lock.json

Large diffs are not rendered by default.

8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,13 @@
"tslib": "^1.10.0"
},
"devDependencies": {
"@types/jest": "^24.0.15",
"@types/jest": "^26.0.20",
"browserify": "^16.5.1",
"jest": "^24.8.0",
"jest": "^26.6.3",
"rimraf": "^2.6.3",
"ts-jest": "^24.0.2",
"ts-jest": "^26.4.4",
"tsify": "^4.0.2",
"typescript": "^3.5.2"
"typescript": "^4.1.3"
},
"scripts": {
"prebuild": "rimraf dist",
Expand Down
26 changes: 26 additions & 0 deletions src/builders/agregate.ts

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be nice for the file name spelling to match the builder function spelling : aggregate

Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import {Aggregate} from './../odata-types';

export function buildAggregate(aggregate: Aggregate | Aggregate[]) {
// Wrap single object in an array for simplified processing
const aggregateArray = Array.isArray(aggregate) ? aggregate : [aggregate];

return aggregateArray
.map(aggregateItem => {
return typeof aggregateItem === "string"
? aggregateItem
: Object.keys(aggregateItem).map(aggregateKey => {
const aggregateValue = aggregateItem[aggregateKey];

// TODO: Are these always required? Can/should we default them if so?
if (!aggregateValue.with) {
throw new Error(`'with' property required for '${aggregateKey}'`);
}
if (!aggregateValue.as) {
throw new Error(`'as' property required for '${aggregateKey}'`);
}

return `${aggregateKey} with ${aggregateValue.with} as ${aggregateValue.as}`;
});
})
.join(',');
}
70 changes: 70 additions & 0 deletions src/builders/expand.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import {Expand, NestedExpandOptions, OrderBy, SUPPORTED_EXPAND_PROPERTIES} from './../odata-types';
import {buildFilter} from "./filter";
import {buildOrderBy} from "./order-by";

export function buildExpand<T>(expands: Expand<T>): string {
if (typeof expands === 'number') {
return expands as any;
} else if (typeof expands === 'string') {
if (expands.indexOf('/') === -1) {
return expands;
}

// Change `Foo/Bar/Baz` to `Foo($expand=Bar($expand=Baz))`
return expands
.split('/')
.reverse()
.reduce((results, item, index, arr) => {
if (index === 0) {
// Inner-most item
return `$expand=${item}`;
} else if (index === arr.length - 1) {
// Outer-most item, don't add `$expand=` prefix (added above)
return `${item}(${results})`;
} else {
// Other items
return `$expand=${item}(${results})`;
}
}, '');
} else if (Array.isArray(expands)) {
return `${(expands as Array<NestedExpandOptions<any>>).map(e => buildExpand(e)).join(',')}`;
} else if (typeof expands === 'object') {
const expandKeys = Object.keys(expands);

if (
expandKeys.some(
key => SUPPORTED_EXPAND_PROPERTIES.indexOf(key.toLowerCase()) !== -1
)
) {
return expandKeys
.map(key => {
let value;
switch (key) {
case 'filter':
value = buildFilter((expands as NestedExpandOptions<any>)[key]);
break;
case 'orderBy':
value = buildOrderBy((expands as NestedExpandOptions<any>)[key] as OrderBy<T>);
break;
case 'levels':
case 'count':
case 'top':
value = `${(expands as NestedExpandOptions<any>)[key]}`;
break;
default:
value = buildExpand((expands as NestedExpandOptions<any>)[key] as Expand<T>);
}
return `$${key.toLowerCase()}=${value}`;
})
.join(';');
} else {
return expandKeys
.map(key => {
const builtExpand = buildExpand((expands as NestedExpandOptions<any>)[key] as NestedExpandOptions<any>);
return builtExpand ? `${key}(${builtExpand})` : key;
})
.join(',');
}
}
return "";
}
200 changes: 200 additions & 0 deletions src/builders/filter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
import {
Alias,
BOOLEAN_FUNCTIONS,
COLLECTION_OPERATORS,
COMPARISON_OPERATORS,
Filter,
FUNCTION_REGEX,
LOGICAL_OPERATORS
} from './../odata-types';
import {handleValue} from './../helpers';
import {INDEXOF_REGEX, ITEM_ROOT} from './../constants';

export function buildFilter(filters: Filter = {}, aliases: Alias[] = [], propPrefix = ''): string {
return ((Array.isArray(filters) ? filters : [filters])
.reduce((acc: string[], filter) => {
if (filter) {
const builtFilter = buildFilterCore(filter, aliases, propPrefix);
if (builtFilter) {
acc.push(builtFilter);
}
}
return acc;
}, []) as string[]).join(' and ');

function buildFilterCore(filter: Filter = {}, aliases: Alias[] = [], propPrefix = '') {
let filterExpr = "";
if (typeof filter === 'string') {
// Use raw filter string
filterExpr = filter;
} else if (filter && typeof filter === 'object') {
const filtersArray = Object.keys(filter).reduce(
(result: any[], filterKey) => {
const value = (filter as any)[filterKey];
let propName = '';
if (propPrefix) {
if (filterKey === ITEM_ROOT) {
propName = propPrefix;
} else if (INDEXOF_REGEX.test(filterKey)) {
propName = filterKey.replace(INDEXOF_REGEX, (_, $1) => $1.trim() === ITEM_ROOT ? `(${propPrefix})` : `(${propPrefix}/${$1.trim()})`);
} else if (FUNCTION_REGEX.test(filterKey)) {
propName = filterKey.replace(FUNCTION_REGEX, (_, $1) => $1.trim() === ITEM_ROOT ? `(${propPrefix})` : `(${propPrefix}/${$1.trim()})`);
} else {
propName = `${propPrefix}/${filterKey}`;
}
} else {
propName = filterKey;
}

if (filterKey === ITEM_ROOT && Array.isArray(value)) {
return result.concat(
value.map((arrayValue: any) => renderPrimitiveValue(propName, arrayValue))
)
}

if (
['number', 'string', 'boolean'].indexOf(typeof value) !== -1 ||
value instanceof Date ||
value === null
) {
// Simple key/value handled as equals operator
result.push(renderPrimitiveValue(propName, value, aliases));
} else if (Array.isArray(value)) {
const op = filterKey;
const builtFilters = value
.map(v => buildFilter(v, aliases, propPrefix))
.filter(f => f)
.map(f => (LOGICAL_OPERATORS.indexOf(op) !== -1 ? `(${f})` : f));
if (builtFilters.length) {
if (LOGICAL_OPERATORS.indexOf(op) !== -1) {
if (builtFilters.length) {
if (op === 'not') {
result.push(parseNot(builtFilters as string[]));
} else {
result.push(`(${builtFilters.join(` ${op} `)})`);
}
}
} else {
result.push(builtFilters.join(` ${op} `));
}
}
} else if (LOGICAL_OPERATORS.indexOf(propName) !== -1) {
const op = propName;
const builtFilters = Object.keys(value).map(valueKey =>
buildFilterCore({[valueKey]: value[valueKey]})
);
if (builtFilters.length) {
if (op === 'not') {
result.push(parseNot(builtFilters as string[]));
} else {
result.push(`${builtFilters.join(` ${op} `)}`);
}
}
} else if (typeof value === 'object') {
if ('type' in value) {
result.push(renderPrimitiveValue(propName, value, aliases));
} else {
const operators = Object.keys(value);
operators.forEach(op => {
if (COMPARISON_OPERATORS.indexOf(op) !== -1) {
result.push(`${propName} ${op} ${handleValue(value[op], aliases)}`);
} else if (LOGICAL_OPERATORS.indexOf(op) !== -1) {
if (Array.isArray(value[op])) {
result.push(
value[op]
.map((v: any) => '(' + buildFilterCore(v, aliases, propName) + ')')
.join(` ${op} `)
);
} else {
result.push('(' + buildFilterCore(value[op], aliases, propName) + ')');
}
} else if (COLLECTION_OPERATORS.indexOf(op) !== -1) {
const collectionClause = buildCollectionClause(filterKey.toLowerCase(), value[op], op, propName);
if (collectionClause) {
result.push(collectionClause);
}
} else if (op === 'has') {
result.push(`${propName} ${op} ${handleValue(value[op], aliases)}`);
} else if (op === 'in') {
const resultingValues = Array.isArray(value[op])
? value[op]
: value[op].value.map((typedValue: any) => ({
type: value[op].type,
value: typedValue,
}));

result.push(
propName + ' in (' + resultingValues.map((v: any) => handleValue(v, aliases)).join(',') + ')'
);
} else if (BOOLEAN_FUNCTIONS.indexOf(op) !== -1) {
// Simple boolean functions (startswith, endswith, contains)
result.push(`${op}(${propName},${handleValue(value[op], aliases)})`);
} else {
// Nested property
const filter = buildFilterCore(value, aliases, propName);
if (filter) {
result.push(filter);
}
}
});
}
} else if (value === undefined) {
// Ignore/omit filter if value is `undefined`
} else {
throw new Error(`Unexpected value type: ${value}`);
}

return result;
},
[]
);

filterExpr = filtersArray.join(' and ');
} /* else {
throw new Error(`Unexpected filters type: ${filter}`);
} */
return filterExpr;
}

function buildCollectionClause(lambdaParameter: string, value: any, op: string, propName: string) {
let clause = '';

if (typeof value === 'string' || value instanceof String) {
clause = getStringCollectionClause(lambdaParameter, value, op, propName);
} else if (value) {
// normalize {any:[{prop1: 1}, {prop2: 1}]} --> {any:{prop1: 1, prop2: 1}}; same for 'all',
// simple values collection: {any:[{'': 'simpleVal1'}, {'': 'simpleVal2'}]} --> {any:{'': ['simpleVal1', 'simpleVal2']}}; same for 'all',
const filterValue = Array.isArray(value) ?
value.reduce((acc, item) => {
if (item.hasOwnProperty(ITEM_ROOT)) {
if (!acc.hasOwnProperty(ITEM_ROOT)) {
acc[ITEM_ROOT] = [];
}
acc[ITEM_ROOT].push(item[ITEM_ROOT])
return acc;
}
return {...acc, ...item}
}, {}) : value;

const filter = buildFilterCore(filterValue, aliases, lambdaParameter);
clause = `${propName}/${op}(${filter ? `${lambdaParameter}:${filter}` : ''})`;
}
return clause;
}
}

function renderPrimitiveValue(key: string, val: any, aliases: Alias[] = []) {
return `${key} eq ${handleValue(val, aliases)}`
}

function getStringCollectionClause(lambdaParameter: string, value: any, collectionOperator: string, propName: string) {
let clause = '';
const conditionOperator = collectionOperator == 'all' ? 'ne' : 'eq';
clause = `${propName}/${collectionOperator}(${lambdaParameter}: ${lambdaParameter} ${conditionOperator} '${value}')`

return clause;
}

function parseNot(builtFilters: string[]): string {
return `not(${builtFilters.join(' and ')})`;
}
16 changes: 16 additions & 0 deletions src/builders/group-by.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import {GroupBy} from './../odata-types';
import {buildTransforms} from './transforms';

export function buildGroupBy<T>(groupBy: GroupBy<T>) {
if (!groupBy.properties) {
throw new Error(`'properties' property required for groupBy`);
}

let result = `(${groupBy.properties.join(',')})`;

if (groupBy.transform) {
result += `,${buildTransforms(groupBy.transform)}`;
}

return result;
}
16 changes: 16 additions & 0 deletions src/builders/order-by.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import {OrderBy, OrderByOptions} from './../odata-types';

export function buildOrderBy<T>(orderBy: OrderBy<T>, prefix: string = ''): string {
if (Array.isArray(orderBy)) {
return (orderBy as OrderByOptions<T>[])
.map(value =>
(Array.isArray(value) && value.length === 2 && ['asc', 'desc'].indexOf(value[1]) !== -1) ? value.join(' ') : value
)
.map(v => `${prefix}${v}`).join(',');
} else if (typeof orderBy === 'object') {
return Object.entries(orderBy)
.map(([k, v]) => buildOrderBy(v as OrderBy<any>, `${k}/`))
.map(v => `${prefix}${v}`).join(',');
}
return `${prefix}${orderBy}`;
}
39 changes: 39 additions & 0 deletions src/builders/transforms.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import {Transform} from './../odata-types';
import {buildGroupBy} from './group-by';
import {buildAggregate} from './agregate';
import {buildFilter} from './filter';

export function buildTransforms<T>(transforms: Transform<T> | Transform<T>[]) {
// Wrap single object an array for simplified processing
const transformsArray = Array.isArray(transforms) ? transforms : [transforms];

const transformsResult = transformsArray.reduce((result: string[], transform) => {
const {aggregate, filter, groupBy, ...rest} = transform;

// TODO: support as many of the following:
// topcount, topsum, toppercent,
// bottomsum, bottomcount, bottompercent,
// identity, concat, expand, search, compute, isdefined
const unsupportedKeys = Object.keys(rest);
if (unsupportedKeys.length) {
throw new Error(`Unsupported transform(s): ${unsupportedKeys}`);
}

if (aggregate) {
result.push(`aggregate(${buildAggregate(aggregate)})`);
}
if (filter) {
const builtFilter = buildFilter(filter);
if (builtFilter) {
result.push(`filter(${buildFilter(builtFilter)})`);
}
}
if (groupBy) {
result.push(`groupby(${buildGroupBy(groupBy)})`);
}

return result;
}, []);

return transformsResult.join('/') || undefined;
}
Loading