2023-04-07 16:02:47 +00:00
|
|
|
import type { Nitro, NitroDevEventHandler, NitroEventHandler } from 'nitropack'
|
2022-11-03 14:04:02 +00:00
|
|
|
import { normalize } from 'pathe'
|
2021-11-21 16:14:46 +00:00
|
|
|
import { useNuxt } from './context'
|
|
|
|
|
2022-06-15 11:53:31 +00:00
|
|
|
/**
|
|
|
|
* normalize handler object
|
|
|
|
*
|
|
|
|
*/
|
|
|
|
function normalizeHandlerMethod (handler: NitroEventHandler) {
|
|
|
|
// retrieve method from handler file name
|
|
|
|
const [, method = undefined] = handler.handler.match(/\.(get|head|patch|post|put|delete|connect|options|trace)(\.\w+)*$/) || []
|
|
|
|
return {
|
|
|
|
method,
|
2022-11-03 14:04:02 +00:00
|
|
|
...handler,
|
|
|
|
handler: normalize(handler.handler)
|
2022-06-15 11:53:31 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-05-06 13:31:52 +00:00
|
|
|
/**
|
|
|
|
* Adds a nitro server handler
|
|
|
|
*
|
|
|
|
*/
|
|
|
|
export function addServerHandler (handler: NitroEventHandler) {
|
2022-06-15 11:53:31 +00:00
|
|
|
useNuxt().options.serverHandlers.push(normalizeHandlerMethod(handler))
|
2022-05-06 13:31:52 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Adds a nitro server handler for development-only
|
|
|
|
*
|
|
|
|
*/
|
|
|
|
export function addDevServerHandler (handler: NitroDevEventHandler) {
|
|
|
|
useNuxt().options.devServerHandlers.push(handler)
|
|
|
|
}
|
2022-09-15 16:10:50 +00:00
|
|
|
|
2022-11-03 14:54:05 +00:00
|
|
|
/**
|
|
|
|
* Adds a Nitro plugin
|
|
|
|
*/
|
|
|
|
export function addServerPlugin (plugin: string) {
|
|
|
|
const nuxt = useNuxt()
|
|
|
|
nuxt.options.nitro.plugins = nuxt.options.nitro.plugins || []
|
|
|
|
nuxt.options.nitro.plugins.push(normalize(plugin))
|
|
|
|
}
|
|
|
|
|
2022-11-03 21:03:12 +00:00
|
|
|
/**
|
|
|
|
* Adds routes to be prerendered
|
|
|
|
*/
|
|
|
|
export function addPrerenderRoutes (routes: string | string[]) {
|
|
|
|
const nuxt = useNuxt()
|
|
|
|
if (!Array.isArray(routes)) {
|
|
|
|
routes = [routes]
|
|
|
|
}
|
|
|
|
routes = routes.filter(Boolean)
|
|
|
|
if (!routes.length) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
nuxt.hook('prerender:routes', (ctx) => {
|
|
|
|
for (const route of routes) {
|
|
|
|
ctx.routes.add(route)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2022-09-15 16:10:50 +00:00
|
|
|
/**
|
|
|
|
* Access to the Nitro instance
|
|
|
|
*
|
|
|
|
* **Note:** You can call `useNitro()` only after `ready` hook.
|
|
|
|
*
|
|
|
|
* **Note:** Changes to the Nitro instance configuration are not applied.
|
|
|
|
*
|
|
|
|
* @example
|
|
|
|
*
|
|
|
|
* ```ts
|
|
|
|
* nuxt.hook('ready', () => {
|
|
|
|
* console.log(useNitro())
|
|
|
|
* })
|
|
|
|
* ```
|
|
|
|
*/
|
|
|
|
export function useNitro (): Nitro {
|
|
|
|
const nuxt = useNuxt()
|
|
|
|
if (!(nuxt as any)._nitro) {
|
|
|
|
throw new Error('Nitro is not initialized yet. You can call `useNitro()` only after `ready` hook.')
|
|
|
|
}
|
|
|
|
return (nuxt as any)._nitro
|
|
|
|
}
|