Skip to content

Commit

Permalink
fix: support function expressions in module config (#537)
Browse files Browse the repository at this point in the history
  • Loading branch information
miii committed Nov 23, 2023
1 parent 8708b53 commit 1d6e1f7
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
5 changes: 3 additions & 2 deletions src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { useLogger, addPlugin, addImports, addTemplate, createResolver, defineNu
import GraphQLPlugin from '@rollup/plugin-graphql'
import { name, version } from '../package.json'
import type { ClientConfig, NuxtApolloConfig, ErrorResponse } from './types'
import { serializeConfig } from './serialize'

export type { ClientConfig, ErrorResponse }

Expand Down Expand Up @@ -107,8 +108,8 @@ export default defineNuxtModule<NuxtApolloConfig<any>>({
'export default {',
` proxyCookies: ${options.proxyCookies},`,
` clientAwareness: ${options.clientAwareness},`,
` cookieAttributes: ${JSON.stringify(options.cookieAttributes)},`,
` clients: ${JSON.stringify(clients)}`,
` cookieAttributes: ${serializeConfig(options.cookieAttributes)},`,
` clients: ${serializeConfig(clients)}`,
'}'
].join('\n')
})
Expand Down
22 changes: 22 additions & 0 deletions src/serialize.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/**
* Serialize config to be used in templates
* @param obj Config object
* @returns Stringified config with kept function expressions
*/
export const serializeConfig = (obj: any) => {
// Stringify function body
if (typeof obj === 'function') {
return obj.toString()
}

// Run recursively on objects and arrays
if (typeof obj === 'object') {
if (Array.isArray(obj)) {
return `[${obj.map(serializeConfig).join(', ')}]`
} else {
return `{${Object.entries(obj).map(([key, value]) => `${serializeConfig(key)}: ${serializeConfig(value)}`).join(', ')}}`
}
}

return JSON.stringify(obj)
}

0 comments on commit 1d6e1f7

Please sign in to comment.