-
Notifications
You must be signed in to change notification settings - Fork 21
/
gqlConverters.js
94 lines (76 loc) · 2.61 KB
/
gqlConverters.js
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
const { checker } = require('suma')
const { camelCase, upperFirst } = require('lodash')
const { BaseEntity } = require('gotu/src/baseEntity')
const stringCase = require('./stringCase')
function requestFieldType2gql(type, presence, input) {
let name
if (Array.isArray(type))
name = `[${requestFieldType2gql(type[0], false, input)}]`
else if (type === Number)
name = `Float`
else if (type.prototype instanceof BaseEntity)
name = `${upperFirst(camelCase(type.name))}${input ? 'Input' : ''}`
else
name = stringCase.pascalCase(type.name)
return presence ? `${name}!` : name
}
function usecaseRequest2gql(useCase, presence) {
const fields = Object.keys(useCase.requestSchema)
const output = []
for (const field of fields) {
const type = useCase.requestSchema[field]
let name = requestFieldType2gql(type, presence, true)
output.push(`${field}: ${name}`)
}
return output.join(`, `)
}
function usecaseResponse2gql(useCase, presence) {
let name = requestFieldType2gql(useCase.responseSchema, presence, false)
return name
}
function schemaOptions(options) {
return Object.assign({
presenceOnRequest: false,
presenceOnResponse: false
}, options || {})
}
function entityFieldType2gql(type) {
let name
if (Array.isArray(type)) name = `[${entityFieldType2gql(type[0])}]`
else if (type === Number) name = `Float`
else if (type.prototype instanceof BaseEntity) name = upperFirst(camelCase(type.name))
else name = type.name
return name
}
function entityField2gql(entity) {
const fields = Object.keys(entity.prototype.meta.schema)
let gql = ""
for (const field of fields) {
if(typeof entity.prototype.meta.schema[field] === 'function') continue
const { type, options } = entity.prototype.meta.schema[field]
let name = entityFieldType2gql(type)
let typeOptions = fieldOptions2gpq(options)
gql += `${field}: ${name}${typeOptions}\n`
}
return gql
}
function fieldOptions2gpq(options) {
let optionsGql = ``
const { validation } = options
if (validation) validation.presence && (optionsGql += `!`)
return optionsGql
}
function usecaseFieldToParams(useCase, schema) {
const hasResponse = !checker.isEmpty(useCase.requestSchema)
if (hasResponse) return `(${usecaseRequest2gql(useCase, schema.presenceOnRequest)}) `
return ''
}
module.exports = {
requestFieldType2gql,
usecaseRequest2gql,
usecaseResponse2gql,
usecaseFieldToParams,
schemaOptions,
entityFieldType2gql,
entityField2gql
}