-
-
Notifications
You must be signed in to change notification settings - Fork 34
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
reafactor: better typings and format
- Loading branch information
1 parent
09421df
commit f66674c
Showing
2 changed files
with
20 additions
and
22 deletions.
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,33 +1,31 @@ | ||
type JsonMapperSignature<TDefaultResult> = <TJsonResult>(value: string) => TJsonResult | TDefaultResult; | ||
|
||
type callSignature = <TJsonResult, TDefaultResult>(value: string) => TJsonResult | TDefaultResult; | ||
|
||
type JsonMapper = { | ||
default: <TDefaultResult>(defaultResult: TDefaultResult) => JsonMapper | ||
} & callSignature; | ||
export type JsonMapper<TJsonResult> = JsonMapperSignature<TJsonResult> & { | ||
default: <TDefaultResult>(value: TDefaultResult) => JsonMapper<TDefaultResult>; | ||
}; | ||
|
||
interface IJsonMapperOptions { | ||
default: any; | ||
interface IJsonMapperOptions<TDefaultResult> { | ||
default: TDefaultResult; | ||
} | ||
|
||
const factory = (options: Readonly<IJsonMapperOptions>): JsonMapper => { | ||
const mapper = (json: string) => { | ||
const factory = <TDefaultResult>(options: Readonly<IJsonMapperOptions<TDefaultResult>>): JsonMapper<TDefaultResult> => { | ||
const mapper: JsonMapper<TDefaultResult> = <TJsonResult>(json: string): TJsonResult | TDefaultResult => { | ||
try { | ||
return JSON.parse(json); | ||
} catch (e) { | ||
return options.default | ||
return options.default; | ||
} | ||
} | ||
}; | ||
|
||
mapper.default = <TDefaultResult>(defaultResult: TDefaultResult) => factory({ | ||
...options, | ||
default: defaultResult | ||
}); | ||
mapper.default = <TJSonResult>(defaultResult: TJSonResult) => | ||
factory<TJSonResult>({ | ||
...options, | ||
default: defaultResult, | ||
}); | ||
|
||
return mapper; | ||
}; | ||
|
||
|
||
|
||
export const jsonMapper: JsonMapper = factory({ | ||
export const jsonMapper = factory({ | ||
default: null, | ||
}); | ||
}); |
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