Skip to content

Commit

Permalink
fix generated types, create server utils
Browse files Browse the repository at this point in the history
  • Loading branch information
dulnan committed Nov 15, 2024
1 parent 725e3d4 commit 8af5c5e
Show file tree
Hide file tree
Showing 17 changed files with 235 additions and 45 deletions.
2 changes: 1 addition & 1 deletion build.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export default defineBuildConfig({
'@polka/url',
'mrmime',
'#graphql-middleware/types',
'#build/nuxt-graphql-middleware',
'#nuxt-graphql-middleware/generated-types',
'#graphql-middleware-server-options-build',
],
})
2 changes: 2 additions & 0 deletions playground/app/plugins/graphqlConfig.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useGraphqlState, defineNuxtPlugin, useCurrentLanguage } from '#imports'
import type { GraphqlResponseTyped } from '#graphql-middleware-server-options-build'

/**
* This is only called when performing a query or mutation from within the nuxt
Expand Down Expand Up @@ -37,6 +38,7 @@ export default defineNuxtPlugin({

async onResponse(ctx) {
const data = ctx.response?._data?.data
console.log(ctx.response?._data?.__cacheability)
},
}
},
Expand Down
6 changes: 3 additions & 3 deletions playground/server/api/fetch-options.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useGraphqlQuery } from '#graphql-composable'
import { useGraphqlQuery } from '#imports'
import { defineEventHandler } from 'h3'

/**
Expand All @@ -7,6 +7,6 @@ import { defineEventHandler } from 'h3'
*/
export default defineEventHandler(async () => {
// Return value is fully typed.
const { data } = await useGraphqlQuery('fetchOptions')
return data
const data = await useGraphqlQuery('fetchOptions')
return data.data
})
11 changes: 8 additions & 3 deletions playground/server/api/server-route.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useGraphqlQuery } from '#graphql-composable'
import { useGraphqlQuery } from '#imports'
import { defineEventHandler } from 'h3'

/**
Expand All @@ -7,6 +7,11 @@ import { defineEventHandler } from 'h3'
*/
export default defineEventHandler(async () => {
// Return value is fully typed.
const { data } = await useGraphqlQuery('users')
return data.users.map((v) => v.email)
const data = await useGraphqlQuery({
name: 'users',
clientContext: {
language: 'de',
},
})
return data.data.users.map((v) => v.email)
})
4 changes: 2 additions & 2 deletions src/codegen/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,9 +133,9 @@ export const plugin: PluginFunction<PluginConfig, string> = (
import type { GraphqlResponse } from '#graphql-middleware-server-options-build'
import type {
${imports.join(',\n ')}
} from './graphql-operations'\n
} from './../graphql-operations'\n
declare module '#build/nuxt-graphql-middleware' {
declare module '#nuxt-graphql-middleware/generated-types' {
export type GraphqlMiddlewareResponseUnion = ${resultTypes.join(' | ')}
${code}
}
Expand Down
28 changes: 22 additions & 6 deletions src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
addPlugin,
addImports,
resolveAlias,
addServerImports,
} from '@nuxt/kit'
import inquirer from 'inquirer'
import { type TypeScriptDocumentsPluginConfig } from '@graphql-codegen/typescript-operations'
Expand Down Expand Up @@ -434,9 +435,6 @@ export default defineNuxtModule<ModuleOptions>({
),
name: 'useAsyncGraphqlQuery',
})
nuxt.options.alias['#graphql-composable'] = moduleResolver.resolve(
'runtime/composables/server',
)

