-
Notifications
You must be signed in to change notification settings - Fork 191
/
module.ts
205 lines (167 loc) · 6.22 KB
/
module.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
import { existsSync } from 'fs'
import jiti from 'jiti'
import { Ref } from 'vue'
import { defu } from 'defu'
import { useLogger, addPlugin, addImports, addTemplate, createResolver, defineNuxtModule } from '@nuxt/kit'
import GraphQLPlugin from '@rollup/plugin-graphql'
import { name, version } from '../package.json'
import type { ClientConfig, NuxtApolloConfig, ErrorResponse } from './types'
export type { ClientConfig, ErrorResponse }
const logger = useLogger(name)
async function readConfigFile (path: string): Promise<ClientConfig> {
return await jiti(import.meta.url, { esmResolve: true, interopDefault: true, requireCache: false })(path)
}
export type ModuleOptions = NuxtApolloConfig
export default defineNuxtModule<NuxtApolloConfig<any>>({
meta: {
name,
version,
configKey: 'apollo',
compatibility: {
nuxt: '^3.0.0-rc.9'
}
},
defaults: {
autoImports: true,
authType: 'Bearer',
authHeader: 'Authorization',
tokenStorage: 'cookie',
proxyCookies: true,
cookieAttributes: {
maxAge: 60 * 60 * 24 * 7,
secure: process.env.NODE_ENV === 'production'
},
clientAwareness: false
},
async setup (options, nuxt) {
if (!options.clients || !Object.keys(options.clients).length) {
throw new Error('[@nuxtjs/apollo] Atleast one client must be configured.')
}
const { resolve } = createResolver(import.meta.url)
const rootResolver = createResolver(nuxt.options.rootDir)
nuxt.options.build.transpile = nuxt.options.build.transpile || []
nuxt.options.build.transpile.push(
resolve('runtime'),
'@wry/context',
'@apollo/client',
'@vue/apollo-composable',
'ts-invariant/process')
const clients: Record<string, ClientConfig> = {}
const configPaths: Record<string, string> = {}
async function prepareClients () {
// eslint-disable-next-line prefer-const
for (let [k, v] of Object.entries(options.clients || {})) {
if (typeof v === 'string') {
const path = rootResolver.resolve(v)
const resolvedConfig = existsSync(path) && await readConfigFile(path)
if (!resolvedConfig) {
logger.warn(`Unable to resolve Apollo config for client: ${k}`)
continue
}
v = resolvedConfig
if (!configPaths[k]) { configPaths[k] = path }
}
v.authType = v?.authType || (v?.authType === '' || v?.authType === null) ? null : options.authType
v.authHeader = v?.authHeader || options.authHeader
v.tokenName = v?.tokenName || `apollo:${k}.token`
v.tokenStorage = v?.tokenStorage || options.tokenStorage
if (v.cookieAttributes) { v.cookieAttributes = defu(v?.cookieAttributes, options.cookieAttributes) }
v.defaultOptions = v?.defaultOptions || options.defaultOptions
if (!v?.httpEndpoint && !v?.wsEndpoint) {
logger.error(`Either \`httpEndpoint\` or \`wsEndpoint\` must be provided for client: \`${k}\``)
}
clients[k] = v
}
}
addTemplate({
filename: 'apollo.d.ts',
getContents: () => [
'import type { ClientConfig } from "@nuxtjs/apollo"',
'declare const clients: Record<string, ClientConfig>',
'declare const clientAwareness: boolean',
'declare const proxyCookies: boolean',
'declare const cookieAttributes: ClientConfig[\'cookieAttributes\']',
'export default { clients, clientAwareness, proxyCookies, cookieAttributes }'
].join('\n')
})
nuxt.options.alias['#apollo'] = addTemplate({
filename: 'apollo.mjs',
getContents: () => [
'export default {',
` proxyCookies: ${options.proxyCookies},`,
` clientAwareness: ${options.clientAwareness},`,
` cookieAttributes: ${JSON.stringify(options.cookieAttributes)},`,
` clients: ${JSON.stringify(clients)}`,
'}'
].join('\n')
}).dst
addPlugin(resolve('runtime/plugin'))
// TODO: Integrate @vue/apollo-components?
addImports([
{ name: 'gql', from: 'graphql-tag' },
...[
'useApollo',
'useAsyncQuery',
'useLazyAsyncQuery'
].map(n => ({ name: n, from: resolve('runtime/composables') })),
...(!options?.autoImports
? []
: [
'useQuery',
'useLazyQuery',
'useMutation',
'useSubscription',
'useApolloClient',
'useQueryLoading',
'useMutationLoading',
'useSubscriptionLoading',
'useGlobalQueryLoading',
'useGlobalMutationLoading',
'useGlobalSubscriptionLoading'
].map(n => ({ name: n, from: '@vue/apollo-composable' })))
])
nuxt.hook('vite:extendConfig', (config) => {
config.optimizeDeps = config.optimizeDeps || {}
config.optimizeDeps.exclude = config.optimizeDeps.exclude || []
config.optimizeDeps.exclude.push('@vue/apollo-composable')
config.plugins = config.plugins || []
config.plugins.push(GraphQLPlugin())
if (!nuxt.options.dev) { config.define = { ...config.define, __DEV__: false } }
})
nuxt.hook('webpack:config', (configs) => {
for (const config of configs) {
// @ts-ignore
const hasGqlLoader = config.module.rules.some((rule: any) => rule?.use === 'graphql-tag/loader')
if (hasGqlLoader) { return }
// @ts-ignore
config.module.rules.push({
test: /\.(graphql|gql)$/,
use: 'graphql-tag/loader',
exclude: /(node_modules)/
})
}
})
nuxt.hook('builder:watch', async (_event, path) => {
if (!Object.values(configPaths).some(p => p.includes(path))) { return }
logger.log('[@nuxtjs/apollo] Reloading Apollo configuration')
await prepareClients()
await nuxt.callHook('builder:generateApp')
})
await prepareClients()
}
})
export const defineApolloClient = (config: ClientConfig) => config
declare module '#app' {
interface RuntimeConfig {
// @ts-ignore
apollo: NuxtApolloConfig<any>
// @ts-ignore
public:{
apollo: NuxtApolloConfig<any>
}
}
interface RuntimeNuxtHooks {
'apollo:auth': (params: { client: string, token: Ref<string | null> }) => void
'apollo:error': (error: ErrorResponse) => void
}
}