|
| 1 | +import { FormDataType, Method, UrlMethodPair, UseFormArguments } from './types' |
| 2 | + |
| 3 | +export class UseFormUtils { |
| 4 | + public static normalizeWayfinderArgsToCallback( |
| 5 | + ...args: [UrlMethodPair | (() => UrlMethodPair)] | [Method | (() => Method), string | (() => string)] |
| 6 | + ): () => UrlMethodPair { |
| 7 | + return () => { |
| 8 | + if (args.length === 2) { |
| 9 | + return { |
| 10 | + method: typeof args[0] === 'function' ? args[0]() : args[0], |
| 11 | + url: typeof args[1] === 'function' ? args[1]() : args[1], |
| 12 | + } |
| 13 | + } |
| 14 | + |
| 15 | + return typeof args[0] === 'function' ? args[0]() : args[0] |
| 16 | + } |
| 17 | + } |
| 18 | + |
| 19 | + public static parseUseFormArgs<TForm extends FormDataType<TForm>>( |
| 20 | + ...args: UseFormArguments<TForm> |
| 21 | + ): { |
| 22 | + rememberKey: string | null |
| 23 | + data: TForm | (() => TForm) |
| 24 | + precognitionEndpoint: (() => UrlMethodPair) | null |
| 25 | + } { |
| 26 | + // Pattern 1: [data: TForm | (() => TForm)] |
| 27 | + if (args.length === 1) { |
| 28 | + return { |
| 29 | + rememberKey: null, |
| 30 | + data: args[0] as TForm | (() => TForm), |
| 31 | + precognitionEndpoint: null, |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + // Pattern 2 & 3: Two arguments - need to distinguish by first arg type |
| 36 | + if (args.length === 2) { |
| 37 | + if (typeof args[0] === 'string') { |
| 38 | + // Pattern 2: [rememberKey: string, data: TForm | (() => TForm)] |
| 39 | + return { |
| 40 | + rememberKey: args[0], |
| 41 | + data: args[1] as TForm | (() => TForm), |
| 42 | + precognitionEndpoint: null, |
| 43 | + } |
| 44 | + } else { |
| 45 | + // Pattern 3: [urlMethodPair: UrlMethodPair | (() => UrlMethodPair), data: TForm | (() => TForm)] |
| 46 | + return { |
| 47 | + rememberKey: null, |
| 48 | + data: args[1] as TForm | (() => TForm), |
| 49 | + precognitionEndpoint: this.normalizeWayfinderArgsToCallback(args[0]), |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + // Pattern 4: [method: Method | (() => Method), url: string | (() => string), data: TForm | (() => TForm)] |
| 55 | + return { |
| 56 | + rememberKey: null, |
| 57 | + data: args[2] as TForm | (() => TForm), |
| 58 | + precognitionEndpoint: this.normalizeWayfinderArgsToCallback(args[0], args[1]), |
| 59 | + } |
| 60 | + } |
| 61 | +} |
0 commit comments