-
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 all commits
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,30 @@ | ||
import {Aggregate, AggregateObject} from './../odata-types'; | ||
|
||
export function buildAggregate(aggregate: Aggregate | Aggregate[]): string { | ||
// 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 | ||
: buildAggregateItem(aggregateItem); | ||
}) | ||
.join(','); | ||
} | ||
|
||
function buildAggregateItem(aggregateItem: AggregateObject) { | ||
return 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}`; | ||
}); | ||
} |
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,76 @@ | ||
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 | number { | ||
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(expandsReducer, ''); | ||
} 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); | ||
|
||
const hasSupportedExpandProperties = expandKeys.some(key => | ||
SUPPORTED_EXPAND_PROPERTIES.indexOf(key.toLowerCase()) !== -1 | ||
); | ||
|
||
if (hasSupportedExpandProperties) { | ||
return mapExpandKeyWithSupportedProps(expandKeys, expands); | ||
} else { | ||
return expandKeys | ||
.map(key => { | ||
const builtExpand = buildExpand((expands as NestedExpandOptions<any>)[key] as NestedExpandOptions<any>); | ||
return builtExpand ? `${key}(${builtExpand})` : key; | ||
}) | ||
.join(','); | ||
} | ||
} | ||
return ""; | ||
} | ||
|
||
function mapExpandKeyWithSupportedProps<T>(expandKeys: string[], expands: NestedExpandOptions<T>) { | ||
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(';'); | ||
} | ||
|
||
function expandsReducer(results: string, item: string, index: number, arr: string[]) { | ||
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})`; | ||
} | ||
|
||
// Other items | ||
return `$expand=${item}(${results})`; | ||
} |
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,209 @@ | ||
import { | ||
Alias, | ||
BOOLEAN_FUNCTIONS, | ||
COLLECTION_OPERATORS, | ||
COMPARISON_OPERATORS, | ||
Filter, | ||
FUNCTION_REGEX, | ||
LOGICAL_OPERATORS, | ||
PlainObject | ||
} 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 replaceFilterKey(filterKey: string, propPrefix: string, regExp: RegExp) { | ||
return filterKey.replace(regExp, (_, $1) => $1.trim() === ITEM_ROOT ? `(${propPrefix})` : `(${propPrefix}/${$1.trim()})`); | ||
} | ||
|
||
function processFilterObj(filter: PlainObject | Array<string | PlainObject>, propPrefix: string, aliases: Alias[]) { | ||
return 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 = replaceFilterKey(filterKey, propPrefix, INDEXOF_REGEX); | ||
} else if (FUNCTION_REGEX.test(filterKey)) { | ||
propName = replaceFilterKey(filterKey, propPrefix, FUNCTION_REGEX); | ||
} 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, aliases); | ||
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; | ||
}, | ||
[] | ||
); | ||
} | ||
|
||
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 = processFilterObj(filter, propPrefix, aliases); | ||
|
||
filterExpr = filtersArray.join(' and '); | ||
} /* else { | ||
throw new Error(`Unexpected filters type: ${filter}`); | ||
} */ | ||
return filterExpr; | ||
} | ||
|
||
function buildCollectionClause(lambdaParameter: string, value: any, op: string, propName: string, aliases: Alias[]) { | ||
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}`; | ||
} |
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