if (options.enableFileUploads) {
addImports({
Expand All @@ -448,6 +446,19 @@ export default defineNuxtModule<ModuleOptions>({
}
}

addServerImports([
{
from: moduleResolver.resolve('./runtime/server/utils/index.ts'),
name: 'useGraphqlQuery',
as: 'useGraphqlQuery',
},
{
from: moduleResolver.resolve('./runtime/server/utils/index.ts'),
name: 'useGraphqlMutation',
as: 'useGraphqlMutation',
},
])

// Add the templates to nuxt and provide a callback to load the file contents.
Object.values(GraphqlMiddlewareTemplate).forEach((filename) => {
const result = addTemplate({
Expand All @@ -471,6 +482,11 @@ export default defineNuxtModule<ModuleOptions>({
result.dst.includes(GraphqlMiddlewareTemplate.OperationTypes)
) {
nuxt.options.alias['#graphql-operations'] = result.dst
} else if (
result.dst.includes(GraphqlMiddlewareTemplate.ComposableContext)
) {
nuxt.options.alias['#nuxt-graphql-middleware/generated-types'] =
result.dst
}
})

Expand All @@ -482,7 +498,7 @@ export default defineNuxtModule<ModuleOptions>({
import type {
GraphqlMiddlewareQuery,
GraphqlMiddlewareMutation,
} from '#build/nuxt-graphql-middleware'
} from '#nuxt-graphql-middleware/generated-types'
declare module '#graphql-documents' {
type Documents = {
Expand Down Expand Up @@ -564,10 +580,10 @@ export { serverOptions }
import type { GraphqlMiddlewareServerOptions } from '${moduleTypesPath}'
${serverOptionsLineTypes}
import type { GraphqlServerResponse } from '#graphql-middleware/types'
import type { GraphqlMiddlewareResponseUnion } from '#build/nuxt-graphql-middleware'
import type { GraphqlMiddlewareResponseUnion } from '#nuxt-graphql-middleware/generated-types'
type GraphqlResponseAdditions =
typeof serverOptions extends GraphqlMiddlewareServerOptions<infer R> ? R : {}
typeof serverOptions extends GraphqlMiddlewareServerOptions<infer R, any, any> ? R : {}
export type GraphqlResponse<T> = GraphqlServerResponse<T> & GraphqlResponseAdditions
Expand Down
31 changes: 23 additions & 8 deletions src/runtime/composables/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,13 @@ import {
type GetMutationArgs,
type MutationObjectArgs,
type GetMutationResult,
encodeContext,
} from './shared'
import { buildRequestParams } from './../helpers'
import type {
GraphqlMiddlewareQuery,
GraphqlMiddlewareMutation,
} from '#build/nuxt-graphql-middleware'
} from '#nuxt-graphql-middleware/generated-types'

function performRequest<T>(
operation: string,
Expand Down Expand Up @@ -45,13 +46,21 @@ export function useGraphqlQuery<
| GetQueryArgs<T, GraphqlMiddlewareQuery>
| [QueryObjectArgs<T, GraphqlMiddlewareQuery>]
): Promise<GraphqlResponse<R>> {
const [name, variables, fetchOptions = {}] =
const [name, variables, fetchOptions = {}, clientContext = {}] =
typeof args[0] === 'string'
? [args[0], args[1]]
: [args[0].name, args[0].variables, args[0].fetchOptions]
? [args[0], args[1], args[2]?.fetchOptions, args[2]?.clientContext]
: [
args[0].name,
args[0].variables,
args[0].fetchOptions,
args[0].clientContext,
]

return performRequest<R>('query', name, 'get', {
params: buildRequestParams(variables),
params: {
...buildRequestParams(variables),
...encodeContext(clientContext),
},
...fetchOptions,
})
}
Expand All @@ -67,13 +76,19 @@ export function useGraphqlMutation<
| GetMutationArgs<T, GraphqlMiddlewareMutation>
| [MutationObjectArgs<T, GraphqlMiddlewareMutation>]
): Promise<GraphqlResponse<R>> {
const [name, body, fetchOptions = {}] =
const [name, body, fetchOptions = {}, clientContext = {}] =
typeof args[0] === 'string'
? [args[0], args[1]]
: [args[0].name, args[0].variables, args[0].fetchOptions]
? [args[0], args[1], args[2]?.fetchOptions, args[2]?.clientContext]
: [
args[0].name,
args[0].variables,
args[0].fetchOptions,
args[0].clientContext,
]

return performRequest<R>('mutation', name, 'post', {
body,
params: encodeContext(clientContext),
...fetchOptions,
})
}
8 changes: 7 additions & 1 deletion src/runtime/composables/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@ import { useRuntimeConfig } from '#imports'
import type {
GraphqlMiddlewareQuery,
GraphqlMiddlewareMutation,
} from '#build/nuxt-graphql-middleware'
} from '#nuxt-graphql-middleware/generated-types'
import type { RequestCacheOptions } from '#graphql-middleware/types'
import { CLIENT_CONTEXT_PREFIX } from '../settings'
import type { GraphqlClientContext } from '#graphql-middleware-client-options'

// Possible query names.
export type GraphqlMiddlewareQueryName = keyof GraphqlMiddlewareQuery
Expand All @@ -15,6 +16,7 @@ export type GraphqlMiddlewareMutationName = keyof GraphqlMiddlewareMutation
export type GraphqlComposableOptions = {
fetchOptions?: FetchOptions
graphqlCaching?: RequestCacheOptions
clientContext?: Partial<GraphqlClientContext>
}

// Determine the argument signature for the query method.
Expand Down Expand Up @@ -63,13 +65,15 @@ export type QueryObjectArgs<
name: T
fetchOptions?: FetchOptions
graphqlCaching?: RequestCacheOptions
clientContext?: Partial<GraphqlClientContext>
variables?: null
}
: {
name: T
variables: M[T][0]
fetchOptions?: FetchOptions
graphqlCaching?: RequestCacheOptions
clientContext?: Partial<GraphqlClientContext>
}

export type MutationObjectArgs<
Expand All @@ -80,11 +84,13 @@ export type MutationObjectArgs<
name: T
variables?: null
fetchOptions?: FetchOptions
clientContext?: Partial<GraphqlClientContext>
}
: {
name: T
variables: M[T][0]
fetchOptions?: FetchOptions
clientContext?: Partial<GraphqlClientContext>
}

export type PickFrom<T, K extends Array<string>> =
Expand Down
15 changes: 12 additions & 3 deletions src/runtime/composables/useAsyncGraphqlQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,11 @@ import type { FetchOptions } from 'ofetch'
import { type Ref, isRef, unref } from 'vue'
import { buildRequestParams } from './../helpers'
import { performRequest } from './nuxtApp'
import { clientOptions } from '#graphql-middleware-client-options'
import type { GraphqlMiddlewareQuery } from '#build/nuxt-graphql-middleware'
import {
clientOptions,
type GraphqlClientContext,
} from '#graphql-middleware-client-options'
import type { GraphqlMiddlewareQuery } from '#nuxt-graphql-middleware/generated-types'
import { useAsyncData, useAppConfig, useNuxtApp } from '#imports'
import { hash } from 'ohash'
import type { GraphqlResponse } from '#graphql-middleware-server-options-build'
Expand All @@ -24,6 +27,7 @@ type AsyncGraphqlQueryOptions<
> = AsyncDataOptions<ResponseType, DefaultT, Keys> & {
graphqlCaching?: RequestCacheOptions
fetchOptions?: F
clientContext?: Partial<GraphqlClientContext>
}

/**
Expand Down Expand Up @@ -105,9 +109,14 @@ export function useAsyncGraphqlQuery<
return useAsyncData<GraphqlResponse<ResponseType>, unknown, DefaultT>(
key,
() => {
const clientContext = clientOptions.buildClientContext
const globalClientContext = clientOptions.buildClientContext
? encodeContext(clientOptions.buildClientContext())
: {}

const clientContext = {
...globalClientContext,
...(asyncDataOptions.clientContext || {}),
}
return performRequest<ResponseType>(
'query',
name,
Expand Down
20 changes: 15 additions & 5 deletions src/runtime/composables/useGraphqlMutation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
} from './shared'
import { performRequest } from './nuxtApp'
import { clientOptions } from '#graphql-middleware-client-options'
import type { GraphqlMiddlewareMutation } from '#build/nuxt-graphql-middleware'
import type { GraphqlMiddlewareMutation } from '#nuxt-graphql-middleware/generated-types'
import type { GraphqlResponse } from '#graphql-middleware-server-options-build'

/**
Expand All @@ -21,15 +21,25 @@ export function useGraphqlMutation<
| GetMutationArgs<T, GraphqlMiddlewareMutation>
| [MutationObjectArgs<T, GraphqlMiddlewareMutation>]
): Promise<GraphqlResponse<R>> {
const [name, body, fetchOptions = {}] =
const [name, body, fetchOptions = {}, overrideClientContext = {}] =
typeof args[0] === 'string'
? [args[0], args[1], args[2]?.fetchOptions]
: [args[0].name, args[0].variables, args[0].fetchOptions]
? [args[0], args[1], args[2]?.fetchOptions, args[2]?.clientContext]
: [
args[0].name,
args[0].variables,
args[0].fetchOptions,
args[0].clientContext,
]

const clientContext = clientOptions.buildClientContext
const globalClientContext = clientOptions.buildClientContext
? encodeContext(clientOptions.buildClientContext())
: {}

const clientContext = {
...globalClientContext,
...overrideClientContext,
}

return performRequest<R>('mutation', name, 'post', {
body,
params: {
Expand Down
26 changes: 22 additions & 4 deletions src/runtime/composables/useGraphqlQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
import { buildRequestParams } from './../helpers'
import { performRequest } from './nuxtApp'
import { clientOptions } from '#graphql-middleware-client-options'
import type { GraphqlMiddlewareQuery } from '#build/nuxt-graphql-middleware'
import type { GraphqlMiddlewareQuery } from '#nuxt-graphql-middleware/generated-types'
import type { GraphqlResponse } from '#graphql-middleware-server-options-build'

/**
Expand All @@ -22,20 +22,38 @@ export function useGraphqlQuery<
| GetQueryArgs<T, GraphqlMiddlewareQuery>
| [QueryObjectArgs<T, GraphqlMiddlewareQuery>]
): Promise<GraphqlResponse<R>> {
const [name, variables, fetchOptions = {}, graphqlCaching = {}] =
const [
name,
variables,
fetchOptions = {},
graphqlCaching = {},
overrideClientContext = {},
] =
typeof args[0] === 'string'
? [args[0], args[1], args[2]?.fetchOptions, args[2]?.graphqlCaching]
? [
args[0],
args[1],
args[2]?.fetchOptions,
args[2]?.graphqlCaching,
args[2]?.clientContext,
]
: [
args[0].name,
args[0].variables,
args[0].fetchOptions,
args[0].graphqlCaching,
args[0].clientContext,
]

const clientContext = clientOptions.buildClientContext
const globalClientContext = clientOptions.buildClientContext
? encodeContext(clientOptions.buildClientContext())
: {}

const clientContext = {
...globalClientContext,
...overrideClientContext,
}

return performRequest<R>(
'query',
name,
Expand Down
Loading

0 comments on commit 8af5c5e

Please sign in to comment.