-
Notifications
You must be signed in to change notification settings - Fork 1
/
module.ts
258 lines (223 loc) · 6.84 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
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
import { defu } from 'defu';
import { dirname, join, relative } from 'path';
import { getObjProp, objectEntries, objectPick, setObjProp } from '@whoj/utils-core';
import { addImports, addPlugin, addTypeTemplate, createResolver, defineNuxtModule, resolvePath, useLogger } from '@nuxt/kit';
import { name, version } from '../package.json';
import type { NuxtAxiosInstance, NuxtAxiosOptions } from './options';
const CONFIG_KEY = 'axios' as const;
export default defineNuxtModule<NuxtAxiosOptions>({
meta: {
name,
version,
configKey: CONFIG_KEY,
compatibility: {
bridge: false,
nuxt: '^3.7.0'
}
},
defaults: ({ options }) => ({
alias: 'axios',
autoImport: {
enabled: false,
imports: {
useAxios: 'useAxios',
useAxiosGet: 'useAxiosGet',
useAxiosPost: 'useAxiosPost',
useAxiosPut: 'useAxiosPut',
useAxiosPatch: 'useAxiosPatch',
useAxiosDelete: 'useAxiosDelete'
},
priority: 1
},
credentials: false,
headers: {
common: {
'crossDomain': 'true',
'Accept': 'application/json, text/plain, */*',
'Access-Control-Allow-Origin': '*',
'X-Requested-With': 'XMLHttpRequest'
}
},
proxy: false,
debug: false,
progress: true,
proxyHeaders: true,
// @ts-ignore
globalName: options.globalName || 'nuxt',
proxyHeadersIgnore: [
'accept',
'cf-connecting-ip',
'cf-ray',
'content-length',
'content-md5',
'content-type',
'host',
'if-modified-since',
'if-none-match',
'x-forwarded-host',
'x-forwarded-port',
'x-forwarded-proto'
]
}),
async setup(_options, nuxt) {
const logger = useLogger('nuxt:axios');
// Combined options
const moduleOptions = defu(
_options,
getObjProp(nuxt.options.runtimeConfig, CONFIG_KEY, {}),
getObjProp(nuxt.options.runtimeConfig.public, CONFIG_KEY, {})
);
// Default port
const defaultPort
= process.env.API_PORT
|| moduleOptions.port
|| process.env.NITRO_PORT
|| process.env.PORT
// @ts-ignore
|| (nuxt.options.server && nuxt.options.server.port)
|| 3000;
// Default host
let defaultHost
= process.env.API_HOST
|| moduleOptions.host
|| process.env.HOST
|| process.env.NITRO_HOST
// @ts-ignore
|| (nuxt.options.server && nuxt.options.server.host)
|| 'localhost';
/* istanbul ignore if */
if (defaultHost === '0.0.0.0') {
defaultHost = 'localhost';
}
// Default prefix
const prefix = process.env.API_PREFIX || moduleOptions.prefix || '/';
// @ts-ignore // HTTPS
const https = Boolean(nuxt.options.server && nuxt.options.server.https);
// Headers
const headers = {
common: {
accept: 'application/json, text/plain, */*'
},
delete: {},
get: {},
head: {},
post: {},
put: {},
patch: {}
};
// Support baseUrl alternative
if (moduleOptions.baseUrl) {
moduleOptions.baseURL = moduleOptions.baseUrl;
delete moduleOptions.baseUrl;
}
if (moduleOptions.browserBaseUrl) {
moduleOptions.browserBaseURL = moduleOptions.browserBaseUrl;
delete moduleOptions.browserBaseUrl;
}
// Apply defaults
const options = defu(moduleOptions, {
baseURL: `http://${defaultHost}:${defaultPort}${prefix}`,
https,
headers
});
/* istanbul ignore if */
const API_URL = process.env.API_URL || process.env.NUXT_AXIOS_BASE_URL;
if (API_URL) {
options.baseURL = process.env.API_URL!;
}
/* istanbul ignore if */
const API_URL_BROWSER = process.env.API_URL_BROWSER || process.env.NUXT_PUBLIC_AXIOS_BROWSER_BASE_URL;
if (API_URL_BROWSER) {
options.browserBaseURL = API_URL_BROWSER;
}
// Default browserBaseURL
if (typeof options.browserBaseURL === 'undefined') {
options.browserBaseURL = options.proxy ? prefix : options.baseURL;
}
// Normalize options
if (options.retry) {
options.retry = {};
}
// Convert http:// to https:// if https option is on
if (options.https) {
const https = (s: string) => s.replace('http://', 'https://');
if (options.baseURL) {
options.baseURL = https(options.baseURL);
}
if (options.browserBaseURL) {
options.browserBaseURL = https(options.browserBaseURL);
}
}
setObjProp(nuxt.options.runtimeConfig, CONFIG_KEY, objectPick(options, ['agents', 'baseUrl', 'baseURL']));
setObjProp(nuxt.options.runtimeConfig.public, CONFIG_KEY, { ...options, baseUrl: undefined, baseURL: undefined, agents: undefined });
// @ts-ignore
const { resolve } = createResolver(import.meta.url);
nuxt.options.build.transpile.push(resolve('./runtime'));
// Register plugin
addPlugin({
order: -1,
mode: 'all',
src: resolve('./runtime/plugin')
});
// imports / composables
if (options.autoImport?.enabled) {
addImports(objectEntries<Record<string, string>>(options.autoImport.imports || {}).map(([name, as]) => ({
name,
as,
priority: options.autoImport?.priority,
from: resolve('./runtime/composables/axios')
})));
}
// Set NUXT_AXIOS_BASE_URL for dynamic SSR baseURL
process.env.NUXT_AXIOS_BASE_URL = process.env._AXIOS_BASE_URL_ = options.baseURL;
logger.debug(`baseURL: ${options.baseURL}`);
logger.debug(`browserBaseURL: ${options.browserBaseURL}`);
let nuxtPath = dirname(await resolvePath('nuxt'));
nuxtPath = relative(join(nuxt.options.buildDir, 'types'), join(nuxtPath, 'dist'));
addTypeTemplate({
filename: 'types/nuxt3-axios.d.ts',
getContents: () => `// Generated by @whoj/nuxt3-axios
import type { AxiosStatic } from 'axios';
import type { NuxtAxiosInstance, NuxtAxiosOptions } from '@whoj/nuxt3-axios';
declare module 'axios' {
export interface AxiosInstance {
CancelToken: AxiosStatic['CancelToken'];
isAxiosError: AxiosStatic['isAxiosError'];
isCancel: AxiosStatic['isCancel'];
}
export interface AxiosRequestConfig {
progress?: boolean;
}
}
declare module 'nuxt/schema' {
interface NuxtConfig {
axios?: NuxtAxiosOptions
}
interface RuntimeConfig {
axios: Pick<NuxtAxiosOptions, 'agents' | 'baseUrl' | 'baseURL'>;
}
interface PublicRuntimeConfig {
axios: Omit<NuxtAxiosOptions, 'agents' | 'autoImport' | 'baseUrl' | 'baseURL'>
}
}
declare module '${join(dirname(nuxtPath), 'app/nuxt')}' {
interface NuxtApp {
$${options.alias}: NuxtAxiosInstance;
}
}
declare module 'vue' {
interface ComponentCustomProperties {
$${options.alias}: NuxtAxiosInstance;
}
}
declare module '@vue/runtime-core' {
interface ComponentCustomProperties {
$${options.alias}: NuxtAxiosInstance;
}
}
export {};
`
});
}
});
export type { NuxtAxiosOptions, NuxtAxiosInstance };