forked from vuejs/vue-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraphql-server.js
220 lines (192 loc) · 5.92 KB
/
graphql-server.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
// modified from vue-cli-plugin-apollo/graphql-server
// added a return value for the server() call
const http = require('http')
const { chalk } = require('@vue/cli-shared-utils')
const express = require('express')
const { ApolloServer, gql } = require('apollo-server-express')
const { PubSub } = require('graphql-subscriptions')
const merge = require('deepmerge')
function defaultValue (provided, value) {
return provided == null ? value : provided
}
function autoCall (fn, ...context) {
if (typeof fn === 'function') {
return fn(...context)
}
return fn
}
module.exports = async (options, cb = null) => {
// Default options
options = merge({
integratedEngine: false
}, options)
// Express app
const app = express()
// Customize those files
let typeDefs = load(options.paths.typeDefs)
const resolvers = load(options.paths.resolvers)
const context = load(options.paths.context)
const schemaDirectives = load(options.paths.directives)
let pubsub
try {
pubsub = load(options.paths.pubsub)
} catch (e) {
if (process.env.NODE_ENV !== 'production' && !options.quiet) {
console.log(chalk.yellow('Using default PubSub implementation for subscriptions.'))
console.log(chalk.grey('You should provide a different implementation in production (for example with Redis) by exporting it in \'apollo-server/pubsub.js\'.'))
}
}
let dataSources
try {
dataSources = load(options.paths.dataSources)
} catch (e) {}
// GraphQL API Server
// Realtime subscriptions
if (!pubsub) pubsub = new PubSub()
// Customize server
try {
const serverModule = load(options.paths.server)
serverModule(app)
} catch (e) {
// No file found
}
// Apollo server options
typeDefs = processSchema(typeDefs)
let apolloServerOptions = {
typeDefs,
resolvers,
schemaDirectives,
dataSources,
tracing: true,
cacheControl: true,
engine: !options.integratedEngine,
// Resolvers context from POST
context: async ({ req, connection }) => {
let contextData
try {
if (connection) {
contextData = await autoCall(context, { connection })
} else {
contextData = await autoCall(context, { req })
}
} catch (e) {
console.error(e)
throw e
}
contextData = Object.assign({}, contextData, { pubsub })
return contextData
},
// Resolvers context from WebSocket
subscriptions: {
path: options.subscriptionsPath,
onConnect: async (connection, websocket) => {
let contextData = {}
try {
contextData = await autoCall(context, {
connection,
websocket
})
contextData = Object.assign({}, contextData, { pubsub })
} catch (e) {
console.error(e)
throw e
}
return contextData
}
}
}
// Automatic mocking
if (options.enableMocks) {
// Customize this file
apolloServerOptions.mocks = load(options.paths.mocks)
apolloServerOptions.mockEntireSchema = false
if (!options.quiet) {
if (process.env.NODE_ENV === 'production') {
console.warn('Automatic mocking is enabled, consider disabling it with the \'enableMocks\' option.')
} else {
console.log('✔️ Automatic mocking is enabled')
}
}
}
// Apollo Engine
if (options.enableEngine && options.integratedEngine) {
if (options.engineKey) {
apolloServerOptions.engine = {
apiKey: options.engineKey,
schemaTag: options.schemaTag,
...options.engineOptions || {}
}
console.log('✔️ Apollo Engine is enabled')
} else if (!options.quiet) {
console.log(chalk.yellow('Apollo Engine key not found.') + `To enable Engine, set the ${chalk.cyan('VUE_APP_APOLLO_ENGINE_KEY')} env variable.`)
console.log('Create a key at https://engine.apollographql.com/')
console.log('You may see `Error: Must provide document` errors (query persisting tries).')
}
} else {
apolloServerOptions.engine = false
}
// Final options
apolloServerOptions = merge(apolloServerOptions, defaultValue(options.serverOptions, {}))
// Apollo Server
const server = new ApolloServer(apolloServerOptions)
await server.start()
// Express middleware
server.applyMiddleware({
app,
path: options.graphqlPath,
cors: options.cors
// gui: {
// endpoint: graphqlPath,
// subscriptionEndpoint: graphqlSubscriptionsPath,
// },
})
// Start server
const httpServer = http.createServer(app)
httpServer.setTimeout(options.timeout)
server.installSubscriptionHandlers(httpServer)
httpServer.listen({
host: options.host || 'localhost',
port: options.port
}, () => {
if (!options.quiet) {
console.log(`✔️ GraphQL Server is running on ${chalk.cyan(`http://localhost:${options.port}${options.graphqlPath}`)}`)
if (process.env.NODE_ENV !== 'production' && !process.env.VUE_CLI_API_MODE) {
console.log(`✔️ Type ${chalk.cyan('rs')} to restart the server`)
}
}
cb && cb()
})
// added in order to let vue cli to deal with the http upgrade request
return {
apolloServer: server,
httpServer
}
}
function load (file) {
const module = require(file)
if (module.default) {
return module.default
}
return module
}
function processSchema (typeDefs) {
if (Array.isArray(typeDefs)) {
return typeDefs.map(processSchema)
}
if (typeof typeDefs === 'string') {
// Convert schema to AST
typeDefs = gql(typeDefs)
}
// Remove upload scalar (it's already included in Apollo Server)
removeFromSchema(typeDefs, 'ScalarTypeDefinition', 'Upload')
return typeDefs
}
function removeFromSchema (document, kind, name) {
const definitions = document.definitions
const index = definitions.findIndex(
def => def.kind === kind && def.name.kind === 'Name' && def.name.value === name
)
if (index !== -1) {
definitions.splice(index, 1)
}
}