-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathgenType.ts
More file actions
182 lines (157 loc) · 6.21 KB
/
genType.ts
File metadata and controls
182 lines (157 loc) · 6.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
import _ from 'lodash';
import assert from '../assert';
import { GlobalConfig, ResourceConfig, LanguageOption } from '../config';
function errorPrefix(resourcePath: ReadonlyArray<string>): string {
return `[dataloader-codegen :: ${resourcePath.join('.')}]`;
}
// The reference at runtime to where the underlying resource lives
const resourceReference = (resourcePath: ReadonlyArray<string>) => ['resources', ...resourcePath].join('.');
/**
* Get the reference to the type representing the resource function this resource
*/
export function getResourceTypeReference(resourceConfig: ResourceConfig, resourcePath: ReadonlyArray<string>) {
function toPropertyTypePath(path: ReadonlyArray<string>): string {
assert(path.length >= 1, 'expected resource path to be a not empty array');
if (path.length === 1) {
return path[0];
}
return `$PropertyType<${toPropertyTypePath(path.slice(0, -1))}, '${path.slice(-1)}'>`;
}
return toPropertyTypePath(['ResourcesType', ...resourcePath]);
}
function getResourceArg(resourceConfig: ResourceConfig, resourcePath: ReadonlyArray<string>) {
// TODO: We assume that the resource accepts a single dict argument. Let's
// make thie configurable to handle resources that use seperate arguments.
return `\
$Call<
ExtractArg,
[${getResourceTypeReference(resourceConfig, resourcePath)}]
>`;
}
/**
* Extract the type T from a Set<T> resource (in this case a batchKey's resource)
* using its `.has(T)`'s function paremeter type
*/
export function getNewKeyTypeFromBatchKeySetType(batchKey: string, resourceArgs: string) {
return `\
$Call<
ExtractArg,
[$PropertyType<$PropertyType<${resourceArgs}, '${batchKey}'>, 'has'>]
>`;
}
export function getLoaderTypeKey(resourceConfig: ResourceConfig, resourcePath: ReadonlyArray<string>) {
// TODO: We assume that the resource accepts a single dict argument. Let's
// make this configurable to handle resources that use seperate arguments.
const resourceArgs = getResourceArg(resourceConfig, resourcePath);
if (resourceConfig.isBatchResource) {
// Extract newKeyType from the batch key's Array's type
// We add NonMaybeType before batch key element type to force the batch key to be required, regardless if the OpenAPI spec specifies it as being optional
let newKeyType = `${resourceConfig.newKey}: $ElementType<$NonMaybeType<$PropertyType<${resourceArgs}, '${resourceConfig.batchKey}'>>, 0>`;
if (resourceConfig.isBatchKeyASet) {
/**
* New key's type has to be extracted differently if the batch key's resource
* expects them in the form of a Set
*/
newKeyType = `${resourceConfig.newKey}: ${getNewKeyTypeFromBatchKeySetType(
resourceConfig.batchKey,
resourceArgs,
)}`;
}
return `{|
...$Diff<${resourceArgs}, {
${resourceConfig.batchKey}: $PropertyType<${resourceArgs}, '${resourceConfig.batchKey}'>
}>,
...{| ${newKeyType} |}
|}`;
}
return resourceArgs;
}
export function getLoaderTypeVal(resourceConfig: ResourceConfig, resourcePath: ReadonlyArray<string>) {
// TODO: We assume that the resource accepts a single dict argument. Let's
// make this configurable to handle resources that use seperate arguments.
const resourceArgs = getResourceArg(resourceConfig, resourcePath);
// TODO: DRY up in codegen to something like RetVal<resource>
let retVal = `\
$Call<
ExtractPromisedReturnValue<[${resourceArgs}]>,
${getResourceTypeReference(resourceConfig, resourcePath)}
>`;
if (resourceConfig.isBatchResource) {
/**
* If the response is nested in some path, unwrap it.
*
* Example:
* ```js
* {
* businesses: [
* { id: 1, name: 'foo' },
* { id: 2, name: 'bar' }
* ]
* }
* ```
*
* Becomes:
* ```js
* [
* { id: 1, name: 'foo' },
* { id: 2, name: 'bar' }
* ]
* ```
*/
if (resourceConfig.nestedPath) {
retVal = `$PropertyType<${retVal}, '${resourceConfig.nestedPath}'>`;
}
retVal = resourceConfig.isResponseDictionary ? `$Values<${retVal}>` : `$ElementType<${retVal}, 0>`;
}
return retVal;
}
export function getLoaderType(resourceConfig: ResourceConfig, resourcePath: ReadonlyArray<string>) {
const key = getLoaderTypeKey(resourceConfig, resourcePath);
const val = getLoaderTypeVal(resourceConfig, resourcePath);
return `DataLoader<
${key},
${val},
// This third argument is the cache key type. Since we use objectHash in cacheKeyOptions, this is "string".
string,
>`;
}
export function getLoadersTypeMap(
config: object,
paths: ReadonlyArray<ReadonlyArray<string>>,
current: ReadonlyArray<string>,
) {
if (_.isEqual(paths, [[]])) {
return getLoaderType(_.get(config, current.join('.')), current);
}
const nextValues = _.uniq(paths.map((p) => p[0]));
const objectProperties: ReadonlyArray<string> = nextValues.map(
(nextVal) =>
`${nextVal}: ${getLoadersTypeMap(
config,
paths.filter((p) => p[0] === nextVal).map((p) => p.slice(1)),
[...current, nextVal],
)},`,
);
return `$ReadOnly<{|
${objectProperties.join('\n')}
|}>`;
}
export function getResourceTypings(
config: GlobalConfig,
): { printResourceTypeImports: () => string; printResourcesType: () => string } {
if (
config.typings &&
config.typings.embedResourcesType &&
config.typings.embedResourcesType.imports &&
config.typings.embedResourcesType.ResourcesType
) {
return {
printResourceTypeImports: () => config.typings.embedResourcesType.imports,
printResourcesType: () => config.typings.embedResourcesType.ResourcesType,
};
}
return {
printResourceTypeImports: () => '',
printResourcesType: () => '',
};
}