Nuxt/packages/nitro/src/presets/azure.ts

106 lines
2.5 KiB
TypeScript
Raw Normal View History

2020-11-28 11:50:55 +00:00
import consola from 'consola'
import fse from 'fs-extra'
import globby from 'globby'
2020-11-28 22:49:39 +00:00
import { join, resolve } from 'upath'
import { writeFile } from '../utils'
2021-01-22 19:55:59 +00:00
import { NitroPreset, NitroContext } from '../context'
2020-11-28 11:50:55 +00:00
2021-01-22 19:55:59 +00:00
export const azure: NitroPreset = {
2020-11-28 11:50:55 +00:00
entry: '{{ _internal.runtimeDir }}/entries/azure',
output: {
serverDir: '{{ output.dir }}/server/functions'
},
2020-11-28 11:50:55 +00:00
hooks: {
2021-01-22 19:55:59 +00:00
async 'nitro:compiled' (ctx: NitroContext) {
2020-11-28 11:50:55 +00:00
await writeRoutes(ctx)
}
}
}
async function writeRoutes ({ output: { serverDir, publicDir } }: NitroContext) {
const host = {
version: '2.0'
}
2020-11-28 11:50:55 +00:00
const routes = [
{
route: '/*',
serve: '/api/server'
}
]
2020-11-28 11:50:55 +00:00
const indexPath = resolve(publicDir, 'index.html')
const indexFileExists = fse.existsSync(indexPath)
if (!indexFileExists) {
routes.unshift(
{
route: '/',
serve: '/api/server'
},
{
route: '/index.html',
serve: '/api/server'
}
)
2020-11-28 11:50:55 +00:00
}
const folderFiles = await globby([
join(publicDir, 'index.html'),
join(publicDir, '**/index.html')
])
const prefix = publicDir.length
const suffix = '/index.html'.length
folderFiles.forEach(file =>
routes.unshift({
route: file.slice(prefix, -suffix) || '/',
serve: file.slice(prefix)
})
)
const otherFiles = await globby([join(publicDir, '**/*.html'), join(publicDir, '*.html')])
otherFiles.forEach((file) => {
if (file.endsWith('index.html')) {
return
}
const route = file.slice(prefix, -5)
const existingRouteIndex = routes.findIndex(_route => _route.route === route)
if (existingRouteIndex > -1) {
routes.splice(existingRouteIndex, 1)
}
routes.unshift(
{
route,
serve: file.slice(prefix)
}
)
})
2020-11-28 11:50:55 +00:00
const functionDefinition = {
entryPoint: 'handle',
bindings: [
{
authLevel: 'anonymous',
type: 'httpTrigger',
direction: 'in',
name: 'req',
route: '{*url}',
methods: ['delete', 'get', 'head', 'options', 'patch', 'post', 'put']
2020-11-28 11:50:55 +00:00
},
{
type: 'http',
direction: 'out',
name: 'res'
}
]
}
await writeFile(resolve(serverDir, 'function.json'), JSON.stringify(functionDefinition))
await writeFile(resolve(serverDir, '../host.json'), JSON.stringify(host))
await writeFile(resolve(publicDir, 'routes.json'), JSON.stringify({ routes }))
if (!indexFileExists) {
await writeFile(indexPath, '')
}
2020-11-28 11:50:55 +00:00
consola.success('Ready to deploy.')
2020-11-28 11:50:55 +00:00
}