UNPKG

@toantranmei/mei-nuxt3-fetcher

Version:
73 lines (67 loc) 2.1 kB
import { defineNuxtModule, useLogger, createResolver, addImports, addPlugin, addImportsDir } from '@nuxt/kit'; import defu from 'defu'; import { existsSync, statSync } from 'node:fs'; import { parseURL, joinURL } from 'ufo'; const name = "@toantranmei/mei-nuxt3-fetcher"; const version = "0.0.6"; const MODULE_CONFIG_KEY = "meiFetcher"; function getOriginAndPathnameFromURL(url) { const { protocol, host, pathname } = parseURL(url); let origin; if (host && protocol) origin = `${protocol}//${host}`; const pathname_ = pathname.length > 0 ? pathname : void 0; return { origin, pathname: pathname_ }; } const module = defineNuxtModule({ meta: { name, version, configKey: MODULE_CONFIG_KEY }, // Default configuration options of the Nuxt module defaults: { isEnabled: true, baseURL: "https://jsonplaceholder.typicode.com" }, async setup(userOptions, nuxt) { const logger = useLogger(name); const { origin, pathname = "/resources" } = getOriginAndPathnameFromURL( userOptions.baseURL ?? "" ); const options = { ...defu(userOptions, { computed: { origin, pathname, fullBaseUrl: joinURL(origin ?? "", pathname) } }) }; if (!options.isEnabled) { logger.info(`Skipping \`${name}\` setup, as module is disabled`); return; } logger.info(`\`${name}\` setup starting`); nuxt.options.runtimeConfig = nuxt.options.runtimeConfig || { public: {} }; nuxt.options.runtimeConfig.public.meiFetcher = options; const { resolve } = createResolver(import.meta.url); addImports([ { name: "HttpFactory", from: resolve(`./runtime/factory`) } ]); addPlugin(resolve("./runtime/plugins/fetcher")); for (const layer of nuxt.options._layers) { const servicesPath = resolve(layer.cwd, "services"); if (existsSync(servicesPath) && statSync(servicesPath).isDirectory()) addImportsDir(servicesPath); } logger.success(`\`${name}\` setup done`); } }); export { module as default };