-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
common.ts
469 lines (403 loc) · 9.88 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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
import chalk from 'chalk'
import indent from 'indent-string'
import leven from 'js-levenshtein'
import { BaseField, DMMF } from '../dmmf-types'
import Decimal from 'decimal.js'
import { DMMFClass } from '../dmmf'
export interface Dictionary<T> {
[key: string]: T
}
export const keyBy: <T>(collection: T[], prop: string) => Dictionary<T> = (
collection,
prop,
) => {
const acc = {}
for (const obj of collection) {
const key = obj[prop]
acc[key] = obj
}
return acc
}
export const keyBy2: <T>(
collection1: T[],
collection2: T[],
prop: string,
) => Dictionary<T> = (collection1, collection2, prop) => {
const acc = {}
for (const obj of collection1) {
const key = obj[prop]
acc[key] = obj
}
for (const obj of collection2) {
const key = obj[prop]
acc[key] = obj
}
return acc
}
export const ScalarTypeTable = {
String: true,
Int: true,
Float: true,
Boolean: true,
Long: true,
DateTime: true,
ID: true,
UUID: true,
Json: true,
Bytes: true,
Decimal: true,
BigInt: true,
}
export function isScalar(str: string): boolean {
if (typeof str !== 'string') {
return false
}
return ScalarTypeTable[str] || false
}
export const needNamespace = {
Json: 'JsonValue',
Decimal: 'Decimal',
}
export function needsNamespace(field: BaseField, dmmf: DMMFClass): boolean {
if (typeof field.type === 'string') {
if (dmmf.datamodelEnumMap[field.type]) {
return false
}
if (GraphQLScalarToJSTypeTable[field.type]) {
return Boolean(needNamespace[field.type])
}
}
return true
}
export const GraphQLScalarToJSTypeTable = {
String: 'string',
Int: 'number',
Float: 'number',
Boolean: 'boolean',
Long: 'number',
DateTime: ['Date', 'string'],
ID: 'string',
UUID: 'string',
Json: 'JsonValue',
Bytes: 'Buffer',
Decimal: ['Decimal', 'number', 'string'],
BigInt: ['BigInt', 'number'],
}
export const JSOutputTypeToInputType = {
JsonValue: 'InputJsonValue',
}
export const JSTypeToGraphQLType = {
string: 'String',
boolean: 'Boolean',
object: 'Json',
}
export function stringifyGraphQLType(
type: string | DMMF.InputType | DMMF.SchemaEnum,
) {
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.SchemaEnum | DMMF.InputType,
): string {
if (value === null) {
return 'null'
}
if (Object.prototype.toString.call(value) === '[object BigInt]') {
return 'BigInt'
}
// https://github.com/MikeMcl/decimal.js/blob/master/decimal.js#L4499
if (Decimal.isDecimal(value)) {
return 'Decimal'
}
if (Buffer.isBuffer(value)) {
return 'Bytes'
}
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.SchemaEnum).values &&
(potentialType as DMMF.SchemaEnum).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.SchemaEnum,
greenKeys = false,
): string {
if (typeof input === 'string') {
return input
}
if ((input as DMMF.SchemaEnum).values) {
return `enum ${input.name} {\n${indent(
(input as DMMF.SchemaEnum).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 key = `${arg.name}`
const str = `${greenKeys ? chalk.green(key) : key}${
arg.isRequired ? '' : '?'
}: ${chalk.white(
arg.inputTypes
.map((argType) => {
return wrapWithList(
argIsInputType(argType.type)
? argType.type.name
: stringifyGraphQLType(argType.type),
argType.isList,
)
})
.join(' | '),
)}`
if (!arg.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('}')}`
}
}
export 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.SchemaEnum,
) {
if (typeof input === 'string') {
if (input === 'Null') {
return 'null'
}
return input
}
return input.name
}
export function getOutputTypeName(
input: string | DMMF.OutputType | DMMF.SchemaField | DMMF.SchemaEnum,
) {
if (typeof input === 'string') {
return input
}
return input.name
}
export function inputTypeToJson(
input: string | DMMF.InputType | DMMF.SchemaEnum,
isRequired: boolean,
nameOnly = false,
): string | object {
if (typeof input === 'string') {
if (input === 'Null') {
return 'null'
}
return input
}
if ((input as DMMF.SchemaEnum).values) {
return (input as DMMF.SchemaEnum).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.inputTypes[0].location === 'inputObjectTypes' ||
arg.inputTypes[1]?.location === 'inputObjectTypes',
)
if (nameOnly) {
return getInputTypeName(input)
}
return inputType.fields.reduce((acc, curr) => {
let str = ''
if (!showDeepType && !curr.isRequired) {
str = curr.inputTypes
.map((argType) => getInputTypeName(argType.type))
.join(' | ')
} else {
str = curr.inputTypes
.map((argInputType) =>
inputTypeToJson(argInputType.type, curr.isRequired, true),
)
.join(' | ')
}
acc[curr.name + (curr.isRequired ? '' : '?')] = str
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)
}
export function isGroupByOutputName(type: string): boolean {
return type.endsWith('GroupByOutputType')
}
export function isSchemaEnum(type: any): type is DMMF.SchemaEnum {
return (
typeof type === 'object' &&
type.name &&
typeof type.name === 'string' &&
type.values &&
Array.isArray(type.values)
)
}