Last active
March 2, 2021 23:45
-
-
Save arantesxyz/34861cfaf5d86836ebd0cebf7e3d9701 to your computer and use it in GitHub Desktop.
Function to validade javascript objects
This file contains hidden or 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
| /** | |
| * | |
| * @param {Any} object Any type to be validated | |
| * @param {String/Array} required Type name to validade | |
| * @param {Function} callback Optional function to be called instead of throwing the error | |
| */ | |
| function validade(object, required = [], callback) { | |
| const type = [].concat(required).map((item) => item.toLowerCase()); | |
| if (object === null && type.includes("null")) return; | |
| const objectType = Array.isArray(object) ? "array" : typeof object; | |
| if (type.includes(objectType)) return; | |
| if (!callback) | |
| throw new Error( | |
| `Expected ${type.join("/")} but received ${objectType}` | |
| ); | |
| callback(objectType); | |
| } |
This file contains hidden or 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
| /** | |
| * | |
| * @param {Unknown} object Any type to be validated | |
| * @param {String | Array<String>} acceptedTypes Type name to validade | |
| * @param {String | Function} action? Field name for error or custom function | |
| * to be executed instead of throwing the error | |
| */ | |
| export default function typeValidator( | |
| object: unknown, | |
| acceptedTypes: string | Array<string>, | |
| action: string | ((type: string) => void) | |
| ): void { | |
| const arr: Array<string> = [] | |
| const type = arr.concat(acceptedTypes).map(item => item.toLowerCase()) | |
| if (object === null && type.includes('null')) return | |
| const objectType = Array.isArray(object) ? 'array' : typeof object | |
| if (type.includes(objectType)) return | |
| if (action instanceof Function) { | |
| return action(objectType) | |
| } | |
| throw new Error( | |
| `Expected ${action} to be of type ${type.join( | |
| '/' | |
| )} but received ${objectType}` | |
| ) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment