Last active
February 22, 2023 02:07
-
-
Save Grubba27/4dd728e1c3c823e44968ce921543b4db to your computer and use it in GitHub Desktop.
try implementing
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
| type Creator = | |
| <Name extends string, Args, Response> | |
| (name: Name, runner: (args: Args) => Response, subModule?: RCreator<Name, Args, Response>) => | |
| RCreator<Name, Args, Response> | |
| const createModule: Creator = (name, runner, subModule) => { | |
| return { | |
| ...subModule, | |
| [name]: runner | |
| } | |
| } | |
| const k = createModule('foo', (s: string) => 1) | |
| const t = {...k} | |
| type RCreator<Name extends string, Args, Response> = { [P in Name]: (args: Args) => Response } | |
| const factory = | |
| <Name extends string, Args, Response> | |
| (subModules?: RCreator<Name, Args, Response>) => { | |
| const addMethod = | |
| <Name extends string, Args, Response> | |
| (name: Name, runner: (args: Args) => Response) => { | |
| const op: RCreator<Name, Args, Response> = createModule(name, runner) | |
| const module: RCreator<Name, Args, Response> = { | |
| ...op, | |
| ...subModules, | |
| } | |
| return factory(module as RCreator<Name, Args, Response> ) | |
| } | |
| const addQuery = addMethod | |
| const addMutation = addMethod | |
| const toRunner = () => { | |
| if (!subModules) { | |
| throw new Error('No modules added') | |
| } | |
| return subModules | |
| } | |
| return { | |
| addMethod, | |
| addQuery, | |
| addMutation, | |
| toRunner | |
| } | |
| } | |
| const M = | |
| factory() | |
| .addMethod('sum', ({a, b}: { a: number, b: number }) => a + b) | |
| .addMethod('sub', ({a, b}: { a: number, b: number }) => a - b) | |
| .addMutation('mul', ({a, b}: { a: number, b: number }) => a * b) | |
| .toRunner() | |
| const r = M.mul({a: 1, b: 2}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment