-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathindex.ts
More file actions
213 lines (201 loc) · 5.4 KB
/
index.ts
File metadata and controls
213 lines (201 loc) · 5.4 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
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
import { ExecutionResult } from 'graphql'
import {
StorageEngineConfig,
StorageEngine,
GraphQLInputData,
GraphQLQueryData,
} from '@cloudgraph/sdk'
import { isEmpty } from 'lodash'
import DGraphClientWrapper from './base'
import {
GET_SCHEMA_QUERY,
processGQLExecutionResult,
UPDATE_SCHEMA_QUERY,
} from './utils'
import { fileUtils, sleep } from '../../utils'
export default class DgraphEngine
extends DGraphClientWrapper
implements StorageEngine
{
constructor(config: StorageEngineConfig) {
super(config)
this.axiosPromises = []
}
axiosPromises: (() => Promise<void>)[]
async healthCheck(showInitialStatus = true): Promise<boolean> {
showInitialStatus &&
this.logger.debug(`running dgraph health check at ${this.host}`)
try {
const healthCheck = await this.generateAxiosRequest({
path: '/health?all',
headers: {
'Content-Type': 'application/json',
},
})
this.logger.debug(healthCheck.data)
return true
} catch (error: any) {
this.logger.warn(
`dgraph at ${this.host} failed health check. Is dgraph running?`
)
this.logger.debug(error)
return false
}
}
async validateSchema(schema: string[], versionString: string): Promise<void> {
const versionCaption = versionString.split('-').join(' ')
this.logger.debug(`Validating Schema for ${versionCaption}`)
return new Promise<void>(async (resolve, reject) => {
try {
await this.generateAxiosRequest({
path: '/admin/schema/validate',
data: schema.join(),
headers: {
'Content-Type': 'text/plain',
},
})
resolve()
} catch (error: any) {
const {
response: {
data: { errors },
},
} = error
this.logger.error('Schema validation failed')
const errMsgs = errors.map((e: Error) =>
e.message.replace('input:', 'line ')
)
this.logger.error(
`${
errMsgs.length
} errors found in ${versionCaption} schema. Check the following lines in the schema.graphql file:\n${errMsgs.join(
'\n'
)}`
)
reject()
}
})
}
async setSchema(
schemas: string[],
config?: { overwrite: string }
): Promise<void> {
const schema = schemas.join()
const data = {
query: UPDATE_SCHEMA_QUERY,
variables: {
schema,
},
}
try {
await this.generateAxiosRequest({
path: '/admin',
data,
})
.then((res: ExecutionResult) => {
const { data: resData, errors } = res
processGQLExecutionResult({
reqData: data,
resData,
errors,
})
if (isEmpty(errors) && config?.overwrite) {
fileUtils.writeGraphqlSchemaToFile(`${config.overwrite}/cg`, schema)
}
})
.catch(error => Promise.reject(error))
sleep(3)
} catch (error: any) {
const {
response: { data: resData, errors },
message,
} = error
this.logger.error(
'There was an issue pushing the schema into the Dgraph db'
)
this.logger.debug(message)
processGQLExecutionResult({
reqData: data,
resData,
errors,
})
}
}
async getSchema(): Promise<string> {
try {
const { data } = await this.query(GET_SCHEMA_QUERY, '/admin')
return data?.getGQLSchema?.schema || ''
} catch (error: any) {
const {
response: { data: resData, errors } = { data: null, errors: null },
message,
} = error ?? {}
this.logger.error('There was an issue getting the Dgraph schema')
this.logger.debug(message)
processGQLExecutionResult({ resData, errors })
return ''
}
}
query(query: string, path = '/graphql'): Promise<any> {
return this.generateAxiosRequest({
path,
data: {
query,
},
})
.then((res: ExecutionResult) => {
const { data: resData } = res
return resData
})
.catch(error => Promise.reject(error))
}
/**
* Add Service Mutation to axiosPromises Array
*/
push(data: GraphQLInputData): void {
const { query, input, patch } = data
const queryData: GraphQLQueryData = {
query,
variables: {
input,
patch,
},
}
this.axiosPromises.push(() =>
this.generateAxiosRequest({
path: '/graphql',
data: queryData,
})
.then((res: ExecutionResult) => {
const { data: resData, errors } = res
processGQLExecutionResult({
reqData: queryData,
resData,
errors,
service: data.name,
})
})
.catch(error => Promise.reject(error))
)
}
/**
* Executes mutations sequentially into Dgraph
*/
async run(): Promise<void> {
for (const mutation of this.axiosPromises) {
try {
await mutation()
} catch (error: any) {
const {
response: { data: resData, errors } = { data: null, errors: null },
message,
} = error ?? {}
this.logger.error('There was an issue pushing data into the Dgraph db')
this.logger.debug(message)
processGQLExecutionResult({ resData, errors })
}
}
// Ensure mutations array is clean after execution
this.axiosPromises = []
}
}