Skip to content

Commit

Permalink
chore: Add playground example for layers (#41)
Browse files Browse the repository at this point in the history
* add playground example with layers

* prevent uncaught exception with empty GraphQL files

* build layers playground in CI

* fix tests
  • Loading branch information
dulnan authored Oct 19, 2024
1 parent 01aa2e3 commit 214a4ca
Show file tree
Hide file tree
Showing 28 changed files with 218 additions and 9 deletions.
4 changes: 4 additions & 0 deletions .github/workflows/node.js.yml
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,10 @@ jobs:
run: |
npm run lint
- name: Build layers playground
run: |
npm run dev:layers:build
- name: Run vitest
run: |
npm run dev:build
Expand Down
2 changes: 1 addition & 1 deletion .graphqlrc.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
schema: './playground/schema.graphql'
schema: './schema.graphql'
documents:
- './playground/app/pages/**/*.graphql'
- './playground/app/components/**/*.graphql'
Expand Down
2 changes: 1 addition & 1 deletion .prettierignore
Original file line number Diff line number Diff line change
@@ -1 +1 @@
playground/schema.graphql
schema.graphql
8 changes: 8 additions & 0 deletions apollo/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,10 @@ const typeDefs = `#graphql
headerServer: String
}
type DataForLayer {
text: String
}
type Query {
users: [User!]!
userById(id: ID!): User
Expand All @@ -103,6 +107,7 @@ const typeDefs = `#graphql
getError: Boolean
getSubmissions: [FormSubmission]
getCurrentTime: String
dataForLayer: DataForLayer
}
type UploadedFile {
Expand Down Expand Up @@ -161,6 +166,9 @@ const resolvers = {
getCurrentTime: () => {
return new Date()
},
dataForLayer: () => {
return { text: 'This is data for the layer page.' }
},
getSubmissions: () => {
return formSubmissions
},
Expand Down
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,11 @@
"scripts": {
"prepack": "nuxt-module-build build && npm run client:build",
"dev": "nuxi dev playground --trace-warnings",
"dev:layers": "nuxi dev playground-layers --trace-warnings",
"debug": "nuxi dev playground --inspect",
"dev:build": "nuxi build playground",
"dev:prepare": "MODULE_BUILD=true nuxt-module-build build --stub && MODULE_BUILD=true nuxt-module-build prepare && nuxi prepare playground",
"dev:layers:build": "nuxi build playground-layers",
"dev:prepare": "MODULE_BUILD=true nuxt-module-build build --stub && MODULE_BUILD=true nuxt-module-build prepare && nuxi prepare playground && nuxi prepare playground-layers",
"dev:start": "node ./playground/.output/server/index.mjs",
"client:build": "nuxi generate client",
"client:dev": "nuxi dev client --port 3300",
Expand Down
9 changes: 9 additions & 0 deletions playground-layers/app/app.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<template>
<div>
<header>
<NuxtLink to="/">Base Page</NuxtLink>
<NuxtLink to="/test-layer">Test Layer</NuxtLink>
</header>
<NuxtPage />
</div>
</template>
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
fragment userLayer on User {
id
firstName
lastName
}
15 changes: 15 additions & 0 deletions playground-layers/app/components/User/index.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<template>
<tr>
<td>{{ id }}</td>
<td>{{ firstName }}</td>
<td>{{ lastName }}</td>
</tr>
</template>

<script lang="ts" setup>
defineProps<{
id: string
firstName: string
lastName: string
}>()
</script>
18 changes: 18 additions & 0 deletions playground-layers/app/pages/index.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<template>
<table v-if="users">
<tbody>
<User v-for="user in users" v-bind="user" :key="user.id" />
</tbody>
</table>
</template>

<script setup lang="ts">
import { useAsyncGraphqlQuery } from '#imports'
const { data: users } = await useAsyncGraphqlQuery('usersLayer', null, {
transform: (v) => v.data.users,
graphqlCaching: {
client: true,
},
})
</script>
7 changes: 7 additions & 0 deletions playground-layers/app/pages/query.usersLayer.graphql
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
#import '~/components/User/fragment.userLayer.graphql'

query usersLayer {
users {
...userLayer
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<template>
<div>This is a component from a layer.</div>
</template>
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
fragment dataForLayer on DataForLayer {
text
}
13 changes: 13 additions & 0 deletions playground-layers/layers/test-layer/nuxt.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { resolve } from 'node:path'

export default defineNuxtConfig({
app: {
head: {
title: 'Title from a layer',
},
},

alias: {
'#test-layer': resolve(__dirname, './'),
},
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
#import '#test-layer/components/fragment.layerData.graphql'

query layerData {
dataForLayer {
...dataForLayer
}
}
17 changes: 17 additions & 0 deletions playground-layers/layers/test-layer/pages/test-layer.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<template>
<main>
<div>A page from a layer.</div>

<code>{{ data }}</code>
</main>
</template>

<script lang="ts" setup>
import { useAsyncGraphqlQuery } from '#imports'
const { data } = await useAsyncGraphqlQuery('layerData', null, {
transform: function (v) {
return v.data.dataForLayer
},
})
</script>
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { defineGraphqlServerOptions } from './../../../../src/runtime/serverOptions/index'

export default defineGraphqlServerOptions({})
43 changes: 43 additions & 0 deletions playground-layers/nuxt.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { defineNuxtConfig } from 'nuxt/config'
import graphqlMiddlewareModule, { type ModuleOptions } from './../src/module'
const IS_DEV = process.env.NODE_ENV === 'development'

const graphqlMiddleware: ModuleOptions = {
graphqlEndpoint: 'http://localhost:4000',
downloadSchema: IS_DEV,
codegenConfig: {},
outputDocuments: false,
schemaPath: './../schema.graphql',
autoInlineFragments: false,
codegenSchemaConfig: {
urlSchemaOptions: {
headers: {
authentication: 'server-token',
},
},
},

clientCache: {
enabled: true,
},

enableFileUploads: false,
}

export default defineNuxtConfig({
modules: [graphqlMiddlewareModule as any],
graphqlMiddleware,
ssr: true,

extends: ['./layers/test-layer'],

imports: {
autoImport: false,
},

future: {
compatibilityVersion: 4,
},

compatibilityDate: '2024-09-14',
})
4 changes: 4 additions & 0 deletions playground-layers/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"private": true,
"name": "nuxt-graphql-middleware-playground-layers"
}
12 changes: 12 additions & 0 deletions playground-layers/server/graphqlMiddleware.serverOptions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { defineGraphqlServerOptions } from './../../src/runtime/serverOptions/index'

export default defineGraphqlServerOptions({
serverFetchOptions: function (event, _operation, operationName) {
const headers: Record<string, any> = {
'x-nuxt-header-server': 'Value from server',
authentication: 'server-token',
'x-apollo-operation-name': operationName,
}
return { headers }
},
})
3 changes: 3 additions & 0 deletions playground-layers/server/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": "../.nuxt/tsconfig.server.json"
}
3 changes: 3 additions & 0 deletions playground-layers/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": "./.nuxt/tsconfig.json"
}
1 change: 1 addition & 0 deletions playground/nuxt.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const IS_DEV = process.env.NODE_ENV === 'development'
const graphqlMiddleware: ModuleOptions = {
graphqlEndpoint: 'http://localhost:4000',
downloadSchema: IS_DEV,
schemaPath: './../schema.graphql',
codegenConfig: {},
outputDocuments: true,
autoInlineFragments: true,
Expand Down
5 changes: 5 additions & 0 deletions playground/schema.graphql → schema.graphql
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
type DataForLayer {
text: String
}

type FormSubmission {
documents: [FormSubmissionDocument]
firstName: String
Expand Down Expand Up @@ -31,6 +35,7 @@ type Mutation {
}

type Query {
dataForLayer: DataForLayer
getCurrentTime: String
getError: Boolean
getRequestHeader(name: String!): String
Expand Down
9 changes: 9 additions & 0 deletions src/helpers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ export async function autoImportDocuments(
if (!patterns.length) {
return Promise.resolve([])
}
console.log({ patterns })
const files = (
await resolveFiles(srcResolver(), patterns, {
followSymbolicLinks: false,
Expand Down Expand Up @@ -189,6 +190,10 @@ export async function buildDocuments(
}
return documents
.map((v) => {
// Ignore empty files.
if (!v.content.trim()) {
return null
}
try {
return {
content: inlineFragments(v.content, resolveAlias),
Expand All @@ -204,6 +209,10 @@ export async function buildDocuments(
})
.filter(falsy)
})
.then((docs) => {
// Ignore empty files.
return docs.filter((v) => v.content.trim())
})

if (!autoInlineFragments) {
return documents
Expand Down
2 changes: 1 addition & 1 deletion src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@ export default defineNuxtModule<ModuleOptions>({
if (isModuleBuild) {
options.graphqlEndpoint = 'http://localhost'
options.downloadSchema = false
options.schemaPath = '~~/playground/schema.graphql'
options.schemaPath = '~~/schema.graphql'
options.autoInlineFragments = true
options.autoImportPatterns = [
'~~/playground/**/*.{gql,graphql}',
Expand Down
18 changes: 18 additions & 0 deletions test/helpers/__snapshots__/generate.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,11 @@ export type Scalars = {
Upload: { input: any; output: any; }
};
export type DataForLayer = {
__typename?: 'DataForLayer';
text?: Maybe<Scalars['String']['output']>;
};
export type FormSubmission = {
__typename?: 'FormSubmission';
documents?: Maybe<Array<Maybe<FormSubmissionDocument>>>;
Expand Down Expand Up @@ -108,6 +113,7 @@ export type MutationUploadFileArgs = {
export type Query = {
__typename?: 'Query';
dataForLayer?: Maybe<DataForLayer>;
getCurrentTime?: Maybe<Scalars['String']['output']>;
getError?: Maybe<Scalars['Boolean']['output']>;
getRequestHeader?: Maybe<Scalars['String']['output']>;
Expand Down Expand Up @@ -415,6 +421,11 @@ export type Scalars = {
Upload: { input: any; output: any; }
};
export type DataForLayer = {
__typename?: 'DataForLayer';
text?: Maybe<Scalars['String']['output']>;
};
export type FormSubmission = {
__typename?: 'FormSubmission';
documents?: Maybe<Array<Maybe<FormSubmissionDocument>>>;
Expand Down Expand Up @@ -472,6 +483,7 @@ export type MutationUploadFileArgs = {
export type Query = {
__typename?: 'Query';
dataForLayer?: Maybe<DataForLayer>;
getCurrentTime?: Maybe<Scalars['String']['output']>;
getError?: Maybe<Scalars['Boolean']['output']>;
getRequestHeader?: Maybe<Scalars['String']['output']>;
Expand Down Expand Up @@ -635,6 +647,11 @@ export type Scalars = {
Upload: { input: any; output: any; }
};
export type DataForLayer = {
__typename?: 'DataForLayer';
text?: Maybe<Scalars['String']['output']>;
};
export type FormSubmission = {
__typename?: 'FormSubmission';
documents?: Maybe<Array<Maybe<FormSubmissionDocument>>>;
Expand Down Expand Up @@ -692,6 +709,7 @@ export type MutationUploadFileArgs = {
export type Query = {
__typename?: 'Query';
dataForLayer?: Maybe<DataForLayer>;
getCurrentTime?: Maybe<Scalars['String']['output']>;
getError?: Maybe<Scalars['Boolean']['output']>;
getRequestHeader?: Maybe<Scalars['String']['output']>;
Expand Down
5 changes: 1 addition & 4 deletions test/helpers/generate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,7 @@ vi.mock('@nuxt/kit', async () => {
describe('generate', () => {
const srcDir = path.resolve(__dirname, './../../playground')
const resolver = createResolver(srcDir).resolve
const schemaPath = path.resolve(
__dirname,
'./../../playground/schema.graphql',
)
const schemaPath = path.resolve(__dirname, './../../schema.graphql')

test('Generates templates correctly for auto imported documents', async () => {
const result = await generate(
Expand Down
2 changes: 1 addition & 1 deletion test/helpers/getSchemaPath.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import path from 'path'
import { afterEach, describe, expect, test, vi } from 'vitest'
import { getSchemaPath } from '../../src/helpers'
const schemaPath = path.resolve(__dirname, './../../playground/schema.graphql')
const schemaPath = path.resolve(__dirname, './../../schema.graphql')

vi.mock('./../../src/codegen/index', async () => {
const codegen: any = await vi.importActual('./../../src/codegen/index')
Expand Down

0 comments on commit 214a4ca

Please sign in to comment.