feat: handle runtimeConfig and static target

master
Sébastien Chopin 2020-07-14 12:32:28 +02:00
parent f2a0dcd566
commit b9f5e053d3
3 changed files with 100 additions and 22 deletions

View File

@ -4,8 +4,10 @@ const consola = require('consola')
const logger = consola.withScope('nuxt:http')
function httpModule (_moduleOptions) {
const { nuxt, addPlugin, requireModule } = this
// Combine options
const moduleOptions = { ...this.options.http, ..._moduleOptions }
const moduleOptions = { ...nuxt.options.http, ..._moduleOptions }
// Default port
const defaultPort =
@ -13,7 +15,7 @@ function httpModule (_moduleOptions) {
moduleOptions.port ||
process.env.PORT ||
process.env.npm_package_config_nuxt_port ||
(this.options.server && this.options.server.port) ||
(nuxt.options.server && nuxt.options.server.port) ||
3000
// Default host
@ -22,7 +24,7 @@ function httpModule (_moduleOptions) {
moduleOptions.host ||
process.env.HOST ||
process.env.npm_package_config_nuxt_host ||
(this.options.server && this.options.server.host) ||
(nuxt.options.server && nuxt.options.server.host) ||
'localhost'
/* istanbul ignore if */
@ -41,11 +43,11 @@ function httpModule (_moduleOptions) {
const prefix = process.env.API_PREFIX || moduleOptions.prefix || '/'
// HTTPS
const https = Boolean(this.options.server && this.options.server.https)
const https = Boolean(nuxt.options.server && nuxt.options.server.https)
// Apply defaults
const options = {
baseURL: `http://${defaultHost}:${defaultPort}${prefix}`,
baseURL: undefined,
browserBaseURL: undefined,
debug: false,
proxyHeaders: true,
@ -58,9 +60,9 @@ function httpModule (_moduleOptions) {
headers: {},
...moduleOptions
}
const toHttps = s => options.https ? s.replace('http://', 'https://') : s
// ENV overrides
/* istanbul ignore if */
if (process.env.API_URL) {
options.baseURL = process.env.API_URL
@ -71,9 +73,24 @@ function httpModule (_moduleOptions) {
options.browserBaseURL = process.env.API_URL_BROWSER
}
// Default browserBaseURL
if (typeof options.browserBaseURL === 'undefined') {
options.browserBaseURL = options.proxy ? prefix : options.baseURL
// If no baseURL defined, get it from Nuxt server
if (!options.baseURL) {
options.baseURL = `http://${defaultHost}:${defaultPort}${prefix}`
// Update auto generated baseURL after listen for static target as we use random port
const publicRuntimeConfig = nuxt.options.publicRuntimeConfig = nuxt.options.publicRuntimeConfig || {}
publicRuntimeConfig.http = publicRuntimeConfig.http || {}
const privateRuntimeConfig = nuxt.options.privateRuntimeConfig = nuxt.options.privateRuntimeConfig || {}
privateRuntimeConfig.http = privateRuntimeConfig.http || {}
// For static exporting
if (nuxt.options.target === 'static') {
nuxt.hook('listen', (_, { host, port }) => {
publicRuntimeConfig.http.browserBaseURL = toHttps(publicRuntimeConfig.http.browserBaseURL || prefix || '/')
privateRuntimeConfig.http.baseURL = toHttps(privateRuntimeConfig.http.baseURL || `http://${host}:${port}${prefix}`)
})
}
}
// Normalize options
@ -87,6 +104,11 @@ function httpModule (_moduleOptions) {
options.retry = JSON.stringify(options.retry)
}
// Default browserBaseURL
if (typeof options.browserBaseURL === 'undefined') {
options.browserBaseURL = options.proxy ? prefix : options.baseURL
}
// Remove port 443 when https
if (options.baseURL.includes('https://')) {
options.baseURL = options.baseURL.replace(':443', '')
@ -98,14 +120,11 @@ function httpModule (_moduleOptions) {
}
// Convert http:// to https:// if https option is on
if (options.https === true) {
const https = s => s.replace('http://', 'https://')
options.baseURL = https(options.baseURL)
options.browserBaseURL = https(options.browserBaseURL)
}
options.baseURL = toHttps(options.baseURL)
options.browserBaseURL = toHttps(options.browserBaseURL)
// Register plugin
this.addPlugin({
addPlugin({
src: path.resolve(__dirname, 'plugin.js'),
fileName: 'http.js',
options
@ -113,19 +132,19 @@ function httpModule (_moduleOptions) {
// Proxy integration
if (options.proxy) {
this.requireModule([
requireModule([
'@nuxtjs/proxy',
typeof options.proxy === 'object' ? options.proxy : {}
])
}
// Alias ky-universal
this.options.alias['ky-universal'] = path.resolve(__dirname, '../ky-universal')
nuxt.options.alias['ky-universal'] = path.resolve(__dirname, '../ky-universal')
// Transpile ky and ky-universal
this.options.build.transpile = this.options.build.transpile || {}
this.options.build.transpile.push('ky')
this.options.build.transpile.push('@nuxt/http')
nuxt.options.build.transpile = nuxt.options.build.transpile || {}
nuxt.options.build.transpile.push('ky')
nuxt.options.build.transpile.push('@nuxt/http')
// Set _HTTP_BASE_URL_ for dynamic SSR baseURL
process.env._HTTP_BASE_URL_ = options.baseURL
@ -136,3 +155,7 @@ function httpModule (_moduleOptions) {
module.exports = httpModule
module.exports.meta = require('../package.json')
module.exports = httpModule
module.exports.meta = require('../package.json')
module.exports = httpModule
module.exports.meta = require('../package.json')

View File

@ -182,10 +182,13 @@ const setupDebugInterceptor = http => {
}<% } %>
export default (ctx, inject) => {
// runtimeConfig
const runtimeConfig = ctx.$config && ctx.$config.http || {}
// prefixUrl
const prefixUrl = process.browser
? '<%= options.browserBaseURL %>'
: (process.env._HTTP_BASE_URL_ || '<%= options.baseURL %>')
? (runtimeConfig.browserBaseURL || '<%= options.browserBaseURL || '' %>')
: (runtimeConfig.baseURL || process.env._HTTP_BASE_URL_ || '<%= options.baseURL || '' %>')
const headers = <%= JSON.stringify(options.headers, null, 2) %>

View File

@ -91,4 +91,56 @@ describe('with-config', () => {
expect(nuxt.moduleContainer.requireModule).toBeDefined()
expect(nuxt.moduleContainer.requireModule.mock.calls[0][0]).toStrictEqual(['@nuxtjs/proxy', { hello: true }])
})
test('should handle `baseUrl` key', async () => {
const nuxt = await setupMockNuxt({
http: {
baseUrl: 'http://localhost:5000'
}
})
expect(nuxt.moduleContainer.addTemplate).toBeDefined()
const call = nuxt.moduleContainer.addTemplate.mock.calls.find(args => args[0].src.includes('plugin.js'))
const options = call[0].options
expect(options.baseURL).toBe('http://localhost:5000')
})
test('should remove `:80` port if http', async () => {
const nuxt = await setupMockNuxt({
http: {
baseUrl: 'http://localhost:80'
}
})
expect(nuxt.moduleContainer.addTemplate).toBeDefined()
const call = nuxt.moduleContainer.addTemplate.mock.calls.find(args => args[0].src.includes('plugin.js'))
const options = call[0].options
expect(options.baseURL).toBe('http://localhost')
})
test('should remove `:443` port if https', async () => {
const nuxt = await setupMockNuxt({
http: {
baseUrl: 'https://localhost:443'
}
})
expect(nuxt.moduleContainer.addTemplate).toBeDefined()
const call = nuxt.moduleContainer.addTemplate.mock.calls.find(args => args[0].src.includes('plugin.js'))
const options = call[0].options
expect(options.baseURL).toBe('https://localhost')
})
test('should handle static target', async () => {
const nuxt = await setupMockNuxt({
target: 'static'
})
expect(nuxt.moduleContainer.addTemplate).toBeDefined()
const call = nuxt.moduleContainer.addTemplate.mock.calls.find(args => args[0].src.includes('plugin.js'))
const options = call[0].options
expect(nuxt.options.privateRuntimeConfig.http).toBeDefined()
expect(nuxt.options.publicRuntimeConfig.http).toBeDefined()
await nuxt.callHook('listen', null, { port: 1234, host: 'hello' })
expect(nuxt.options.privateRuntimeConfig.http.baseURL).toBe('http://hello:1234/test_api')
expect(nuxt.options.publicRuntimeConfig.http.browserBaseURL).toBe('/test_api')
expect(options.baseURL).toBe('http://localhost:3000/test_api')
expect(options.browserBaseURL).toBe('/test_api')
})
})