-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
105 generate fully typed composables based on queries (#108)
* Generate fully typed composables based on queries #105 * lint:fix * run github ci on PR's * added peerDependencies, because Build is done with some warnings: - Inlined implicit external consola - Inlined implicit external scule - Inlined implicit external graphql * moved parser, so it can be called from module.ts * workaround for The inferred type of 'default' cannot be named without a reference * moved parser, so it can be called from module.ts * fix consola LogLevel issue
- Loading branch information
1 parent
458079e
commit d041d99
Showing
21 changed files
with
833 additions
and
747 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
<script setup lang="ts"> | ||
import { useRuntimeConfig } from 'nuxt/app' | ||
import { wpPosts, wpPostByUri } from '#wpnuxt' | ||
const prefix = useRuntimeConfig().public.wpNuxt.generateComposables?.prefix | ||
const { data: posts } = await wpPosts() | ||
const { data: postsLimited } = await wpPosts({ limit: 1 }) | ||
const { data: postByUri } = await wpPostByUri({ uri: 'hello-world' }) | ||
</script> | ||
|
||
<template> | ||
<div> | ||
<UContainer class="prose dark:prose-invert pt-5"> | ||
<h2>Examples of generated composables</h2> | ||
<p> | ||
prefix for composables: {{ prefix }} | ||
</p> | ||
<h3>{{ prefix }}Posts()</h3> | ||
<ul> | ||
<li | ||
v-for="post in posts?.posts?.nodes" | ||
:key="post.id" | ||
> | ||
{{ post.title }} | ||
</li> | ||
</ul> | ||
<h3>{{ prefix }}Posts({ limit: 1 })</h3> | ||
<ul> | ||
<li | ||
v-for="post in postsLimited?.posts?.nodes" | ||
:key="post.id" | ||
> | ||
{{ post.title }} | ||
</li> | ||
</ul> | ||
<h3>{{ prefix }}PostByUri({ uri: 'hello-world' })</h3> | ||
<p> | ||
{{ postByUri?.nodeByUri?.title }} | ||
</p> | ||
</UContainer> | ||
</div> | ||
</template> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
import { promises as fsp } from 'node:fs' | ||
import { upperFirst } from 'scule' | ||
import type { Import } from 'unimport' | ||
import type { WPNuxtConfigComposables, WPNuxtQuery } from './types' | ||
import { getLogger } from './utils' | ||
import { parseDoc } from './useParser' | ||
|
||
export interface WPNuxtContext { | ||
composables: WPNuxtConfigComposables | ||
template?: string | ||
fns: WPNuxtQuery[] | ||
fnImports?: Import[] | ||
generateImports?: () => string | ||
generateDeclarations?: () => string | ||
docs?: string[] | ||
} | ||
|
||
export async function prepareContext(ctx: WPNuxtContext) { | ||
const logger = getLogger() | ||
if (ctx.docs) { | ||
await prepareFunctions(ctx) | ||
} | ||
|
||
const fnName = (fn: string) => ctx.composables.prefix + upperFirst(fn) | ||
|
||
const fnExp = (q: WPNuxtQuery, typed = false) => { | ||
const functionName = fnName(q.name) | ||
if (!typed) { | ||
return `export const ${functionName} = (params) => fetchContent('${q.name}', params)` | ||
} | ||
return ` export const ${functionName}: (params?: ${q.name}QueryVariables) => AsyncData<${q.name}Query | undefined, FetchError | null | undefined>` | ||
} | ||
|
||
ctx.generateImports = () => [ | ||
'import { useGraphqlQuery } from \'#graphql-composable\'', | ||
...ctx.fns.map(f => fnExp(f)) | ||
].join('\n') | ||
|
||
ctx.generateDeclarations = () => [ | ||
`import type { ${ctx.fns.map(o => getQueryTypeTemplate(o)).join(', ')} } from '#graphql-operations'`, | ||
'import { AsyncData } from \'nuxt/app\'', | ||
'import { FetchError } from \'ofetch\'', | ||
'declare module \'#wpnuxt\' {', | ||
...([ | ||
...ctx.fns!.map(f => fnExp(f, true)) | ||
]), | ||
'}' | ||
].join('\n') | ||
|
||
ctx.fnImports = ctx.fns.map((fn): Import => ({ from: '#wpnuxt', name: fnName(fn.name) })) | ||
|
||
logger.debug('generated WPNuxt composables: ') | ||
ctx.fns.forEach(f => logger.debug(` ${fnName(f.name)}()`)) | ||
} | ||
|
||
function getQueryTypeTemplate(q: WPNuxtQuery) { | ||
return `${q.name}Query, ${q.name}QueryVariables` | ||
} | ||
|
||
async function prepareFunctions(ctx: WPNuxtContext) { | ||
if (!ctx.docs) { | ||
getLogger().error('no GraphQL query documents were found!') | ||
return | ||
} | ||
for await (const doc of ctx.docs) { | ||
const operations = await parseDoc(await fsp.readFile(doc, 'utf8')) | ||
operations.forEach((query) => { | ||
ctx.fns.push(query) | ||
}) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
import { statSync } from 'node:fs' | ||
import { type Resolver, resolveFiles } from '@nuxt/kit' | ||
import { prepareContext, type WPNuxtContext } from './context' | ||
|
||
const allowDocument = (f: string, resolver: Resolver) => { | ||
const isSchema = f.match(/([^/]+)\.(gql|graphql)$/)?.[0]?.toLowerCase().includes('schema') | ||
return !isSchema && !!statSync(resolver.resolve(f)).size | ||
} | ||
export async function generateWPNuxtComposables(ctx: WPNuxtContext, queryOutputPath: string, resolver: Resolver) { | ||
const gqlMatch = '**/*.{gql,graphql}' | ||
const documents: string[] = [] | ||
const files = (await resolveFiles(queryOutputPath, [gqlMatch, '!**/schemas'], { followSymbolicLinks: false })).filter(doc => allowDocument(doc, resolver)) | ||
documents.push(...files) | ||
ctx.docs = documents | ||
|
||
await prepareContext(ctx) | ||
} |
Oops, something went wrong.