forked from mockoon/mockoon
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Closes mockoon#1124
- Loading branch information
Showing
4 changed files
with
110 additions
and
0 deletions.
There are no files selected for viewing
59 changes: 59 additions & 0 deletions
59
packages/commons-server/src/libs/templating-helpers/helpers/find.ts
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,59 @@ | ||
import { fromSafeString } from '../../utils'; | ||
|
||
const find = function (...args) { | ||
const parameters = args.slice(0, -1); | ||
|
||
if (parameters.length === 0) { | ||
return ''; | ||
} | ||
|
||
const [arr, ...filters] = parameters; | ||
|
||
if (!(arr instanceof Array)) { | ||
return ''; | ||
} | ||
if (!arr.length || !filters.length) { | ||
return undefined; | ||
} | ||
|
||
const validate = (payload, condition) => { | ||
if ( | ||
condition !== null && | ||
typeof condition === 'object' && | ||
!Array.isArray(condition) | ||
) { | ||
if (typeof payload === 'object') { | ||
const keys = Object.keys(condition); | ||
|
||
return keys.every((k) => | ||
validate(payload[k], fromSafeString(condition[k])) | ||
); | ||
} | ||
|
||
return false; | ||
} | ||
|
||
return payload === condition; | ||
}; | ||
|
||
const and = (item, conditions, { or }) => | ||
conditions.every((subConditions) => { | ||
if (Array.isArray(subConditions)) { | ||
return or(item, subConditions); | ||
} | ||
|
||
return validate(item, subConditions); | ||
}); | ||
const or = (item, conditions) => | ||
conditions.some((subConditions) => { | ||
if (Array.isArray(subConditions)) { | ||
return and(item, subConditions, { or }); | ||
} | ||
|
||
return validate(item, subConditions); | ||
}); | ||
|
||
return arr.find((item) => or(item, filters)); | ||
}; | ||
|
||
export default find; |
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
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