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

108 lines
2.8 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'
import { join, resolve } from 'pathe'
import { hl, prettyPath, 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 }: NitroContext) {
const host = {
version: '2.0'
}
2020-11-28 11:50:55 +00:00
const config = {
routes: [],
navigationFallback: {
rewrite: '/api/server'
}
}
2020-11-28 11:50:55 +00:00
const indexPath = resolve(output.publicDir, 'index.html')
const indexFileExists = fse.existsSync(indexPath)
if (!indexFileExists) {
config.routes.unshift(
{
route: '/index.html',
redirect: '/'
},
{
route: '/',
rewrite: '/api/server'
}
)
2020-11-28 11:50:55 +00:00
}
const folderFiles = await globby([
join(output.publicDir, 'index.html'),
join(output.publicDir, '**/index.html')
])
const prefix = output.publicDir.length
const suffix = '/index.html'.length
folderFiles.forEach(file =>
config.routes.unshift({
route: file.slice(prefix, -suffix) || '/',
rewrite: file.slice(prefix)
})
)
const otherFiles = await globby([join(output.publicDir, '**/*.html'), join(output.publicDir, '*.html')])
otherFiles.forEach((file) => {
if (file.endsWith('index.html')) {
return
}
const route = file.slice(prefix, '.html'.length)
const existingRouteIndex = config.routes.findIndex(_route => _route.route === route)
if (existingRouteIndex > -1) {
config.routes.splice(existingRouteIndex, 1)
}
config.routes.unshift(
{
route,
rewrite: 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(output.serverDir, 'function.json'), JSON.stringify(functionDefinition))
await writeFile(resolve(output.serverDir, '../host.json'), JSON.stringify(host))
await writeFile(resolve(output.publicDir, 'staticwebapp.config.json'), JSON.stringify(config))
if (!indexFileExists) {
await writeFile(indexPath, '')
}
2020-11-28 11:50:55 +00:00
const apiDir = resolve(output.serverDir, '..')
consola.success('Ready to run', hl('npx @azure/static-web-apps-cli start ' + prettyPath(output.publicDir) + ' --api-location ' + prettyPath(apiDir)), 'for local testing')
2020-11-28 11:50:55 +00:00
}