unjs / nitro

Next Generation Server Toolkit. Create web servers with everything you need and deploy them wherever you prefer.
https://nitro.unjs.io
MIT License
5.82k stars 492 forks source link

Unable to dynamically add a driver for a storage named `cache` in a plugin #2674

Open censujiang opened 3 weeks ago

censujiang commented 3 weeks ago

Environment

Reproduction

https://stackblitz.com/edit/github-sbrgxd?file=server%2Fplugins%2Fstorage.ts

Describe the bug

As the title indicates, as long as the driver name is cache, an error will occur during the build or dev.

https://github.com/unjs/nitro/issues/1161#issuecomment-2295248527

Additional context

The problem occurs in the build phase of my Nuxt App, but not in the dev phase of the Nitro copy I provided

Logs

ERROR  [nuxt] [request error] [unhandled] [500] Cannot access 'nitroApp' before initialization                                                                                                                                          20:03:46  
  at Object.onRequest (/D:/my-nuxt-template/.nuxt/prerender/chunks/runtime.mjs:6801:7)
  at Object.handler (/D:/my-nuxt-template/node_modules/h3/dist/index.mjs:1959:21)
  at toNodeHandle (/D:/my-nuxt-template/node_modules/h3/dist/index.mjs:2266:17)
  at callHandle (/D:/my-nuxt-template/node_modules/unenv/runtime/fetch/call.mjs:25:12)
  at ufetch (/D:/my-nuxt-template/node_modules/unenv/runtime/fetch/index.mjs:9:23)
  at Object.localFetch (/D:/my-nuxt-template/.nuxt/prerender/chunks/runtime.mjs:6821:39)
  at /D:/my-nuxt-template/.nuxt/prerender/chunks/runtime.mjs:3162:36
`
censujiang commented 3 weeks ago

key code:

import redisDriver from 'unstorage/drivers/redis'
import azureAppConfigurationDriver from 'unstorage/drivers/azure-app-configuration'

export default defineNitroPlugin((nuxtApp) => {
  const storage = useStorage()
  if (useRuntimeConfig().systemRuntimeType == 'azure') {
    storage.unmount('cache')
    const azure = azureAppConfigurationDriver({
      prefix: "default",
      label: "cache",
    })
    storage.mount('cache', azure)
  } else {
    storage.unmount('cache')
    const redis = redisDriver({
      url: "redis://localhost:6379",
    })
    storage.mount('cache', redis)
  }
})