-
Notifications
You must be signed in to change notification settings - Fork 6
/
sample.js
333 lines (315 loc) · 12.6 KB
/
sample.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
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
import UUID from "pure-uuid"
import * as GraphQL from "graphql"
import * as GraphQLTools from "@graphql-tools/schema"
import GraphQLToolsSequelize from "graphql-tools-sequelize"
import GraphQLToolsTypes from "graphql-tools-types"
import HAPI from "hapi"
import HAPIGraphiQL from "hapi-plugin-graphiql"
import Boom from "boom"
import Sequelize from "sequelize"
;(async function () {
/* establish database connection */
let db = new Sequelize("./sample.db", "", "", {
dialect: "sqlite", host: "", port: "", storage: "./sample.db",
define: { freezeTableName: true, timestamps: false },
logging: (msg) => { console.log("Sequelize: " + msg) },
})
await db.authenticate()
/* define database schema */
let dm = {}
dm.OrgUnit = db.define("OrgUnit", {
id: { type: Sequelize.UUID, primaryKey: true },
initials: { type: Sequelize.STRING(3), allowNull: false },
name: { type: Sequelize.STRING(100), allowNull: false }
})
dm.Person = db.define("Person", {
id: { type: Sequelize.UUID, primaryKey: true },
initials: { type: Sequelize.STRING(3), allowNull: false },
name: { type: Sequelize.STRING(100), allowNull: false },
role: { type: Sequelize.STRING(30), allowNull: true }
})
dm.OrgUnit.belongsTo(dm.OrgUnit, {
as: "parentUnit",
foreignKey: "parentUnitId"
})
dm.Person.belongsTo(dm.Person, {
as: "supervisor",
foreignKey: "personId"
})
dm.Person.belongsTo(dm.OrgUnit, {
as: "belongsTo",
foreignKey: "orgUnitId"
})
dm.OrgUnit.hasMany(dm.Person, {
as: "members",
foreignKey: "orgUnitId"
})
dm.OrgUnit.hasOne(dm.Person, {
as: "director",
foreignKey: "directorId"
})
/* on-the-fly (re-)create database schema */
await db.sync({ force: true })
/* fill database initially */
const uuid = () => (new UUID(1)).format()
const uMSG = await dm.OrgUnit.create({ id: uuid(), initials: "msg", name: "msg systems ag" })
const uXT = await dm.OrgUnit.create({ id: uuid(), initials: "XT", name: "msg Applied Technology Research (XT)" })
const uXIS = await dm.OrgUnit.create({ id: uuid(), initials: "XIS", name: "msg Information Security (XIS)" })
const pHZ = await dm.Person.create ({ id: uuid(), initials: "HZ", name: "Hans Zehetmaier" })
const pJS = await dm.Person.create ({ id: uuid(), initials: "JS", name: "Jens Stäcker" })
const pRSE = await dm.Person.create ({ id: uuid(), initials: "RSE", name: "Ralf S. Engelschall" })
const pBEN = await dm.Person.create ({ id: uuid(), initials: "BEN", name: "Bernd Endras" })
const pCGU = await dm.Person.create ({ id: uuid(), initials: "CGU", name: "Carol Gutzeit" })
const pMWS = await dm.Person.create ({ id: uuid(), initials: "MWS", name: "Mark-W. Schmidt" })
const pBWE = await dm.Person.create ({ id: uuid(), initials: "BWE", name: "Bernhard Weber" })
const pFST = await dm.Person.create ({ id: uuid(), initials: "FST", name: "Florian Stahl", role: "employee" })
await uMSG.setDirector(pHZ)
await uMSG.setMembers([ pHZ, pJS ])
await uXT.setDirector(pRSE)
await uXT.setMembers([ pRSE, pBEN, pCGU ])
await uXT.setParentUnit(uMSG)
await uXIS.setDirector(pMWS)
await uXIS.setMembers([ pMWS, pBWE, pFST ])
await uXIS.setParentUnit(uMSG)
await pJS.setSupervisor(pHZ)
await pRSE.setSupervisor(pJS)
await pBEN.setSupervisor(pRSE)
await pCGU.setSupervisor(pRSE)
await pMWS.setSupervisor(pJS)
await pBWE.setSupervisor(pMWS)
await pFST.setSupervisor(pMWS)
/* establish GraphQL to Sequelize mapping */
const validator = async (/* type, obj */) => {
return true
}
const authorizer = async (/* moment, op, type, obj, ctx */) => {
return true
}
const gts = new GraphQLToolsSequelize(db, {
validator: validator,
authorizer: authorizer,
tracer: async (record /*, ctx */) => {
console.log(`trace: record=${JSON.stringify(record)}`)
},
fts: {
"OrgUnit": [ "name" ],
"Person": [ "name" ]
}
})
await gts.boot()
/* the GraphQL schema definition */
let definition = `
schema {
query: Root
mutation: Root
}
scalar UUID
scalar JSON
type Root {
${gts.entityQuerySchema("Root", "", "OrgUnit")}
${gts.entityQuerySchema("Root", "", "OrgUnit*")}
${gts.entityQuerySchema("Root", "", "Person")}
${gts.entityQuerySchema("Root", "", "Person*")}
}
type OrgUnit {
${gts.attrIdSchema("OrgUnit")}
${gts.attrHcSchema("OrgUnit")}
initials: String
name: String
director: Person
members: [Person]!
parentUnit: OrgUnit
${gts.entityCloneSchema ("OrgUnit")}
${gts.entityCreateSchema("OrgUnit")}
${gts.entityUpdateSchema("OrgUnit")}
${gts.entityDeleteSchema("OrgUnit")}
}
type Person {
${gts.attrIdSchema("Person")}
${gts.attrHcSchema("Person")}
initials: String
name: String
role: Role
belongsTo: OrgUnit
supervisor: Person
${gts.entityCloneSchema ("Person")}
${gts.entityCreateSchema("Person")}
${gts.entityUpdateSchema("Person")}
${gts.entityDeleteSchema("Person")}
}
enum Role {
principal
employee
assistant
}
`
/* the GraphQL schema resolvers */
let resolvers = {
UUID: GraphQLToolsTypes.UUID({ name: "UUID", storage: "string" }),
JSON: GraphQLToolsTypes.JSON({ name: "JSON" }),
Root: {
OrgUnit: gts.entityQueryResolver ("Root", "", "OrgUnit"),
OrgUnits: gts.entityQueryResolver ("Root", "", "OrgUnit*"),
Person: gts.entityQueryResolver ("Root", "", "Person"),
Persons: gts.entityQueryResolver ("Root", "", "Person*"),
},
OrgUnit: {
id: gts.attrIdResolver ("OrgUnit"),
hc: gts.attrHcResolver ("OrgUnit"),
director: gts.entityQueryResolver ("OrgUnit", "director", "Person"),
members: gts.entityQueryResolver ("OrgUnit", "members", "Person*"),
parentUnit: gts.entityQueryResolver ("OrgUnit", "parentUnit", "OrgUnit"),
clone: gts.entityCloneResolver ("OrgUnit"),
create: gts.entityCreateResolver("OrgUnit"),
update: gts.entityUpdateResolver("OrgUnit"),
delete: gts.entityDeleteResolver("OrgUnit")
},
Person: {
id: gts.attrIdResolver ("Person"),
hc: gts.attrHcResolver ("Person"),
role: ({ role }) => role,
belongsTo: gts.entityQueryResolver ("Person", "belongsTo", "OrgUnit"),
supervisor: gts.entityQueryResolver ("Person", "supervisor", "Person"),
clone: gts.entityCloneResolver ("Person"),
create: gts.entityCreateResolver("Person"),
update: gts.entityUpdateResolver("Person"),
delete: gts.entityDeleteResolver("Person")
}
}
/* generate executable GraphQL schema */
let schema = GraphQLTools.makeExecutableSchema({
typeDefs: [ definition ],
resolvers: resolvers,
allowUndefinedInResolve: false,
resolverValidationOptions: {
requireResolversForArgs: true,
requireResolversForNonScalar: true,
requireResolversForAllFields: false
}
})
/* GraphQL query */
let query = `
mutation AddCoCWT {
m1: Person {
create(
id: "acf34c80-9f83-11e6-8d46-080027e303e4",
with: {
initials: "JHO",
name: "Jochen Hörtreiter",
supervisor: "${pRSE.id}"
}
) {
id initials name
}
}
m2: OrgUnit {
create(
id: "acf34c80-9f83-11e6-8d47-080027e303e4",
with: {
initials: "CoC-WT",
name: "CoC Web Technologies",
parentUnit: "${uXT.id}",
director: "acf34c80-9f83-11e6-8d46-080027e303e4"
}
) {
id initials name
}
}
q1: OrgUnits(where: {
initials: "CoC-WT"
}) {
id
name
director { id name }
parentUnit { id name }
members { id name }
}
u1: Person(id: "acf34c80-9f83-11e6-8d46-080027e303e4") {
update(with: { initials: "XXX", role: "assistant" }) {
id initials name role
}
}
c1: Person(id: "acf34c80-9f83-11e6-8d46-080027e303e4") {
clone {
id initials name
}
}
d1: Person(id: "acf34c80-9f83-11e6-8d46-080027e303e4") {
delete
}
}
`
/* setup network service */
let server = new HAPI.Server({
address: "0.0.0.0",
port: 12345
})
/* establish the HAPI route for GraphiQL UI */
await server.register({
plugin: HAPIGraphiQL,
options: {
graphiqlURL: "/api",
graphqlFetchURL: "/api",
graphqlFetchOpts: `{
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
},
body: JSON.stringify(params),
credentials: "same-origin"
}`,
graphqlExample: query.replace(/^\n/, "").replace(/^ /mg, "")
}
})
/* establish the HAPI route for GraphQL API */
server.route({
method: "POST",
path: "/api",
config: {
payload: { output: "data", parse: true, allow: "application/json" }
},
handler: async (request, h) => {
/* determine request */
if (typeof request.payload !== "object" || request.payload === null)
return Boom.badRequest("invalid request")
let query = request.payload.query
let variables = request.payload.variables
let operation = request.payload.operationName
/* support special case of GraphiQL */
if (typeof variables === "string")
variables = JSON.parse(variables)
if (typeof operation === "object" && operation !== null)
return Boom.badRequest("invalid request")
/* wrap GraphQL operation into a database transaction */
return db.transaction({
autocommit: false,
deferrable: true,
type: Sequelize.Transaction.TYPES.DEFERRED,
isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.SERIALIZABLE
}, (tx) => {
/* create context for GraphQL resolver functions */
let ctx = { tx }
/* execute the GraphQL query against the GraphQL schema */
return GraphQL.graphql(schema, query, null, ctx, variables, operation)
}).then((result) => {
/* success/commit */
return h.response(result).code(200)
}).catch((result) => {
/* error/rollback */
if (typeof result === "object" && result instanceof Error)
result = `${result.name}: ${result.message}`
else if (typeof result !== "string")
result = result.toString()
result = { errors: [ { message: result } ] }
return h.response(result).code(200)
})
}
})
/* start server */
await server.start()
console.log(`GraphiQL UI: [GET] http://${server.info.host}:${server.info.port}/api`)
console.log(`GraphQL API: [POST] http://${server.info.host}:${server.info.port}/api`)
})().catch((ex) => {
console.log(`ERROR: ${ex}`)
})