-
Notifications
You must be signed in to change notification settings - Fork 59
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
sheppardv
wants to merge
2
commits into
techniq:main
Choose a base branch
from
sheppardv:refactor
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"], | ||
}; |
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(','); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 ""; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 ')})`; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}`; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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