Skip to content

Commit

Permalink
Refactor query merge (#194)
Browse files Browse the repository at this point in the history
* refactor query merge

* /api/config with info about installed @wpnuxt modules

* chore: update dependencies
  • Loading branch information
vernaillen authored Aug 30, 2024
1 parent ebdcdd7 commit 1734b42
Show file tree
Hide file tree
Showing 7 changed files with 213 additions and 212 deletions.
10 changes: 5 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,12 @@
"@graphql-codegen/client-preset": "^4.3.3",
"@graphql-codegen/typescript-operations": "^4.2.3",
"@nuxt/devtools": "^1.4.1",
"@nuxt/eslint-config": "^0.5.3",
"@nuxt/eslint-config": "^0.5.4",
"@nuxt/module-builder": "^0.8.3",
"@nuxt/schema": "3.13.0",
"@nuxt/test-utils": "^3.14.1",
"@rollup/rollup-linux-arm64-gnu": "^4.21.1",
"@rollup/rollup-linux-arm64-musl": "^4.21.1",
"@rollup/rollup-linux-arm64-gnu": "^4.21.2",
"@rollup/rollup-linux-arm64-musl": "^4.21.2",
"@types/node": "22.5.1",
"@vitest/coverage-v8": "^2.0.5",
"@vue/test-utils": "^2.4.6",
Expand All @@ -81,14 +81,14 @@
"nuxt": "^3.13.0",
"nuxt-content-twoslash": "^0.1.1",
"release-it": "^17.6.0",
"shiki": "^1.13.0",
"shiki": "^1.15.0",
"twoslash": "^0.2.9",
"typescript": "^5.5.4",
"untyped": "1.4.2",
"vite": "^5.4.2",
"vitest": "^2.0.5",
"vue-docgen-web-types": "^0.1.8",
"vue-tsc": "2.1.0"
"vue-tsc": "2.1.2"
},
"peerDependencies": {
"consola": "^3.2.3",
Expand Down
4 changes: 2 additions & 2 deletions playground/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@
"@iconify-json/mdi": "^1.1.68",
"@iconify-json/svg-spinners": "^1.1.3",
"@iconify-json/uil": "^1.1.9",
"@nuxt/eslint": "^0.5.3",
"@nuxt/image": "^1.7.1",
"@nuxt/eslint": "^0.5.4",
"@nuxt/image": "^1.8.0",
"@nuxt/ui-pro": "^1.4.1",
"nuxt": "^3.13.0",
"vite-plugin-eslint2": "^4.4.0"
Expand Down
276 changes: 118 additions & 158 deletions pnpm-lock.yaml

Large diffs are not rendered by default.

64 changes: 17 additions & 47 deletions src/module.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { existsSync, cpSync, promises as fsp } from 'node:fs'
import { defineNuxtModule, hasNuxtModule, addComponentsDir, addServerHandler, createResolver, installModule, addTemplate, addTypeTemplate, addImports, type Resolver, addPlugin } from '@nuxt/kit'
import { join } from 'pathe'
import { defineNuxtModule, addComponentsDir, addServerHandler, createResolver, installModule, addTemplate, addTypeTemplate, addImports, type Resolver, addPlugin, hasNuxtModule } from '@nuxt/kit'
import consola from 'consola'
import { name, version } from '../package.json'
import type { WPNuxtConfig } from './types'
import { initLogger, validateConfig } from './utils'
import { initLogger, mergeQueries, validateConfig } from './utils'
import { generateWPNuxtComposables } from './generate'
import type { WPNuxtContext } from './context'

Expand All @@ -16,7 +14,9 @@ const defaultConfigs: WPNuxtConfig = {
enableCache: true,
staging: false,
logLevel: 3,
composablesPrefix: 'useWP'
composablesPrefix: 'useWP',
hasBlocksModule: false,
hasAuthModule: false
}

export default defineNuxtModule<WPNuxtConfig>({
Expand All @@ -40,11 +40,14 @@ export default defineNuxtModule<WPNuxtConfig>({
staging: process.env.WPNUXT_STAGING === 'true' || options.staging!,
downloadSchema: process.env.WPNUXT_DOWNLOAD_SCHEMA === 'true' || options.downloadSchema,
logLevel: process.env.WPNUXT_LOG_LEVEL ? Number.parseInt(process.env.WPNUXT_LOG_LEVEL) : options.logLevel,
composablesPrefix: process.env.WPNUXT_COMPOSABLES_PREFIX || options.composablesPrefix
composablesPrefix: process.env.WPNUXT_COMPOSABLES_PREFIX || options.composablesPrefix,
hasBlocksModule: hasNuxtModule('@wpnuxt/blocks'),
hasAuthModule: hasNuxtModule('@wpnuxt/auth')
}
nuxt.options.runtimeConfig.public.wpNuxt = publicWPNuxtConfig
validateConfig(publicWPNuxtConfig)
const logger = initLogger(publicWPNuxtConfig.logLevel)
logger.info('config:', publicWPNuxtConfig)

logger.info('Connecting GraphQL to', publicWPNuxtConfig.wordpressUrl)
logger.info('frontendUrl:', publicWPNuxtConfig.frontendUrl)
Expand Down Expand Up @@ -95,48 +98,15 @@ export default defineNuxtModule<WPNuxtConfig>({
route: '/api/wpContent',
handler: resolveRuntimeModule('./server/api/wpContent.post')
})
addServerHandler({
route: '/api/config',
handler: resolveRuntimeModule('./server/api/config')
})

await installModule('@vueuse/nuxt', {})

const queryOutputPath = resolve((nuxt.options.srcDir || nuxt.options.rootDir) + '/.queries/')
await fsp.rm(queryOutputPath, { recursive: true, force: true })

const userQueryPath = '~/extend/queries/'
.replace(/^(~~|@@)/, nuxt.options.rootDir)
.replace(/^(~|@)/, nuxt.options.srcDir)
const userQueryPathExists = existsSync(userQueryPath)
cpSync(resolveRuntimeModule('./queries/'), queryOutputPath, { recursive: true })

if (hasNuxtModule('@wpnuxt/blocks')) {
for (const m of nuxt.options._installedModules) {
if (m.meta.name === '@wpnuxt/blocks' && m.entryPath) {
logger.debug('Loading queries from @wpnuxt/blocks')
let blocksQueriesPath
if (m.entryPath == '../src/module') {
blocksQueriesPath = join(nuxt.options.rootDir, '../src/runtime/queries/')
} else if (m.entryPath.startsWith('../')) {
blocksQueriesPath = join(nuxt.options.rootDir, '../', m.entryPath, './runtime/queries/')
} else {
blocksQueriesPath = join('./node_modules', m.entryPath, 'dist/runtime/queries/')
}
cpSync(blocksQueriesPath, queryOutputPath, { recursive: true })
}
}
} else {
logger.debug('Tip: Install the @wpnuxt/blocks module if you want to render Gutenberg blocks with separate vue components')
// TODO: find a way to avoid this hack. (it makes sure the dynamic import in WPContent doesn't throw an error)
addTemplate({
write: true,
filename: 'wpnuxt/blocks.mjs',
getContents: () => `export { }`
})
nuxt.options.alias['#wpnuxt/blocks'] = resolve(nuxt.options.buildDir, 'wpnuxt/blocks')
}
if (userQueryPathExists) {
logger.debug('Extending queries:', userQueryPath)
cpSync(resolve(userQueryPath), queryOutputPath, { recursive: true })
}
logger.debug('Copied merged queries in folder:', queryOutputPath)
const mergedQueriesFolder = await mergeQueries(nuxt)
console.log('mergedQueriesFolder', mergedQueriesFolder)

await installModule('nuxt-graphql-middleware', {
debug: publicWPNuxtConfig.logLevel ? publicWPNuxtConfig.logLevel > 3 : false,
Expand Down Expand Up @@ -169,7 +139,7 @@ export default defineNuxtModule<WPNuxtConfig>({
}
},
outputDocuments: true,
autoImportPatterns: queryOutputPath,
autoImportPatterns: mergedQueriesFolder,
includeComposables: true,
devtools: true
})
Expand Down Expand Up @@ -204,7 +174,7 @@ export default defineNuxtModule<WPNuxtConfig>({
fnImports: [],
composablesPrefix: publicWPNuxtConfig.composablesPrefix
}
await generateWPNuxtComposables(ctx, queryOutputPath, srcResolver)
await generateWPNuxtComposables(ctx, mergedQueriesFolder, srcResolver)

addTemplate({
write: true,
Expand Down
7 changes: 7 additions & 0 deletions src/runtime/server/api/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export default defineEventHandler(async (event) => {
const config = useRuntimeConfig(event)
console.log('config', config)
return {
wpNuxt: config.public.wpNuxt
}
})
3 changes: 3 additions & 0 deletions src/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ export interface WPNuxtConfig {
* @default true
*/
downloadSchema?: boolean

hasBlocksModule?: boolean
hasAuthModule?: boolean
}

export interface WPNuxtConfigQueries {
Expand Down
61 changes: 61 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { existsSync, cpSync, promises as fsp } from 'node:fs'
import { type LogLevel, createConsola } from 'consola'
import { ref } from 'vue'
import { hasNuxtModule, addTemplate, createResolver } from '@nuxt/kit'
import { join } from 'pathe'
import type { WPNuxtConfig } from './types'

const loggerRef = ref()
Expand Down Expand Up @@ -36,3 +40,60 @@ export function validateConfig(options: Partial<WPNuxtConfig>) {
throw new Error('WPNuxt error: frontend url should not have a trailing slash: ' + options.frontendUrl)
}
}

export async function mergeQueries(nuxt: any) {
const { resolve } = createResolver(import.meta.url)
const resolveRuntimeModule = (path: string) => resolve('./runtime', path)
const logger = getLogger()

const queryOutputPath = resolve((nuxt.options.srcDir || nuxt.options.rootDir) + '/.queries/')
await fsp.rm(queryOutputPath, { recursive: true, force: true })

const userQueryPath = '~/extend/queries/'
.replace(/^(~~|@@)/, nuxt.options.rootDir)
.replace(/^(~|@)/, nuxt.options.srcDir)
const userQueryPathExists = existsSync(userQueryPath)
cpSync(resolveRuntimeModule('./queries/'), queryOutputPath, { recursive: true })

addQueriesFromAddOnModule('@wpnuxt/blocks', queryOutputPath, nuxt, resolve)
addQueriesFromAddOnModule('@wpnuxt/auth', queryOutputPath, nuxt, resolve)

if (userQueryPathExists) {
logger.debug('Extending queries:', userQueryPath)
cpSync(resolve(userQueryPath), queryOutputPath, { recursive: true })
}
logger.debug('Copied merged queries in folder:', queryOutputPath)
return queryOutputPath
}

// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
function addQueriesFromAddOnModule(addOnModuleName: string, queryOutputPath: string, nuxt: any, resolve: Function) {
const logger = getLogger()
if (hasNuxtModule(addOnModuleName)) {
console.log('addOnModule found:', addOnModuleName)
for (const m of nuxt.options._installedModules) {
if (m.meta.name === addOnModuleName && m.entryPath) {
logger.debug('Loading queries from ' + addOnModuleName)
let blocksQueriesPath
if (m.entryPath == '../src/module') {
blocksQueriesPath = join(nuxt.options.rootDir, '../src/runtime/queries/')
} else if (m.entryPath.startsWith('../')) {
blocksQueriesPath = join(nuxt.options.rootDir, '../', m.entryPath, './runtime/queries/')
} else {
blocksQueriesPath = join('./node_modules', m.entryPath, 'dist/runtime/queries/')
}
console.log('blocksQueriesPath', blocksQueriesPath)
cpSync(blocksQueriesPath, queryOutputPath, { recursive: true })
}
}
} else {
const moduleName = addOnModuleName.replace('@', '')
// TODO: (should we?) find a way to avoid this hack. (it makes sure the dynamic import in WPContent doesn't throw an error)
addTemplate({
write: true,
filename: moduleName + '.mjs',
getContents: () => `export { }`
})
nuxt.options.alias['#' + moduleName] = resolve(nuxt.options.buildDir, moduleName)
}
}

0 comments on commit 1734b42

Please sign in to comment.