-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
common.ts
370 lines (322 loc) · 8.04 KB
/
common.ts
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
import chalk from 'chalk'
import indent from 'indent-string'
import leven from 'js-levenshtein'
import { DMMF } from '../dmmf-types'
export interface Dictionary<T> {
[key: string]: T
}
export const keyBy: <T>(
collection: T[],
iteratee: (value: T) => string,
) => Dictionary<T> = (collection, iteratee) => {
return collection.reduce<any>((acc, curr) => {
acc[iteratee(curr)] = curr
return acc
}, {})
}
export const ScalarTypeTable = {
String: true,
Int: true,
Float: true,
Boolean: true,
Long: true,
DateTime: true,
ID: true,
UUID: true,
Json: true,
}
export function isScalar(str: string): boolean {
if (typeof str !== 'string') {
return false
}
return ScalarTypeTable[str] || false
}
export const GraphQLScalarToJSTypeTable = {
String: 'string',
Int: 'number',
Float: 'number',
Boolean: 'boolean',
Long: 'number',
DateTime: ['Date', 'string'],
ID: 'string',
UUID: 'string',
Json: 'JsonValue',
}
export const JSTypeToGraphQLType = {
string: 'String',
boolean: 'Boolean',
object: 'Json',
}
export function stringifyGraphQLType(
type: string | DMMF.InputType | DMMF.Enum,
) {
if (typeof type === 'string') {
return type
}
return type.name
}
export function wrapWithList(str: string, isList: boolean) {
if (isList) {
return `List<${str}>`
}
return str
}
export function getGraphQLType(
value: any,
potentialType?: string | DMMF.Enum | DMMF.InputType,
): string {
if (value === null) {
return 'null'
}
if (Array.isArray(value)) {
let scalarTypes = value.reduce((acc, val) => {
const type = getGraphQLType(val, potentialType)
if (!acc.includes(type)) {
acc.push(type)
}
return acc
}, [])
// Merge Float and Int together
if (scalarTypes.includes('Float') && scalarTypes.includes('Int')) {
scalarTypes = ['Float']
}
return `List<${scalarTypes.join(' | ')}>`
}
const jsType = typeof value
if (jsType === 'number') {
if (Math.trunc(value) === value) {
return 'Int'
} else {
return 'Float'
}
}
if (Object.prototype.toString.call(value) === '[object Date]') {
return 'DateTime'
}
if (jsType === 'string') {
if (
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(
value,
)
) {
return 'UUID'
}
const date = new Date(value)
if (
potentialType &&
typeof potentialType === 'object' &&
(potentialType as DMMF.Enum).values &&
(potentialType as DMMF.Enum).values.includes(value)
) {
return potentialType.name
}
if (date.toString() === 'Invalid Date') {
return 'String'
}
if (
/\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)/.test(
value,
)
) {
return 'DateTime'
}
}
return JSTypeToGraphQLType[jsType]
}
export function graphQLToJSType(gql: string) {
return GraphQLScalarToJSTypeTable[gql]
}
export function getSuggestion(
str: string,
possibilities: string[],
): string | null {
const bestMatch = possibilities.reduce<{
distance: number
str: string | null
}>(
(acc, curr) => {
const distance = leven(str, curr)
if (distance < acc.distance) {
return {
distance,
str: curr,
}
}
return acc
},
{
// heuristic to be not too strict, but allow some big mistakes (<= ~ 5)
distance: Math.min(
Math.floor(str.length) * 1.1,
...possibilities.map((p) => p.length * 3),
),
str: null,
},
)
return bestMatch.str
}
export function stringifyInputType(
input: string | DMMF.InputType | DMMF.Enum,
greenKeys: boolean = false,
): string {
if (typeof input === 'string') {
return input
}
if ((input as DMMF.Enum).values) {
return `enum ${input.name} {\n${indent(
(input as DMMF.Enum).values.join(', '),
2,
)}\n}`
} else {
const body = indent(
(input as DMMF.InputType).fields // TS doesn't discriminate based on existence of fields properly
.map((arg) => {
const argInputType = arg.inputType[0]
const key = `${arg.name}`
const str = `${greenKeys ? chalk.green(key) : key}${
argInputType.isRequired ? '' : '?'
}: ${chalk.white(
arg.inputType
.map((argType) =>
argIsInputType(argType.type)
? argType.type.name
: wrapWithList(
stringifyGraphQLType(argType.type),
argType.isList,
),
)
.join(' | '),
)}`
if (!argInputType.isRequired) {
return chalk.dim(str)
}
return str
})
.join('\n'),
2,
)
return `${chalk.dim('type')} ${chalk.bold.dim(input.name)} ${chalk.dim(
'{',
)}\n${body}\n${chalk.dim('}')}`
}
}
function argIsInputType(arg: DMMF.ArgType): arg is DMMF.InputType {
if (typeof arg === 'string') {
return false
}
return true
}
export function getInputTypeName(
input: string | DMMF.InputType | DMMF.SchemaField | DMMF.Enum,
) {
if (typeof input === 'string') {
return input
}
return input.name
}
export function getOutputTypeName(
input: string | DMMF.OutputType | DMMF.SchemaField | DMMF.Enum,
) {
if (typeof input === 'string') {
return input
}
return input.name
}
export function inputTypeToJson(
input: string | DMMF.InputType | DMMF.Enum,
isRequired: boolean,
nameOnly: boolean = false,
): string | object {
if (typeof input === 'string') {
return input
}
if ((input as DMMF.Enum).values) {
return (input as DMMF.Enum).values.join(' | ')
}
// TS "Trick" :/
const inputType: DMMF.InputType = input as DMMF.InputType
// If the parent type is required and all fields are non-scalars,
// it's very useful to show to the user, which options they actually have
const showDeepType =
isRequired &&
inputType.fields.every((arg) => arg.inputType[0].kind === 'object') &&
!inputType.isWhereType &&
!inputType.atLeastOne
if (nameOnly) {
return getInputTypeName(input)
}
return inputType.fields.reduce((acc, curr) => {
const argInputType = curr.inputType[0]
acc[curr.name + (argInputType.isRequired ? '' : '?')] =
curr.isRelationFilter && !showDeepType && !argInputType.isRequired
? getInputTypeName(argInputType.type)
: inputTypeToJson(argInputType.type, argInputType.isRequired, true)
return acc
}, {})
}
export function destroyCircular(from, seen: any[] = []) {
const to: any = Array.isArray(from) ? [] : {}
seen.push(from)
for (const key of Object.keys(from)) {
const value = from[key]
if (typeof value === 'function') {
continue
}
if (!value || typeof value !== 'object') {
to[key] = value
continue
}
if (seen.indexOf(from[key]) === -1) {
to[key] = destroyCircular(from[key], seen.slice(0))
continue
}
to[key] = '[Circular]'
}
if (typeof from.name === 'string') {
to.name = from.name
}
if (typeof from.message === 'string') {
to.message = from.message
}
if (typeof from.stack === 'string') {
to.stack = from.stack
}
return to
}
export function unionBy<T>(
arr1: T[],
arr2: T[],
iteratee: (element: T) => string | number,
): T[] {
const map = {}
for (const element of arr1) {
map[iteratee(element)] = element
}
for (const element of arr2) {
const key = iteratee(element)
if (!map[key]) {
map[key] = element
}
}
return Object.values(map)
}
export function uniqBy<T>(
arr: T[],
iteratee: (element: T) => string | number,
): T[] {
const map = {}
for (const element of arr) {
map[iteratee(element)] = element
}
return Object.values(map)
}
export function capitalize(str: string): string {
return str[0].toUpperCase() + str.slice(1)
}
/**
* Converts the first character of a word to lower case
* @param name
*/
export function lowerCase(name: string): string {
return name.substring(0, 1).toLowerCase() + name.substring(1)
}