1
1
import * as t from 'io-ts' ;
2
2
import { Json } from 'io-ts-types' ;
3
3
import { flattened , optional , optionalized } from './combinators' ;
4
- import { OutputConstrainedProps } from './utils' ;
5
4
6
5
export const GenericHttpRequest = optionalized ( {
7
6
// DISCUSS: renaming this to something more specific, e.g. route, or path, or routeParams, or pathParams
@@ -18,13 +17,46 @@ export type HttpRequestCodec<T> = t.Type<
18
17
> ;
19
18
20
19
export type HttpRequestCombinatorProps = {
21
- params ?: NonNullable < OutputConstrainedProps < string | undefined > > ;
22
- query ?: NonNullable < OutputConstrainedProps < string | string [ ] | undefined > > ;
23
- headers ?: NonNullable < OutputConstrainedProps < string | undefined > > ;
20
+ params ?: NonNullable < t . Props > ;
21
+ query ?: NonNullable < t . Props > ;
22
+ headers ?: NonNullable < t . Props > ;
24
23
body ?: NonNullable < t . Props > ;
25
24
} ;
26
25
27
- export function httpRequest < Props extends HttpRequestCombinatorProps > ( props : Props ) {
26
+ /**
27
+ * Attempts to produce a helpful error message when invalid codecs are passed to `httpRequest`
28
+ * It is a workaround until something like https://github.com/microsoft/TypeScript/pull/40468
29
+ * is merged.
30
+ */
31
+ type EmitOutputTypeErrors <
32
+ P extends t . Props | undefined ,
33
+ O ,
34
+ OName extends string ,
35
+ > = P extends undefined
36
+ ? P
37
+ : {
38
+ [ K in keyof P & string ] : P [ K ] extends t . Type < any , O , any >
39
+ ? P [ K ]
40
+ : `Codec's output type is not assignable to ${OName } . Try using one like \`NumberFromString \``;
41
+ } ;
42
+
43
+ type EmitPropsErrors < P extends HttpRequestCombinatorProps > = {
44
+ params ?: EmitOutputTypeErrors < P [ 'params' ] , string | undefined , 'string | undefined' > ;
45
+ query ?: EmitOutputTypeErrors <
46
+ P [ 'query' ] ,
47
+ string | string [ ] | undefined ,
48
+ 'string | string[] | undefined'
49
+ > ;
50
+ headers ?: EmitOutputTypeErrors <
51
+ P [ 'headers' ] ,
52
+ string | undefined ,
53
+ 'string | undefined'
54
+ > ;
55
+ } ;
56
+
57
+ export function httpRequest <
58
+ Props extends HttpRequestCombinatorProps & EmitPropsErrors < Props > ,
59
+ > ( props : Props ) {
28
60
return flattened ( 'httpRequest' , {
29
61
query : { } ,
30
62
params : { } ,
0 commit comments