Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Issue #3336148: Add support for forms #247

Merged
merged 10 commits into from
Aug 28, 2024
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@
"dist",
"playground/components",
"playground/pages",
"playground/app.vue"
"playground/app.vue",
"playground/middleware"
],
"scripts": {
"prepack": "nuxt-module-build",
Expand Down
14 changes: 14 additions & 0 deletions playground/components/global/DrupalForm.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<template>
<form :formId="formId" :method="method" v-bind="attributes" :action="useRoute().fullPath" class="drupal-form">
<slot><div v-html="content" /></slot>
</form>
</template>

<script setup lang="ts">
const props = defineProps<{
formId: String,
attributes: Object,
method: String,
content?: String,
}>()
</script>
34 changes: 34 additions & 0 deletions playground/middleware/formHandler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { readFormData, createError } from 'h3'
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

let's rename this file to "drupalFormHandler" to clarify it's only about the drupal-form, not every form.

Also I'm wondering whether we can declare the middleware in a way it is NOT shipped in the client bundle? This codes never ever needs to run on the client, so it seems to be silly to have it there. Would using server-middleware instead of route middleware be an option that helps us there?
https://nuxt.com/docs/guide/directory-structure/server#server-middleware

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've moved it to server middleware which is global(cannot be imported in page, which should be fine)

but also as a page middleware, when using import.meta.server the code doesn't leak into client bundle

import { useRuntimeConfig, useRequestEvent } from '#imports'

export default defineNuxtRouteMiddleware(async (from) => {
if (import.meta.server) {
const runtimeConfig = useRuntimeConfig()
const event = useRequestEvent()
const { ceApiEndpoint } = runtimeConfig.public.drupalCe
const drupalBaseUrl = getDrupalBaseUrl()

if (event?.node?.req?.method === 'POST') {
const formData = await readFormData(event)

if (formData) {
const targetUrl = from.fullPath
const response = await $fetch.raw(drupalBaseUrl + ceApiEndpoint + targetUrl, {
method: 'POST',
body: formData,
})

event.context.drupalCeCustomPageResponse = {
_data: response._data,
headers: Object.fromEntries(response.headers.entries()),
}
} else {
throw createError({
statusCode: 400,
statusMessage: 'Bad Request',
message: 'The request contains invalid form data or no form data at all.',
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's say

"No or invalid form data given. See drupalFormHandler."

})
}
}
}
})
16 changes: 0 additions & 16 deletions playground/middleware/redirect.global.ts

This file was deleted.

1 change: 1 addition & 0 deletions playground/pages/[...slug].vue
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ const page = await fetchPage(useRoute().path, { query: useRoute().query })
// Set to false to support custom layouts, using <NuxtLayout> instead.
definePageMeta({
layout: false,
middleware: 'form-handler',
})
const layout = computed(() => {
return page.value.page_layout || 'default'
Expand Down
3 changes: 1 addition & 2 deletions src/module.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { fileURLToPath } from 'url'
import { defineNuxtModule, addPlugin, addServerPlugin, createResolver, addImportsDir, addServerHandler } from '@nuxt/kit'
import { defineNuxtModule, addServerPlugin, createResolver, addImportsDir, addServerHandler } from '@nuxt/kit'
import { defu } from 'defu'
import type { NuxtOptionsWithDrupalCe } from './types'

Expand Down Expand Up @@ -59,7 +59,6 @@ export default defineNuxtModule<ModuleOptions>({
const { resolve } = createResolver(import.meta.url)
const runtimeDir = fileURLToPath(new URL('./runtime', import.meta.url))
nuxt.options.build.transpile.push(runtimeDir)
addPlugin(resolve(runtimeDir, 'plugin'))
if (options.serverLogLevel) {
addServerPlugin(resolve(runtimeDir, 'server/plugins/errorLogger'))
}
Expand Down
35 changes: 28 additions & 7 deletions src/runtime/composables/useDrupalCe/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { appendResponseHeader } from 'h3'
import type { UseFetchOptions } from '#app'
import type { $Fetch, NitroFetchRequest } from 'nitropack'
import { getDrupalBaseUrl, getMenuBaseUrl } from './server'
import { useRuntimeConfig, useState, useFetch, navigateTo, createError, h, resolveComponent, setResponseStatus, useNuxtApp, useRequestHeaders, ref, watch } from '#imports'
import { useRuntimeConfig, useState, useFetch, navigateTo, createError, h, resolveComponent, setResponseStatus, useNuxtApp, useRequestHeaders, ref, watch, useRequestEvent } from '#imports'

export const useDrupalCe = () => {
const config = useRuntimeConfig().public.drupalCe
Expand Down Expand Up @@ -116,9 +116,32 @@ export const useDrupalCe = () => {
page_layout: 'default',
title: '',
}))
const serverResponse = useState('server-response', () => null)
useFetchOptions.key = `page-${path}`
const page = ref(null)
const pageError = ref(null)

const { data: page, error } = await useCeApi(path, useFetchOptions, true)
if (import.meta.server) {
serverResponse.value = useRequestEvent(nuxtApp).context.drupalCeCustomPageResponse
}

// Check if the page data is already provided, e.g. by a form response.
if (serverResponse.value && serverResponse.value._data) {
page.value = serverResponse.value._data
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this never sets pageErrror like the other if part. does it actually handle error codes correctly?

passThroughHeaders(nuxtApp, serverResponse.value.headers)
// Clear the server response state after it was sent to the client.
if (import.meta.client) {
serverResponse.value = null
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm still not 100% convinced we need serverResponse for hydrating things, since page should be already hydrated. But let's merge and re-check things once we have it merged and working.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tested and ensured it's not double-hydrated. maybe code could be nicer, but that seems all good!

}
} else {
const { data, error } = await useCeApi(path, useFetchOptions, true)
page.value = data.value
pageError.value = error.value
}

if (page.value?.messages) {
pushMessagesToState(page.value.messages)
}

if (page?.value?.redirect) {
await callWithNuxt(nuxtApp, navigateTo, [
Expand All @@ -128,13 +151,11 @@ export const useDrupalCe = () => {
return pageState
}

if (error.value) {
overrideErrorHandler ? overrideErrorHandler(error) : pageErrorHandler(error, { config, nuxtApp })
page.value = error.value?.data
if (pageError.value) {
overrideErrorHandler ? overrideErrorHandler(pageError) : pageErrorHandler(pageError, { config, nuxtApp })
page.value = pageError.value?.data
}

page.value?.messages && pushMessagesToState(page.value.messages)

pageState.value = page
return page
}
Expand Down
4 changes: 0 additions & 4 deletions src/runtime/plugin.ts

This file was deleted.