diff options
| author | ST-DDT <[email protected]> | 2022-05-07 10:25:37 +0200 |
|---|---|---|
| committer | GitHub <[email protected]> | 2022-05-07 08:25:37 +0000 |
| commit | a60d5e3ea3d1109b90cbb51d8a4a10aba2290ada (patch) | |
| tree | bb3dbbfe9dc7c3659b61631418b74208be7210d0 /src | |
| parent | f2c3a39563c706129ff5622c21fe3168707be77b (diff) | |
| download | faker-a60d5e3ea3d1109b90cbb51d8a4a10aba2290ada.tar.xz faker-a60d5e3ea3d1109b90cbb51d8a4a10aba2290ada.zip | |
feat: support locale definitions directly from faker.fake (#884)
Diffstat (limited to 'src')
| -rw-r--r-- | src/modules/fake/index.ts | 23 |
1 files changed, 18 insertions, 5 deletions
diff --git a/src/modules/fake/index.ts b/src/modules/fake/index.ts index a9f2a22a..a94d8845 100644 --- a/src/modules/fake/index.ts +++ b/src/modules/fake/index.ts @@ -88,16 +88,29 @@ export class Fake { // split the method into module and function const parts = method.split('.'); - if (this.faker[parts[0]] == null) { - throw new FakerError(`Invalid module: ${parts[0]}`); + let currentModuleOrMethod: unknown = this.faker; + let currentDefinitions: unknown = this.faker.definitions; + + // Search for the requested method or definition + for (const part of parts) { + currentModuleOrMethod = currentModuleOrMethod?.[part]; + currentDefinitions = currentDefinitions?.[part]; } - if (this.faker[parts[0]][parts[1]] == null) { - throw new FakerError(`Invalid method: ${parts[0]}.${parts[1]}`); + // Make method executable + let fn: (args?: unknown) => unknown; + if (typeof currentModuleOrMethod === 'function') { + fn = currentModuleOrMethod as (args?: unknown) => unknown; + } else if (Array.isArray(currentDefinitions)) { + fn = () => + this.faker.helpers.arrayElement(currentDefinitions as unknown[]); + } else { + throw new FakerError(`Invalid module method or definition: ${method} +- faker.${method} is not a function +- faker.definitions.${method} is not an array`); } // assign the function from the module.function namespace - let fn: (args?: unknown) => string = this.faker[parts[0]][parts[1]]; fn = fn.bind(this); // If parameters are populated here, they are always going to be of string type |
